1use crate::template::{Error, Kind};
3use std::fmt::Write;
4
5macro_rules! part {
6 ($name:ident) => {
7 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8 pub struct $name(pub &'static str);
9 impl $name {
10 pub const fn new(name: &'static str) -> Self {
11 Self(name)
12 }
13 }
14 };
15}
16part!(Field);
17part!(Click);
18part!(Outlet);
19
20#[derive(Clone, Copy, Debug)]
21pub enum Attribute {
22 Static(&'static str, &'static str),
23 Field(&'static str, Field),
24 Click(Click),
25 Children(Outlet),
26 Class(&'static str, Field),
27}
28#[derive(Clone, Copy, Debug)]
29pub enum Node {
30 Element {
31 tag: &'static str,
32 attrs: &'static [Attribute],
33 children: &'static [Node],
34 },
35 Text(&'static str),
36 Field(Field),
37 Outlet(Outlet),
38}
39#[derive(Debug)]
40pub struct Template {
41 roots: &'static [Node],
42 compiled: std::sync::OnceLock<Result<std::sync::Arc<Compiled>, Error>>,
43}
44impl Template {
45 pub fn roots(&self) -> &'static [Node] {
46 self.roots
47 }
48 pub const fn new(roots: &'static [Node]) -> Self {
49 Self {
50 roots,
51 compiled: std::sync::OnceLock::new(),
52 }
53 }
54 pub fn cached(&self) -> Result<std::sync::Arc<Compiled>, Error> {
55 self.compiled
56 .get_or_init(|| self.compile().map(std::sync::Arc::new))
57 .clone()
58 }
59}
60pub const fn element(
61 tag: &'static str,
62 attrs: &'static [Attribute],
63 children: &'static [Node],
64) -> Node {
65 Node::Element {
66 tag,
67 attrs,
68 children,
69 }
70}
71pub const fn div(attrs: &'static [Attribute], children: &'static [Node]) -> Node {
72 element("div", attrs, children)
73}
74pub const fn span(attrs: &'static [Attribute], children: &'static [Node]) -> Node {
75 element("span", attrs, children)
76}
77pub const fn button(attrs: &'static [Attribute], children: &'static [Node]) -> Node {
78 element("button", attrs, children)
79}
80pub const fn text(value: &'static str) -> Node {
81 Node::Text(value)
82}
83pub const fn field(value: Field) -> Node {
84 Node::Field(value)
85}
86pub const fn outlet(value: Outlet) -> Node {
87 Node::Outlet(value)
88}
89pub const fn attr(name: &'static str, value: &'static str) -> Attribute {
90 Attribute::Static(name, value)
91}
92pub const fn class(value: &'static str) -> Attribute {
93 attr("class", value)
94}
95pub const fn bind_attr(name: &'static str, value: Field) -> Attribute {
96 Attribute::Field(name, value)
97}
98pub const fn on_click(value: Click) -> Attribute {
99 Attribute::Click(value)
100}
101pub const fn children(value: Outlet) -> Attribute {
102 Attribute::Children(value)
103}
104pub const fn toggle_class(token: &'static str, value: Field) -> Attribute {
105 Attribute::Class(token, value)
106}
107
108#[derive(Clone, Debug)]
109pub struct Slot {
110 pub name: Option<&'static str>,
111 pub kind: Kind,
112}
113#[derive(Clone, Debug)]
115pub struct Compiled {
116 pub wire: String,
117 pub slots: Vec<Slot>,
118 pub node_count: usize,
119 pub paths: Vec<Vec<u16>>,
120}
121fn string(out: &mut String, value: &str) {
122 out.push('"');
123 for c in value.chars() {
124 match c {
125 '"' => out.push_str("\\\""),
126 '\\' => out.push_str("\\\\"),
127 c if c < ' ' => {
128 write!(out, "\\u{:04x}", c as u32).unwrap();
129 }
130 c => out.push(c),
131 }
132 }
133 out.push('"');
134}
135impl Compiled {
136 pub fn slot(&self, name: &str) -> Option<(u16, Kind)> {
137 self.slots
138 .iter()
139 .enumerate()
140 .find(|(_, s)| s.name == Some(name))
141 .map(|(i, s)| (i as u16, s.kind))
142 }
143}
144impl Template {
145 pub fn compile(&self) -> Result<Compiled, Error> {
146 struct Compiler {
147 roots: String,
148 targets: Vec<(Vec<u16>, Slot)>,
149 nodes: usize,
150 bytes: usize,
151 }
152 impl Compiler {
153 fn slot(&mut self, path: &[u16], name: &'static str, kind: Kind) -> Result<(), Error> {
154 if name.is_empty()
155 || name.len() > 128
156 || self.targets.len() >= 256
157 || self.targets.iter().any(|(_, t)| t.name == Some(name))
158 {
159 return Err(Error("empty, duplicate or over-budget slot name"));
160 }
161 self.bytes += name.len();
162 self.targets.push((
163 path.to_vec(),
164 Slot {
165 name: Some(name),
166 kind,
167 },
168 ));
169 Ok(())
170 }
171 fn nodes(
172 &mut self,
173 nodes: &[Node],
174 path: &mut Vec<u16>,
175 parent: Option<&str>,
176 in_button: bool,
177 ) -> Result<(), Error> {
178 if path.len() > 64 {
179 return Err(Error("template depth budget"));
180 }
181 self.roots.push('[');
182 for (index, node) in nodes.iter().enumerate() {
183 self.nodes += 1;
184 if self.nodes > 256 {
185 return Err(Error("template node budget"));
186 }
187 if index > 0 {
188 self.roots.push(',');
189 }
190 path.push(index as u16);
191 match node {
192 Node::Text(value) => {
193 if parent.is_some_and(|p| matches!(p, "table" | "tbody" | "tr"))
194 && !value.trim().is_empty()
195 {
196 return Err(Error("table structure cannot contain direct text"));
197 }
198 self.bytes += value.len();
199 self.roots.push_str("[0,");
200 string(&mut self.roots, value);
201 self.roots.push(']');
202 }
203 Node::Field(value) => {
204 if parent.is_some_and(|p| matches!(p, "table" | "tbody" | "tr")) {
205 return Err(Error("table structure cannot contain text fields"));
206 }
207 self.slot(path, value.0, Kind::Text)?;
208 self.roots.push_str("[0,\"\"]");
209 }
210 Node::Outlet(value) => {
211 if parent.is_some_and(|p| !matches!(p, "div" | "tbody" | "td")) {
212 return Err(Error(
213 "dynamic outlets require a div parent in this profile",
214 ));
215 }
216 self.slot(path, value.0, Kind::Range)?;
217 if path.len() == 1 {
218 self.nodes += 1;
219 }
220 if self.nodes > 256 {
221 return Err(Error("template node budget"));
222 }
223 self.roots.push_str("[2]");
224 }
225 Node::Element {
226 tag,
227 attrs,
228 children,
229 } => {
230 if attrs.iter().any(|a| matches!(a, Attribute::Class(..)))
231 && attrs
232 .iter()
233 .any(|a| matches!(a, Attribute::Field("class", _)))
234 {
235 return Err(Error(
236 "class toggles cannot share a dynamic whole class attribute",
237 ));
238 }
239 if !crate::template::context(parent, tag, in_button) {
240 return Err(Error("unsupported HTML tag or content context"));
241 }
242 self.roots.push_str("[1,");
243 string(&mut self.roots, tag);
244 self.roots.push_str(",[");
245 let mut names = Vec::new();
246 let mut written = 0;
247 let mut toggles = Vec::new();
248 for attribute in *attrs {
249 match *attribute {
250 Attribute::Static(name, value) => {
251 if !crate::template::attribute(name)
252 || !name
253 .bytes()
254 .all(|b| b.is_ascii_lowercase() || b == b'-')
255 || names.contains(&name)
256 || (name == "type"
257 && (*tag != "button" || value != "button"))
258 || (name == "disabled" && *tag != "button")
259 {
260 return Err(Error(
261 "unsupported, duplicate or invalid HTML attribute",
262 ));
263 }
264 names.push(name);
265 self.bytes += name.len() + value.len();
266 if written > 0 {
267 self.roots.push(',');
268 }
269 written += 1;
270 self.roots.push('[');
271 string(&mut self.roots, name);
272 self.roots.push(',');
273 string(&mut self.roots, value);
274 self.roots.push(']');
275 }
276 Attribute::Field(name, value) => {
277 if !matches!(name, "class" | "title" | "aria-label")
278 || names.contains(&name)
279 {
280 return Err(Error(
281 "unsupported or duplicate dynamic attribute",
282 ));
283 }
284 names.push(name);
285 self.slot(path, value.0, Kind::Attribute(name))?;
286 }
287 Attribute::Click(value) => {
288 if names.contains(&"on:click") {
289 return Err(Error("duplicate click target"));
290 }
291 names.push("on:click");
292 self.slot(path, value.0, Kind::Click)?;
293 }
294 Attribute::Children(value) => {
295 if !matches!(*tag, "div" | "tbody" | "td")
296 || names.contains(&"children")
297 {
298 return Err(Error(
299 "children outlet requires a div, tbody or td",
300 ));
301 }
302 names.push("children");
303 self.slot(path, value.0, Kind::Children)?;
304 }
305 Attribute::Class(token, value) => {
306 if !crate::template::class_token(token)
307 || toggles.contains(&token)
308 {
309 return Err(Error("invalid or duplicate class token"));
310 }
311 toggles.push(token);
312 self.bytes += token.len();
313 let initial = attrs
314 .iter()
315 .find_map(|a| {
316 if let Attribute::Static("class", value) = a {
317 Some(
318 value
319 .split_ascii_whitespace()
320 .any(|s| s == token),
321 )
322 } else {
323 None
324 }
325 })
326 .unwrap_or(false);
327 self.slot(path, value.0, Kind::Class(token, initial))?;
328 }
329 }
330 }
331 self.roots.push_str("],");
332 self.nodes(children, path, Some(tag), in_button || *tag == "button")?;
333 self.roots.push(']');
334 }
335 }
336 path.pop();
337 if self.bytes > 64 * 1024 {
338 return Err(Error("template string budget"));
339 }
340 }
341 self.roots.push(']');
342 Ok(())
343 }
344 }
345 if self.roots.is_empty() {
346 return Err(Error("empty template"));
347 }
348 let mut c = Compiler {
349 roots: String::new(),
350 targets: Vec::new(),
351 nodes: 0,
352 bytes: 0,
353 };
354 c.nodes(self.roots, &mut Vec::new(), None, false)?;
355 let mut wire = format!("[{},[", c.roots);
356 for (i, (path, slot)) in c.targets.iter().enumerate() {
357 if i > 0 {
358 wire.push(',');
359 }
360 wire.push_str("[[");
361 for (j, index) in path.iter().enumerate() {
362 if j > 0 {
363 wire.push(',');
364 }
365 write!(wire, "{index}").unwrap();
366 }
367 wire.push_str("],");
368 match slot.kind {
369 Kind::Text => wire.push_str("0,null"),
370 Kind::Click => wire.push_str("2,null"),
371 Kind::Children => wire.push_str("3,null"),
372 Kind::Range => wire.push_str("4,null"),
373 Kind::Class(name, _) => {
374 wire.push_str("5,");
375 string(&mut wire, name);
376 }
377 Kind::Attribute(name) => {
378 wire.push_str("1,");
379 string(&mut wire, name);
380 }
381 }
382 wire.push(']');
383 }
384 wire.push_str("]]");
385 Ok(Compiled {
386 wire,
387 node_count: c.nodes,
388 paths: c.targets.iter().map(|(path, _)| path.clone()).collect(),
389 slots: c.targets.into_iter().map(|(_, s)| s).collect(),
390 })
391 }
392}
393
394#[cfg(test)]
395mod tests {
396 use super::*;
397 #[test]
398 fn rejects_duplicate_names_cross_kind_and_ambiguous_attributes_before_wire_creation() {
399 static DUPLICATE: Template = Template::new(&[button(
400 &[on_click(Click::new("same"))],
401 &[field(Field::new("same"))],
402 )]);
403 static ATTR: Template = Template::new(&[div(
404 &[class("a"), bind_attr("class", Field::new("class"))],
405 &[],
406 )]);
407 static CHILDREN: Template = Template::new(&[button(&[children(Outlet::new("body"))], &[])]);
408 static ROOT: Template = Template::new(&[outlet(Outlet::new("root"))]);
409 for template in [&DUPLICATE, &ATTR, &CHILDREN] {
410 assert!(template.compile().is_err());
411 }
412 assert_eq!(ROOT.compile().unwrap().node_count, 2);
413 }
414 #[test]
415 fn named_children_append_after_static_content_in_the_shared_declaration() {
416 static TEMPLATE: Template = Template::new(&[div(
417 &[children(Outlet::new("body"))],
418 &[text("static prefix")],
419 )]);
420 let compiled = TEMPLATE.cached().unwrap();
421 assert_eq!(compiled.node_count, 2);
422 assert_eq!(compiled.slots[0].kind, Kind::Children);
423 assert!(std::sync::Arc::ptr_eq(
424 &compiled,
425 &TEMPLATE.cached().unwrap()
426 ));
427 }
428 #[test]
429 fn named_slot_metadata_is_shared_declaration_data_and_limits_count_physical_nodes() {
430 static SMALL: Template = Template::new(&[div(&[], &[field(Field::new("text"))])]);
431 static LARGE: Template = Template::new(&[div(&[], &[Node::Text("x"); 256])]);
432 let compiled = SMALL.compile().unwrap();
433 assert_eq!(compiled.node_count, 2);
434 assert_eq!(compiled.slot("text"), Some((0, Kind::Text)));
435 assert!(compiled.slot("missing").is_none());
436 assert!(LARGE.compile().is_err());
437 }
438}