Skip to main content

plexus_ui_engine/swap/
boot.rs

1//! FRAME-17: **what the route needs at boot**, read from the live
2//! version's manifest and compiled trees before anything is mounted:
3//!
4//! - [`App::reachable`] — the route's component, each section's (its
5//!   assignment, else the default) and every component their trees name,
6//!   to any depth: what the boot fetches and imports, nothing more (the
7//!   rest when a section is swapped or the route changes).
8//! - [`App::boot_specs`] — the `live` snapshots the route's first page
9//!   asks, as the mount will ask them: the route's props, each section's
10//!   props from its layout, every prop declared and not passed `null`, the
11//!   state as declared; a `live` whose `when` is false at boot (a palette's
12//!   empty query) is not among them, nor one whose methods are not in its
13//!   component's `uses`, nor anything under an `{#if}` or `{#each}`. The
14//!   engine opens them before it mounts (the registry keeps each answer for
15//!   the subscriber to come), so the first calls leave right after the
16//!   boot rather than after the whole page is drawn.
17//!
18//! Their order: the largest page first — a spec whose params carry a
19//! `limit`, the largest first, before the rest (each with its changes
20//! stream opened just before its snapshot): a page of rows is the longest
21//! answer, so it is asked first and the small reads overlap it.
22
23use super::{App, ComponentEntry};
24use crate::live::{Clock, LiveSpec};
25use crate::signals::Runtime;
26use crate::transport::Wire;
27use crate::tree::{eval_params, eval_when, Attr, ComponentTree, Node, Renderer, State};
28use serde_json::{json, Map, Value};
29use std::collections::BTreeMap;
30use std::rc::Rc;
31
32impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> App<R, W, C> {
33    /// The live version's tree of `name`, parsed (once a page: kept by its
34    /// hash), when it is an rhx component whose files are here.
35    pub(super) fn tree_of(&self, version: &str, name: &str) -> Option<Rc<ComponentTree>> {
36        let text = {
37            let st = self.st.borrow();
38            st.files.version(version, name)?.0.to_string()
39        };
40        let hash = super::sha256_hex(&text);
41        if let Some(t) = self.trees.borrow().get(&hash) {
42            return Some(t.clone());
43        }
44        // Read, not compiled: its expressions compile when it mounts.
45        let t = Rc::new(ComponentTree::read(&text).ok()?);
46        self.read_trees.borrow_mut().entry(hash).or_insert(t).clone().into()
47    }
48
49    /// `text` parsed, kept by its sha256.
50    pub(super) fn parsed(&self, text: &str) -> Result<Rc<ComponentTree>, String> {
51        let hash = super::sha256_hex(text);
52        if let Some(t) = self.trees.borrow().get(&hash) {
53            return Ok(t.clone());
54        }
55        let t = Rc::new(ComponentTree::parse(text).map_err(|e| e.to_string())?);
56        self.trees.borrow_mut().insert(hash, t.clone());
57        Ok(t)
58    }
59
60    /// The component that fills `slot` of `layout` at boot: its assignment
61    /// for the live version, else the manifest's default.
62    fn section_component(&self, layout: &str, slot: &str) -> Option<String> {
63        let st = self.st.borrow();
64        match st.assignments.iter().find(|a| a.layout == layout && a.slot == slot) {
65            Some(a) if a.version == st.version => Some(a.component.clone()),
66            Some(_) => None,
67            None => st.manifest.slots.get(layout).and_then(|m| m.get(slot)).cloned(),
68        }
69    }
70
71    /// FRAME-18: a module layout's sections at boot — it has no tree to
72    /// read: the slots `manifest.slots` declares for it and those an
73    /// assignment names, each with what fills it. A mark the module draws
74    /// under a condition is among them whether or not it is drawn. FRAME-29:
75    /// a bound mark is not seen here (no manifest names it for the layout):
76    /// its component is fetched at its first walk, its snapshots asked after
77    /// the mount; a slot `slots.json` names that a mark also binds has its
78    /// default fetched and asked here all the same, and let go after the
79    /// keep.
80    fn module_sections(&self, layout: &str) -> Vec<String> {
81        let slots: Vec<String> = {
82            let st = self.st.borrow();
83            let mut slots: Vec<String> = st.manifest.slots.get(layout).map(|m| m.keys().cloned().collect()).unwrap_or_default();
84            for a in st.assignments.iter().filter(|a| a.layout == layout) {
85                if !slots.contains(&a.slot) {
86                    slots.push(a.slot.clone());
87                }
88            }
89            slots
90        };
91        slots.iter().filter_map(|slot| self.section_component(layout, slot)).collect()
92    }
93
94    /// The live version's components the route to `component` mounts:
95    /// it, its sections' components and every component their trees name.
96    pub fn reachable(&self, component: &str) -> Vec<String> {
97        let (version, manifest) = {
98            let st = self.st.borrow();
99            (st.version.clone(), st.manifest.clone())
100        };
101        let mut seen: Vec<String> = Vec::new();
102        let mut todo = vec![component.to_string()];
103        while let Some(name) = todo.pop() {
104            if seen.contains(&name) || !manifest.components.contains_key(&name) {
105                continue;
106            }
107            seen.push(name.clone());
108            if manifest.components.get(&name).is_some_and(|e| !e.is_rhx()) {
109                todo.extend(self.module_sections(&name).into_iter().rev());
110                continue;
111            }
112            let Some(tree) = self.tree_of(&version, &name) else { continue };
113            let mut named = Vec::new();
114            walk(&tree.tree, true, &mut |n, _| match n {
115                Node::Component { name: c, .. } => named.push(c.clone()),
116                Node::Slot { name: slot, .. } => named.extend(self.section_component(&name, slot)),
117                _ => {}
118            });
119            todo.extend(named.into_iter().rev());
120        }
121        seen
122    }
123
124    /// The `live` specs the route to `component` with `props` asks first
125    /// (see the module's words), in the order they are opened.
126    pub fn boot_specs(&self, component: &str, props: Map<String, Value>) -> Vec<LiveSpec> {
127        let version = self.version();
128        let manifest = self.manifest();
129        let rt = Runtime::new();
130        let mut out: Vec<LiveSpec> = Vec::new();
131        let mut todo: Vec<(String, Map<String, Value>)> = vec![(component.to_string(), props)];
132        let mut visited = 0;
133        while let Some((name, mut props)) = todo.pop() {
134            visited += 1;
135            if visited > 64 {
136                break;
137            }
138            // FRAME-18: a module's own specs are its code's; its sections'
139            // are read from `manifest.slots`, their props unknown (a mark's
140            // `data-*` is read when it is drawn): each declared prop null.
141            if manifest.components.get(&name).is_some_and(|e| !e.is_rhx()) {
142                todo.extend(self.module_sections(&name).into_iter().rev().map(|c| (c, Map::new())));
143                continue;
144            }
145            let Some(entry) = manifest.components.get(&name).filter(|e| e.is_rhx()) else { continue };
146            let Some(tree) = self.tree_of(&version, &name) else { continue };
147            for p in &tree.props {
148                props.entry(p.clone()).or_insert(Value::Null);
149            }
150            let state = State::new(&rt, &tree.state);
151            for d in tree.live.values() {
152                if let Some(spec) = spec_at_boot(entry, d, &props, &state) {
153                    if !out.contains(&spec) {
154                        out.push(spec);
155                    }
156                }
157            }
158            let mut kids = Vec::new();
159            walk(&tree.tree, false, &mut |n, _| match n {
160                Node::Component { name: c, props: p } => kids.push((c.clone(), attrs(p, &props, &state))),
161                Node::Slot { name: slot, props: p } => {
162                    if let Some(c) = self.section_component(&name, slot) {
163                        kids.push((c, attrs(p, &props, &state)));
164                    }
165                }
166                _ => {}
167            });
168            todo.extend(kids.into_iter().rev());
169        }
170        // The largest page first; the rest as found.
171        let limit = |s: &LiveSpec| s.params.get("limit").and_then(Value::as_u64);
172        out.sort_by(|a, b| limit(b).cmp(&limit(a)));
173        out
174    }
175}
176
177/// `decl` as the mount will ask it at boot, or none: held by its `when`,
178/// or a method its component's `uses` does not name.
179fn spec_at_boot(entry: &ComponentEntry, d: &crate::tree::LiveDecl, props: &Map<String, Value>, state: &State) -> Option<LiveSpec> {
180    // GAMMA-5: an open entry holds what is under its prefix.
181    let allowed = |m: &str| crate::bus::covers(entry.uses.iter().map(String::as_str), m);
182    if !allowed(&d.snapshot) || d.changes.as_deref().is_some_and(|c| !allowed(c)) {
183        return None;
184    }
185    if !eval_when(d.when.as_ref(), props, state) {
186        return None;
187    }
188    let on: Vec<(&str, &str)> = d.on.iter().map(|(a, b)| (a.as_str(), b.as_str())).collect();
189    LiveSpec::new(&d.snapshot, eval_params(&d.params, props, state), d.changes.as_deref(), eval_params(&d.changes_params, props, state), &d.key, &on).ok()
190}
191
192/// A component's or a slot's props, as its parent's scope gives them.
193fn attrs(given: &BTreeMap<String, Attr>, props: &Map<String, Value>, state: &State) -> Map<String, Value> {
194    let as_params: BTreeMap<String, Value> = given
195        .iter()
196        .map(|(k, a)| match a {
197            Attr::Lit(s) => (k.clone(), Value::String(s.clone())),
198            Attr::Expr(e) => (k.clone(), json!({ "expr": e })),
199        })
200        .collect();
201    match eval_params(&as_params, props, state) {
202        Value::Object(m) => m,
203        _ => Map::new(),
204    }
205}
206
207/// Every node of `nodes`, an `{#if}`'s and an `{#each}`'s too when `deep`.
208fn walk(nodes: &[Node], deep: bool, f: &mut dyn FnMut(&Node, bool)) {
209    for n in nodes {
210        f(n, deep);
211        match n {
212            Node::El { children, .. } => walk(children, deep, f),
213            Node::If { then, otherwise, .. } if deep => {
214                walk(then, deep, f);
215                walk(otherwise, deep, f);
216            }
217            Node::Each { body, .. } if deep => walk(body, deep, f),
218            _ => {}
219        }
220    }
221}
222
223#[cfg(test)]
224#[path = "tests_boot.rs"]
225mod tests;