Skip to main content

plexus_ui_engine/tree/
recording.rs

1//! UI-6: **the recording renderer** — the native tests' [`Renderer`]: every
2//! call kept in order ([`Call`]), and the tree it built kept too, so a test
3//! asserts both what was called and what is drawn ([`Recording::html`]).
4//! A node is a number; `0` is the root, there from the start.
5
6use super::Renderer;
7use serde_json::Value;
8use std::cell::RefCell;
9use std::collections::BTreeMap;
10use std::rc::Rc;
11
12/// One renderer call.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum Call {
15    Create { node: u32, tag: String },
16    CreateText { node: u32, text: String },
17    SetAttr { node: u32, name: String, value: String },
18    /// FRAME-50: an attribute taken off.
19    RemoveAttr { node: u32, name: String },
20    SetText { node: u32, text: String },
21    Insert { parent: u32, child: u32, before: Option<u32> },
22    Remove { parent: u32, child: u32 },
23    Listen { node: u32, event: String },
24    /// FRAME-30: a sheet adopted by the page (`on`) or dropped.
25    Sheet { key: String, on: bool },
26}
27
28impl Call {
29    /// The node the call made or changed (an insert's or remove's child).
30    pub fn node(&self) -> u32 {
31        match self {
32            Call::Create { node, .. } | Call::CreateText { node, .. } | Call::SetAttr { node, .. } | Call::RemoveAttr { node, .. } | Call::SetText { node, .. } | Call::Listen { node, .. } => *node,
33            Call::Insert { child, .. } | Call::Remove { child, .. } => *child,
34            // A sheet is the page's (the root's), no node of a component's.
35            Call::Sheet { .. } => 0,
36        }
37    }
38}
39
40#[derive(Default)]
41struct Drawn {
42    /// An element's tag, or `None` for a text node.
43    tag: Option<String>,
44    text: String,
45    attrs: BTreeMap<String, String>,
46    children: Vec<u32>,
47    parent: Option<u32>,
48}
49
50#[derive(Default)]
51struct Log {
52    calls: Vec<Call>,
53    nodes: Vec<Drawn>,
54    /// Every registration held: its id, node, event and handler.
55    listeners: Vec<(u64, u32, String, Rc<dyn Fn(Value)>)>,
56    next_listener: u64,
57}
58
59/// The recording renderer: a handle; clones share one log.
60#[derive(Clone)]
61pub struct Recording(Rc<RefCell<Log>>);
62
63impl std::fmt::Debug for Recording {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        write!(f, "Recording({} calls)", self.0.borrow().calls.len())
66    }
67}
68
69impl Default for Recording {
70    fn default() -> Self {
71        Self::new()
72    }
73}
74
75impl Recording {
76    /// A log holding only the root, `0` (`<root>`).
77    pub fn new() -> Self {
78        let log = Log { nodes: vec![Drawn { tag: Some("root".into()), ..Drawn::default() }], ..Log::default() };
79        Self(Rc::new(RefCell::new(log)))
80    }
81
82    /// The root node.
83    pub fn root(&self) -> u32 {
84        0
85    }
86
87    /// Every call so far.
88    pub fn calls(&self) -> Vec<Call> {
89        self.0.borrow().calls.clone()
90    }
91
92    /// Where the log stands: [`Self::calls_since`] takes it.
93    pub fn mark(&self) -> usize {
94        self.0.borrow().calls.len()
95    }
96
97    /// The calls after `mark`.
98    pub fn calls_since(&self, mark: usize) -> Vec<Call> {
99        self.0.borrow().calls[mark..].to_vec()
100    }
101
102    /// What is drawn under `node`, as HTML: attributes in name order, a
103    /// text node's text as it is (an anchor draws nothing).
104    pub fn html(&self, node: u32) -> String {
105        let log = self.0.borrow();
106        let mut out = String::new();
107        for c in &log.nodes[node as usize].children {
108            draw(&log.nodes, *c, &mut out);
109        }
110        out
111    }
112
113    /// The nodes now in the tree under `node` (itself included), depth first.
114    pub fn under(&self, node: u32) -> Vec<u32> {
115        let log = self.0.borrow();
116        let mut out = vec![node];
117        let mut i = 0;
118        while i < out.len() {
119            out.extend(log.nodes[out[i] as usize].children.iter().copied());
120            i += 1;
121        }
122        out
123    }
124
125    /// The elements now in the tree with attribute `name` = `value`.
126    pub fn find_attr(&self, name: &str, value: &str) -> Vec<u32> {
127        self.under(0).into_iter().filter(|n| self.0.borrow().nodes[*n as usize].attrs.get(name).is_some_and(|v| v == value)).collect()
128    }
129
130    /// The elements now in the tree named `tag`.
131    pub fn find_tag(&self, tag: &str) -> Vec<u32> {
132        self.under(0).into_iter().filter(|n| self.0.borrow().nodes[*n as usize].tag.as_deref() == Some(tag)).collect()
133    }
134
135    /// Fires `event` on `node` with `payload`: each listener on it runs.
136    pub fn fire(&self, node: u32, event: &str, payload: Value) {
137        let hit: Vec<Rc<dyn Fn(Value)>> =
138            self.0.borrow().listeners.iter().filter(|(_, n, e, _)| *n == node && e == event).map(|(_, _, _, h)| h.clone()).collect();
139        assert!(!hit.is_empty(), "nothing listens for {event} on node {node}");
140        for h in hit {
141            h(payload.clone());
142        }
143    }
144
145    /// UI-10: fires `event` on the window: each `window-<event>`
146    /// registration held runs (whose node is drawn, as the DOM renderer's
147    /// guard does).
148    pub fn fire_window(&self, event: &str, payload: Value) {
149        let name = format!("window-{event}");
150        let drawn = self.under(0);
151        let hit: Vec<Rc<dyn Fn(Value)>> =
152            self.0.borrow().listeners.iter().filter(|(_, n, e, _)| *e == name && drawn.contains(n)).map(|(_, _, _, h)| h.clone()).collect();
153        for h in hit {
154            h(payload.clone());
155        }
156    }
157
158    /// The `window-*` registrations held now — raw: one not taken away is
159    /// counted whether or not its node is drawn.
160    pub fn window_listeners(&self) -> usize {
161        self.0.borrow().listeners.iter().filter(|(_, _, e, _)| e.starts_with("window-")).count()
162    }
163
164    /// Every registration held now, raw (element and window).
165    pub fn listeners(&self) -> usize {
166        self.0.borrow().listeners.len()
167    }
168
169    fn push(&self, call: Call) {
170        self.0.borrow_mut().calls.push(call);
171    }
172
173    fn make(&self, drawn: Drawn) -> u32 {
174        let mut log = self.0.borrow_mut();
175        log.nodes.push(drawn);
176        (log.nodes.len() - 1) as u32
177    }
178}
179
180fn draw(nodes: &[Drawn], n: u32, out: &mut String) {
181    let d = &nodes[n as usize];
182    match &d.tag {
183        None => out.push_str(&d.text),
184        Some(tag) => {
185            out.push('<');
186            out.push_str(tag);
187            for (k, v) in &d.attrs {
188                out.push_str(&format!(" {k}=\"{v}\""));
189            }
190            out.push('>');
191            for c in &d.children {
192                draw(nodes, *c, out);
193            }
194            out.push_str(&format!("</{tag}>"));
195        }
196    }
197}
198
199impl Renderer for Recording {
200    type Node = u32;
201
202    fn create_element(&self, tag: &str) -> u32 {
203        let node = self.make(Drawn { tag: Some(tag.into()), ..Drawn::default() });
204        self.push(Call::Create { node, tag: tag.into() });
205        node
206    }
207
208    fn create_text(&self, text: &str) -> u32 {
209        let node = self.make(Drawn { text: text.into(), ..Drawn::default() });
210        self.push(Call::CreateText { node, text: text.into() });
211        node
212    }
213
214    fn set_attr(&self, node: &u32, name: &str, value: &str) {
215        self.0.borrow_mut().nodes[*node as usize].attrs.insert(name.into(), value.into());
216        self.push(Call::SetAttr { node: *node, name: name.into(), value: value.into() });
217    }
218
219    fn remove_attr(&self, node: &u32, name: &str) {
220        self.0.borrow_mut().nodes[*node as usize].attrs.remove(name);
221        self.push(Call::RemoveAttr { node: *node, name: name.into() });
222    }
223
224    fn set_text(&self, node: &u32, text: &str) {
225        self.0.borrow_mut().nodes[*node as usize].text = text.into();
226        self.push(Call::SetText { node: *node, text: text.into() });
227    }
228
229    fn insert(&self, parent: &u32, child: &u32, before: Option<&u32>) {
230        {
231            let mut log = self.0.borrow_mut();
232            if let Some(old) = log.nodes[*child as usize].parent.take() {
233                log.nodes[old as usize].children.retain(|c| c != child);
234            }
235            let kids = &mut log.nodes[*parent as usize].children;
236            let at = before.and_then(|b| kids.iter().position(|c| c == b)).unwrap_or(kids.len());
237            kids.insert(at, *child);
238            log.nodes[*child as usize].parent = Some(*parent);
239        }
240        self.push(Call::Insert { parent: *parent, child: *child, before: before.copied() });
241    }
242
243    fn remove(&self, parent: &u32, child: &u32) {
244        {
245            let mut log = self.0.borrow_mut();
246            log.nodes[*parent as usize].children.retain(|c| c != child);
247            log.nodes[*child as usize].parent = None;
248        }
249        self.push(Call::Remove { parent: *parent, child: *child });
250    }
251
252    fn marks(&self, root: &u32) -> Vec<u32> {
253        let log = self.0.borrow();
254        fn walk(nodes: &[Drawn], n: u32, out: &mut Vec<u32>) {
255            for c in &nodes[n as usize].children {
256                if nodes[*c as usize].attrs.contains_key("data-slot") {
257                    out.push(*c);
258                }
259                walk(nodes, *c, out);
260            }
261        }
262        let mut out = Vec::new();
263        walk(&log.nodes, *root, &mut out);
264        out
265    }
266
267    fn attrs(&self, node: &u32) -> Vec<(String, String)> {
268        self.0.borrow().nodes[*node as usize].attrs.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
269    }
270
271    fn contains(&self, ancestor: &u32, node: &u32) -> bool {
272        let log = self.0.borrow();
273        let mut at = Some(*node);
274        while let Some(n) = at {
275            if n == *ancestor {
276                return true;
277            }
278            at = log.nodes[n as usize].parent;
279        }
280        false
281    }
282
283    fn observe(&self, _root: &u32, _f: Rc<dyn Fn(Vec<u32>)>) -> super::Unlisten {
284        Box::new(|| {})
285    }
286
287    fn sheet(&self, key: &str, _css: &str, on: bool) {
288        self.push(Call::Sheet { key: key.into(), on });
289    }
290
291    fn listen(&self, node: &u32, event: &str, handler: Rc<dyn Fn(Value)>) -> super::Unlisten {
292        let id = {
293            let mut log = self.0.borrow_mut();
294            log.next_listener += 1;
295            let id = log.next_listener;
296            log.listeners.push((id, *node, event.into(), handler));
297            id
298        };
299        self.push(Call::Listen { node: *node, event: event.into() });
300        let log = Rc::downgrade(&self.0);
301        Box::new(move || {
302            if let Some(log) = log.upgrade() {
303                log.borrow_mut().listeners.retain(|(i, ..)| *i != id);
304            }
305        })
306    }
307}