Skip to main content

rustysan_sword/
component.rs

1//! Typed components: props structs that serde fills from a component tag.
2use minijinja::Value;
3use serde::{
4    Deserialize, Deserializer, Serialize, Serializer,
5    de::{self, DeserializeOwned},
6    forward_to_deserialize_any,
7    ser::SerializeMap,
8};
9use std::{collections::HashMap, fmt, sync::Arc};
10
11/// A failure while registering or preparing a typed component.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct ComponentError {
14    message: String,
15}
16
17impl ComponentError {
18    /// Create an error from a message for the template author.
19    pub fn new(message: impl Into<String>) -> Self {
20        Self {
21            message: message.into(),
22        }
23    }
24}
25
26impl fmt::Display for ComponentError {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        f.write_str(&self.message)
29    }
30}
31
32impl std::error::Error for ComponentError {}
33
34/// A component whose props are a Rust struct.
35///
36/// The struct is filled from the tag's attributes by serde and read by the component
37/// template as plain variables, one per field. See [`crate::Sword::with_component`].
38pub trait Component: DeserializeOwned + Serialize + 'static {
39    /// Make an attribute that is not a field an error instead of an HTML attribute.
40    const STRICT_ATTRIBUTES: bool = false;
41
42    /// Fill derived values after deserialization. It runs synchronously on the render
43    /// thread, so it must not block.
44    fn prepare(self) -> Result<Self, ComponentError> {
45        Ok(self)
46    }
47}
48
49/// Trusted markup in a prop. A plain `String` is always escaped when printed; an `Html`
50/// field is printed as it is, like [`View::with_html`](https://docs.rs/laravel-rust) data.
51#[derive(Debug, Clone, PartialEq, Eq, Default)]
52pub struct Html(String);
53
54impl Html {
55    /// Mark markup as trusted.
56    pub fn new(markup: impl Into<String>) -> Self {
57        Self(markup.into())
58    }
59    /// The markup.
60    pub fn as_str(&self) -> &str {
61        &self.0
62    }
63    /// Take the markup.
64    pub fn into_string(self) -> String {
65        self.0
66    }
67}
68
69impl From<String> for Html {
70    fn from(markup: String) -> Self {
71        Self(markup)
72    }
73}
74
75impl From<&str> for Html {
76    fn from(markup: &str) -> Self {
77        Self(markup.to_owned())
78    }
79}
80
81/// A per-process key that view data cannot guess, so data cannot pose as trusted markup.
82fn marker() -> &'static str {
83    static MARKER: std::sync::OnceLock<String> = std::sync::OnceLock::new();
84    MARKER.get_or_init(|| {
85        use std::hash::{BuildHasher, Hasher};
86        let token = std::collections::hash_map::RandomState::new()
87            .build_hasher()
88            .finish();
89        format!("__sword_html_{token:016x}")
90    })
91}
92
93impl Serialize for Html {
94    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
95        let mut map = serializer.serialize_map(Some(1))?;
96        map.serialize_entry(marker(), &self.0)?;
97        map.end()
98    }
99}
100
101impl<'de> Deserialize<'de> for Html {
102    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
103        String::deserialize(deserializer).map(Self)
104    }
105}
106
107/// Turn serialized props into template values, restoring trusted markup.
108pub(crate) fn to_value(json: serde_json::Value) -> Value {
109    match json {
110        serde_json::Value::Object(map) if map.len() == 1 && map.contains_key(marker()) => {
111            match map.into_iter().next() {
112                Some((_, serde_json::Value::String(markup))) => Value::from_safe_string(markup),
113                _ => Value::UNDEFINED,
114            }
115        }
116        serde_json::Value::Object(map) => {
117            Value::from_iter(map.into_iter().map(|(key, value)| (key, to_value(value))))
118        }
119        serde_json::Value::Array(items) => {
120            Value::from(items.into_iter().map(to_value).collect::<Vec<_>>())
121        }
122        serde_json::Value::Null => Value::from(()),
123        serde_json::Value::Bool(flag) => Value::from(flag),
124        serde_json::Value::String(text) => Value::from(text),
125        // Read numbers by value: with serde_json's `arbitrary_precision`, which another crate
126        // in the build may enable, serializing a `Number` yields a private map instead.
127        serde_json::Value::Number(number) => number
128            .as_i64()
129            .map(Value::from)
130            .or_else(|| number.as_u64().map(Value::from))
131            .or_else(|| number.as_f64().map(Value::from))
132            .unwrap_or(Value::UNDEFINED),
133    }
134}
135
136/// Records the field list a derived `Deserialize` hands to `deserialize_struct`.
137struct Probe<'a> {
138    fields: &'a mut Option<Vec<&'static str>>,
139}
140
141#[derive(Debug)]
142struct Stop;
143
144impl fmt::Display for Stop {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        f.write_str("probe stopped")
147    }
148}
149impl std::error::Error for Stop {}
150impl de::Error for Stop {
151    fn custom<T: fmt::Display>(_: T) -> Self {
152        Stop
153    }
154}
155
156impl<'de> Deserializer<'de> for Probe<'_> {
157    type Error = Stop;
158    fn deserialize_any<V: de::Visitor<'de>>(self, _: V) -> Result<V::Value, Stop> {
159        Err(Stop)
160    }
161    fn deserialize_struct<V: de::Visitor<'de>>(
162        self,
163        _name: &'static str,
164        fields: &'static [&'static str],
165        _visitor: V,
166    ) -> Result<V::Value, Stop> {
167        *self.fields = Some(fields.to_vec());
168        Err(Stop)
169    }
170    forward_to_deserialize_any! {
171        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
172        option unit unit_struct newtype_struct seq tuple tuple_struct map enum identifier
173        ignored_any
174    }
175}
176
177fn fields_of<T: DeserializeOwned>(component: &str) -> Result<Vec<&'static str>, ComponentError> {
178    let mut fields = None;
179    let _ = T::deserialize(Probe {
180        fields: &mut fields,
181    });
182    let fields = fields.ok_or_else(|| {
183        ComponentError::new(format!(
184            "component `{component}` must be a struct with named fields and no #[serde(flatten)]"
185        ))
186    })?;
187    for field in &fields {
188        let valid = field
189            .chars()
190            .next()
191            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
192            && field.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
193            && !field.starts_with("__sword")
194            && !matches!(*field, "slot" | "attributes" | "loop");
195        if !valid {
196            return Err(ComponentError::new(format!(
197                "component `{component}` has field `{field}`, which cannot be a template variable"
198            )));
199        }
200    }
201    Ok(fields)
202}
203
204type Build = dyn Fn(serde_json::Value) -> Result<Value, String> + Send + Sync;
205
206/// One registered component.
207#[derive(Clone)]
208pub(crate) struct Typed {
209    pub fields: Vec<&'static str>,
210    pub strict: bool,
211    build: Arc<Build>,
212}
213
214/// The immutable set of typed components of one engine.
215#[derive(Clone, Default)]
216pub(crate) struct Components(HashMap<String, Typed>);
217
218impl fmt::Debug for Components {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        f.debug_list().entries(self.0.keys()).finish()
221    }
222}
223
224impl Components {
225    pub fn get(&self, name: &str) -> Option<&Typed> {
226        self.0.get(name)
227    }
228
229    pub fn register<T: Component>(&mut self, name: &str) -> Result<(), ComponentError> {
230        if !crate::valid_name(name) {
231            return Err(ComponentError::new(format!(
232                "invalid component name `{name}`"
233            )));
234        }
235        if self.0.contains_key(name) {
236            return Err(ComponentError::new(format!(
237                "component `{name}` is already registered"
238            )));
239        }
240        let fields = fields_of::<T>(name)?;
241        let build = |json: serde_json::Value| -> Result<Value, String> {
242            let component: T = serde_json::from_value(json).map_err(|error| {
243                let message = error.to_string();
244                if message.contains("invalid type: string") {
245                    format!(
246                        "{message} (a literal attribute is a string; write :name=\"...\" to pass a number or boolean)"
247                    )
248                } else {
249                    message
250                }
251            })?;
252            let component = component.prepare().map_err(|error| error.message)?;
253            let json = serde_json::to_value(&component).map_err(|error| error.to_string())?;
254            Ok(to_value(json))
255        };
256        self.0.insert(
257            name.to_owned(),
258            Typed {
259                fields,
260                strict: T::STRICT_ATTRIBUTES,
261                build: Arc::new(build),
262            },
263        );
264        Ok(())
265    }
266
267    /// Build a component's props from the attributes the tag supplied.
268    pub fn build(&self, name: &str, given: Value) -> Result<Value, minijinja::Error> {
269        let fail = |message: String| {
270            minijinja::Error::new(
271                minijinja::ErrorKind::InvalidOperation,
272                format!("<x-{name}>: {message}"),
273            )
274        };
275        let typed = self
276            .get(name)
277            .ok_or_else(|| fail("is not a registered component".to_owned()))?;
278        let json = serde_json::to_value(&given).map_err(|error| fail(error.to_string()))?;
279        (typed.build)(json).map_err(fail)
280    }
281}