Skip to main content

hemplate_runtime/
hidden.rs

1//! Typed values for HTML's enumerated `hidden` attribute.
2
3use alloc::string::String;
4use core::fmt;
5
6use crate::{HtmlEscape, RenderError};
7
8/// The output state of an HTML `+hidden` binding.
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum HiddenValue<'a> {
11    /// Omit the attribute (`bool::false`).
12    Omitted,
13    /// Emit the attribute name alone (`bool::true`).
14    Present,
15    /// Emit an escaped string state, including `until-found` or `false`.
16    Value(&'a str),
17}
18
19/// A value supported by HTML `+hidden` bindings.
20///
21/// Booleans toggle presence; strings preserve the enumerated attribute value.
22/// Generic templates must require this capability, not merely `Display`:
23/// stringifying a Boolean would make `false` hide the element too.
24pub trait HiddenAttribute {
25    /// Return the typed attribute state without allocating or escaping it yet.
26    fn hidden_value(&self) -> HiddenValue<'_>;
27}
28
29impl HiddenAttribute for bool {
30    fn hidden_value(&self) -> HiddenValue<'_> {
31        if *self {
32            HiddenValue::Present
33        } else {
34            HiddenValue::Omitted
35        }
36    }
37}
38
39impl HiddenAttribute for str {
40    fn hidden_value(&self) -> HiddenValue<'_> {
41        HiddenValue::Value(self)
42    }
43}
44
45impl HiddenAttribute for String {
46    fn hidden_value(&self) -> HiddenValue<'_> {
47        self.as_str().hidden_value()
48    }
49}
50
51impl<T: HiddenAttribute + ?Sized> HiddenAttribute for &T {
52    fn hidden_value(&self) -> HiddenValue<'_> {
53        (**self).hidden_value()
54    }
55}
56
57impl<T: HiddenAttribute + ?Sized> HiddenAttribute for &mut T {
58    fn hidden_value(&self) -> HiddenValue<'_> {
59        (**self).hidden_value()
60    }
61}
62
63/// Render an HTML hidden binding, preserving the template's attribute casing.
64/// `name` is the trusted, ASCII-case-insensitive `hidden` spelling from codegen.
65#[doc(hidden)]
66pub fn render_hidden<T: HiddenAttribute + ?Sized>(
67    value: &T,
68    name: &str,
69    buf: &mut dyn fmt::Write,
70) -> Result<(), RenderError> {
71    match value.hidden_value() {
72        HiddenValue::Omitted => {}
73        HiddenValue::Present => {
74            buf.write_str(" ")?;
75            buf.write_str(name)?;
76        }
77        HiddenValue::Value(text) => {
78            write!(buf, " {name}=\"{}\"", HtmlEscape(text))?;
79        }
80    }
81    Ok(())
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    fn render(value: &(impl HiddenAttribute + ?Sized)) -> String {
89        let mut buf = String::new();
90        render_hidden(value, "hidden", &mut buf).unwrap();
91        buf
92    }
93
94    #[test]
95    fn booleans_and_strings_keep_distinct_hidden_states() {
96        assert_eq!(render(&false), "");
97        assert_eq!(render(&true), " hidden");
98        for text in ["until-found", "false", "true", ""] {
99            assert_eq!(render(text), alloc::format!(" hidden=\"{text}\""));
100        }
101        assert_eq!(render("<&>\"'"), " hidden=\"&lt;&amp;&gt;&quot;&#x27;\"");
102    }
103
104    #[test]
105    fn references_and_owned_strings_forward_without_reclassification() {
106        let mut boolean = false;
107        assert_eq!(render(&&&boolean), "");
108        assert_eq!(render(&&mut boolean), "");
109        assert_eq!(render(&String::from("false")), " hidden=\"false\"");
110        assert_eq!(
111            render(&&String::from("until-found")),
112            " hidden=\"until-found\""
113        );
114    }
115
116    #[test]
117    fn hidden_rendering_preserves_name_case_and_propagates_writer_errors() {
118        struct Failing;
119        impl fmt::Write for Failing {
120            fn write_str(&mut self, _: &str) -> fmt::Result {
121                Err(fmt::Error)
122            }
123        }
124        let mut output = String::new();
125        render_hidden(&true, "HIDDEN", &mut output).unwrap();
126        assert_eq!(output, " HIDDEN");
127        assert!(render_hidden(&true, "hidden", &mut Failing).is_err());
128        assert!(render_hidden("until-found", "hidden", &mut Failing).is_err());
129        assert!(render_hidden(&false, "hidden", &mut Failing).is_ok());
130    }
131}