rustysan_sword/
component.rs1use 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#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct ComponentError {
14 message: String,
15}
16
17impl ComponentError {
18 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
34pub trait Component: DeserializeOwned + Serialize + 'static {
39 const STRICT_ATTRIBUTES: bool = false;
41
42 fn prepare(self) -> Result<Self, ComponentError> {
45 Ok(self)
46 }
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Default)]
52pub struct Html(String);
53
54impl Html {
55 pub fn new(markup: impl Into<String>) -> Self {
57 Self(markup.into())
58 }
59 pub fn as_str(&self) -> &str {
61 &self.0
62 }
63 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
81fn 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
107pub(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 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
136struct 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#[derive(Clone)]
208pub(crate) struct Typed {
209 pub fields: Vec<&'static str>,
210 pub strict: bool,
211 build: Arc<Build>,
212}
213
214#[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 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}