Skip to main content

glory_html/
display.rs

1//! Shared template-instance data. Static elements have no semantic identities.
2use crate::{
3    template::Kind,
4    view::{Attribute, Compiled, Node, Template},
5};
6use glory_render::{Error, NodeId};
7use std::{
8    cell::{Cell, RefCell},
9    collections::BTreeMap,
10    rc::{Rc, Weak},
11    sync::Arc,
12};
13
14#[derive(Clone, Debug, PartialEq, Eq)]
15pub enum Value {
16    Text(String),
17    Flag(bool),
18    None,
19}
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub enum Tree {
22    Element {
23        tag: &'static str,
24        attrs: BTreeMap<&'static str, String>,
25        children: Vec<Tree>,
26    },
27    Text(String),
28    Outlet(u16),
29}
30#[derive(Default, Debug)]
31pub struct Queue(RefCell<Vec<NodeId>>);
32impl Queue {
33    pub fn take(&self) -> Vec<NodeId> {
34        std::mem::take(&mut *self.0.borrow_mut())
35    }
36}
37#[derive(Debug)]
38pub struct Frame {
39    template: &'static Template,
40    compiled: Arc<Compiled>,
41    values: RefCell<Vec<Value>>,
42    changed: RefCell<BTreeMap<u16, Value>>,
43    queue: RefCell<Option<(Weak<Queue>, NodeId)>>,
44    queued: Cell<bool>,
45}
46#[derive(Clone, Debug)]
47pub enum Placement {
48    Root(Rc<Frame>),
49    Outlet { frame: Rc<Frame>, slot: u16 },
50}
51impl PartialEq for Placement {
52    fn eq(&self, other: &Self) -> bool {
53        match (self, other) {
54            (Self::Root(a), Self::Root(b)) => Rc::ptr_eq(a, b),
55            (Self::Outlet { frame: a, slot: x }, Self::Outlet { frame: b, slot: y }) => {
56                Rc::ptr_eq(a, b) && x == y
57            }
58            _ => false,
59        }
60    }
61}
62impl Eq for Placement {}
63impl Frame {
64    pub fn compiled(&self) -> &Compiled {
65        &self.compiled
66    }
67    pub fn phrasing(&self) -> bool {
68        fn nodes(input: &[Node]) -> bool {
69            input.iter().all(|node| match node {
70                Node::Text(_) | Node::Field(_) => true,
71                Node::Element {
72                    tag: "span",
73                    attrs,
74                    children,
75                } => {
76                    attrs
77                        .iter()
78                        .all(|attr| !matches!(attr, Attribute::Children(_)))
79                        && nodes(children)
80                }
81                _ => false,
82            })
83        }
84        nodes(self.template.roots())
85    }
86    pub fn context(&self, slot: u16) -> Option<&'static str> {
87        let path = self.compiled.paths.get(slot as usize)?;
88        let path = if self.compiled.slots[slot as usize].kind == Kind::Children {
89            path.as_slice()
90        } else {
91            path.get(..path.len().checked_sub(1)?)?
92        };
93        let (first, rest) = path.split_first()?;
94        let mut node = self.template.roots().get(*first as usize)?;
95        for index in rest {
96            let Node::Element { children, .. } = node else {
97                return None;
98            };
99            node = children.get(*index as usize)?;
100        }
101        if let Node::Element { tag, .. } = node {
102            Some(tag)
103        } else {
104            None
105        }
106    }
107    pub fn accepts(&self, parent: &str) -> bool {
108        if matches!(
109            parent,
110            "p" | "span" | "button" | "a" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6"
111        ) {
112            return self.phrasing();
113        }
114        self.template.roots().iter().all(|node| match node {
115            Node::Text(text) => {
116                !matches!(parent, "table" | "tbody" | "tr") || text.trim().is_empty()
117            }
118            Node::Field(_) => !matches!(parent, "table" | "tbody" | "tr"),
119            Node::Outlet(_) => true,
120            Node::Element { tag, .. } => crate::template::context(Some(parent), tag, false),
121        })
122    }
123    pub fn new(template: &'static Template) -> Result<Rc<Self>, Error> {
124        let compiled = template
125            .cached()
126            .map_err(|e| Error::Backend(e.to_string()))?;
127        let values = compiled
128            .slots
129            .iter()
130            .map(|slot| match slot.kind {
131                Kind::Text | Kind::Attribute(_) => Value::Text(String::new()),
132                Kind::Class(_, initial) => Value::Flag(initial),
133                _ => Value::None,
134            })
135            .collect();
136        Ok(Rc::new(Self {
137            template,
138            compiled,
139            values: RefCell::new(values),
140            changed: RefCell::new(BTreeMap::new()),
141            queue: RefCell::new(None),
142            queued: Cell::new(false),
143        }))
144    }
145    pub fn slot(&self, name: &str) -> Result<(u16, Kind), Error> {
146        self.compiled
147            .slot(name)
148            .ok_or(Error::InvalidProps("unknown display slot"))
149    }
150    pub fn value(&self, slot: u16) -> Result<Value, Error> {
151        self.values
152            .borrow()
153            .get(slot as usize)
154            .cloned()
155            .ok_or(Error::InvalidProps("display slot"))
156    }
157    pub fn text(&self, slot: u16, text: String) -> Result<(), Error> {
158        if text.len() > 65536 {
159            return Err(Error::InvalidProps("display field payload budget"));
160        }
161        if !matches!(
162            self.compiled.slots.get(slot as usize).map(|s| s.kind),
163            Some(Kind::Text | Kind::Attribute(_))
164        ) {
165            return Err(Error::InvalidProps("display text slot kind"));
166        }
167        self.write(slot, Value::Text(crate::normalize(&text)))
168    }
169    pub fn flag(&self, slot: u16, value: bool) -> Result<(), Error> {
170        if !matches!(
171            self.compiled.slots.get(slot as usize).map(|s| s.kind),
172            Some(Kind::Class(..))
173        ) {
174            return Err(Error::InvalidProps("display class slot kind"));
175        }
176        self.write(slot, Value::Flag(value))
177    }
178    fn write(&self, slot: u16, value: Value) -> Result<(), Error> {
179        let mut values = self.values.borrow_mut();
180        let previous = values
181            .get_mut(slot as usize)
182            .ok_or(Error::InvalidProps("display field slot"))?;
183        if *previous == value {
184            return Ok(());
185        }
186        *previous = value.clone();
187        drop(values);
188        self.changed.borrow_mut().insert(slot, value);
189        if !self.queued.replace(true)
190            && let Some((queue, id)) = self.queue.borrow().as_ref()
191            && let Some(queue) = queue.upgrade()
192        {
193            queue.0.borrow_mut().push(*id);
194        }
195        Ok(())
196    }
197    pub fn bind(&self, queue: &Rc<Queue>, id: NodeId) {
198        *self.queue.borrow_mut() = Some((Rc::downgrade(queue), id));
199        self.take_changes();
200    }
201    pub fn take_changes(&self) -> BTreeMap<u16, Value> {
202        self.queued.set(false);
203        std::mem::take(&mut *self.changed.borrow_mut())
204    }
205    pub fn tree(&self) -> Vec<Tree> {
206        fn nodes(frame: &Frame, input: &[Node]) -> Vec<Tree> {
207            input
208                .iter()
209                .map(|node| match node {
210                    Node::Text(text) => Tree::Text(crate::normalize(text)),
211                    Node::Field(field) => {
212                        let (slot, _) = frame.slot(field.0).expect("validated field");
213                        let Value::Text(value) = frame.value(slot).unwrap() else {
214                            unreachable!()
215                        };
216                        Tree::Text(value)
217                    }
218                    Node::Outlet(outlet) => Tree::Outlet(frame.slot(outlet.0).unwrap().0),
219                    Node::Element {
220                        tag,
221                        attrs,
222                        children,
223                    } => {
224                        let mut values = BTreeMap::new();
225                        for attr in *attrs {
226                            match attr {
227                                Attribute::Static(name, value) => {
228                                    values.insert(*name, crate::normalize(value));
229                                }
230                                Attribute::Field(name, field) => {
231                                    let Value::Text(value) =
232                                        frame.value(frame.slot(field.0).unwrap().0).unwrap()
233                                    else {
234                                        unreachable!()
235                                    };
236                                    values.insert(*name, value);
237                                }
238                                Attribute::Click(click) => {
239                                    values.insert(
240                                        "data-gly-dclick",
241                                        frame.slot(click.0).unwrap().0.to_string(),
242                                    );
243                                }
244                                _ => {}
245                            }
246                        }
247                        for attr in *attrs {
248                            if let Attribute::Class(token, field) = attr {
249                                let Value::Flag(enabled) =
250                                    frame.value(frame.slot(field.0).unwrap().0).unwrap()
251                                else {
252                                    unreachable!()
253                                };
254                                let class = values.entry("class").or_insert_with(String::new);
255                                let present =
256                                    class.split_ascii_whitespace().any(|part| part == *token);
257                                if present != enabled {
258                                    let mut parts: Vec<_> = class
259                                        .split_ascii_whitespace()
260                                        .filter(|part| *part != *token)
261                                        .collect();
262                                    if enabled {
263                                        parts.push(token);
264                                    }
265                                    *class = parts.join(" ");
266                                }
267                            }
268                        }
269                        let mut children = nodes(frame, children);
270                        for attr in *attrs {
271                            if let Attribute::Children(outlet) = attr {
272                                children.push(Tree::Outlet(frame.slot(outlet.0).unwrap().0));
273                            }
274                        }
275                        Tree::Element {
276                            tag,
277                            attrs: values,
278                            children,
279                        }
280                    }
281                })
282                .collect()
283        }
284        nodes(self, self.template.roots())
285    }
286}