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 for a dynamic HTML Boolean attribute such as `+disabled`.
20#[diagnostic::on_unimplemented(
21    message = "`{Self}` is not a `bool`, so it cannot decide a Boolean attribute",
22    label = "a Boolean attribute is present for `true` and omitted for `false` or `None`",
23    note = "a string such as `\"false\"` is not false; convert the value to `bool` first"
24)]
25pub trait BooleanAttribute {
26    /// Whether the attribute is present.
27    fn present(&self) -> bool;
28}
29
30impl BooleanAttribute for bool {
31    fn present(&self) -> bool {
32        *self
33    }
34}
35
36impl<T: BooleanAttribute + ?Sized> BooleanAttribute for &T {
37    fn present(&self) -> bool {
38        (**self).present()
39    }
40}
41
42/// A value supported by HTML `+hidden` bindings.
43///
44/// Booleans toggle presence; strings preserve the enumerated attribute value.
45/// Generic templates must require this capability, not merely `Display`:
46/// stringifying a Boolean would make `false` hide the element too.
47pub trait HiddenAttribute {
48    /// Return the typed attribute state without allocating or escaping it yet.
49    fn hidden_value(&self) -> HiddenValue<'_>;
50}
51
52impl HiddenAttribute for bool {
53    fn hidden_value(&self) -> HiddenValue<'_> {
54        if *self {
55            HiddenValue::Present
56        } else {
57            HiddenValue::Omitted
58        }
59    }
60}
61
62impl HiddenAttribute for str {
63    fn hidden_value(&self) -> HiddenValue<'_> {
64        HiddenValue::Value(self)
65    }
66}
67
68impl HiddenAttribute for String {
69    fn hidden_value(&self) -> HiddenValue<'_> {
70        self.as_str().hidden_value()
71    }
72}
73
74impl<T: HiddenAttribute + ?Sized> HiddenAttribute for &T {
75    fn hidden_value(&self) -> HiddenValue<'_> {
76        (**self).hidden_value()
77    }
78}
79
80impl<T: HiddenAttribute + ?Sized> HiddenAttribute for &mut T {
81    fn hidden_value(&self) -> HiddenValue<'_> {
82        (**self).hidden_value()
83    }
84}
85
86/// Render an HTML hidden binding, preserving the template's attribute casing.
87/// `name` is the trusted, ASCII-case-insensitive `hidden` spelling from codegen.
88#[doc(hidden)]
89pub fn render_hidden<T: HiddenAttribute + ?Sized>(
90    value: &T,
91    name: &str,
92    buf: &mut dyn fmt::Write,
93) -> Result<(), RenderError> {
94    match value.hidden_value() {
95        HiddenValue::Omitted => {}
96        HiddenValue::Present => {
97            buf.write_str(" ")?;
98            buf.write_str(name)?;
99        }
100        HiddenValue::Value(text) => {
101            write!(buf, " {name}=\"{}\"", HtmlEscape(text))?;
102        }
103    }
104    Ok(())
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    fn render(value: &(impl HiddenAttribute + ?Sized)) -> String {
112        let mut buf = String::new();
113        render_hidden(value, "hidden", &mut buf).unwrap();
114        buf
115    }
116
117    #[test]
118    fn booleans_and_strings_keep_distinct_hidden_states() {
119        assert_eq!(render(&false), "");
120        assert_eq!(render(&true), " hidden");
121        for text in ["until-found", "false", "true", ""] {
122            assert_eq!(render(text), alloc::format!(" hidden=\"{text}\""));
123        }
124        assert_eq!(render("<&>\"'"), " hidden=\"&lt;&amp;&gt;&quot;&#x27;\"");
125    }
126
127    #[test]
128    fn references_and_owned_strings_forward_without_reclassification() {
129        let mut boolean = false;
130        assert_eq!(render(&&&boolean), "");
131        assert_eq!(render(&&mut boolean), "");
132        assert_eq!(render(&String::from("false")), " hidden=\"false\"");
133        assert_eq!(
134            render(&&String::from("until-found")),
135            " hidden=\"until-found\""
136        );
137    }
138
139    #[test]
140    fn hidden_rendering_preserves_name_case_and_propagates_writer_errors() {
141        struct Failing;
142        impl fmt::Write for Failing {
143            fn write_str(&mut self, _: &str) -> fmt::Result {
144                Err(fmt::Error)
145            }
146        }
147        let mut output = String::new();
148        render_hidden(&true, "HIDDEN", &mut output).unwrap();
149        assert_eq!(output, " HIDDEN");
150        assert!(render_hidden(&true, "hidden", &mut Failing).is_err());
151        assert!(render_hidden("until-found", "hidden", &mut Failing).is_err());
152        assert!(render_hidden(&false, "hidden", &mut Failing).is_ok());
153    }
154}