plexus-ui-engine 0.2.0

The plexus-ui engine — signals, live() over Plexus streams, the view tree over a renderer, Rhai folds, sections, hot-swap
Documentation
//! FRAME-17: **what the route needs at boot**, read from the live
//! version's manifest and compiled trees before anything is mounted:
//!
//! - [`App::reachable`] — the route's component, each section's (its
//!   assignment, else the default) and every component their trees name,
//!   to any depth: what the boot fetches and imports, nothing more (the
//!   rest when a section is swapped or the route changes).
//! - [`App::boot_specs`] — the `live` snapshots the route's first page
//!   asks, as the mount will ask them: the route's props, each section's
//!   props from its layout, every prop declared and not passed `null`, the
//!   state as declared; a `live` whose `when` is false at boot (a palette's
//!   empty query) is not among them, nor one whose methods are not in its
//!   component's `uses`, nor anything under an `{#if}` or `{#each}`. The
//!   engine opens them before it mounts (the registry keeps each answer for
//!   the subscriber to come), so the first calls leave right after the
//!   boot rather than after the whole page is drawn.
//!
//! Their order: the largest page first — a spec whose params carry a
//! `limit`, the largest first, before the rest (each with its changes
//! stream opened just before its snapshot): a page of rows is the longest
//! answer, so it is asked first and the small reads overlap it.

use super::{App, ComponentEntry};
use crate::live::{Clock, LiveSpec};
use crate::signals::Runtime;
use crate::transport::Wire;
use crate::tree::{eval_params, eval_when, Attr, ComponentTree, Node, Renderer, State};
use serde_json::{json, Map, Value};
use std::collections::BTreeMap;
use std::rc::Rc;

impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> App<R, W, C> {
    /// The live version's tree of `name`, parsed (once a page: kept by its
    /// hash), when it is an rhx component whose files are here.
    pub(super) fn tree_of(&self, version: &str, name: &str) -> Option<Rc<ComponentTree>> {
        let text = {
            let st = self.st.borrow();
            st.files.version(version, name)?.0.to_string()
        };
        let hash = super::sha256_hex(&text);
        if let Some(t) = self.trees.borrow().get(&hash) {
            return Some(t.clone());
        }
        // Read, not compiled: its expressions compile when it mounts.
        let t = Rc::new(ComponentTree::read(&text).ok()?);
        self.read_trees.borrow_mut().entry(hash).or_insert(t).clone().into()
    }

    /// `text` parsed, kept by its sha256.
    pub(super) fn parsed(&self, text: &str) -> Result<Rc<ComponentTree>, String> {
        let hash = super::sha256_hex(text);
        if let Some(t) = self.trees.borrow().get(&hash) {
            return Ok(t.clone());
        }
        let t = Rc::new(ComponentTree::parse(text).map_err(|e| e.to_string())?);
        self.trees.borrow_mut().insert(hash, t.clone());
        Ok(t)
    }

    /// The component that fills `slot` of `layout` at boot: its assignment
    /// for the live version, else the manifest's default.
    fn section_component(&self, layout: &str, slot: &str) -> Option<String> {
        let st = self.st.borrow();
        match st.assignments.iter().find(|a| a.layout == layout && a.slot == slot) {
            Some(a) if a.version == st.version => Some(a.component.clone()),
            Some(_) => None,
            None => st.manifest.slots.get(layout).and_then(|m| m.get(slot)).cloned(),
        }
    }

    /// FRAME-18: a module layout's sections at boot — it has no tree to
    /// read: the slots `manifest.slots` declares for it and those an
    /// assignment names, each with what fills it. A mark the module draws
    /// under a condition is among them whether or not it is drawn. FRAME-29:
    /// a bound mark is not seen here (no manifest names it for the layout):
    /// its component is fetched at its first walk, its snapshots asked after
    /// the mount; a slot `slots.json` names that a mark also binds has its
    /// default fetched and asked here all the same, and let go after the
    /// keep.
    fn module_sections(&self, layout: &str) -> Vec<String> {
        let slots: Vec<String> = {
            let st = self.st.borrow();
            let mut slots: Vec<String> = st.manifest.slots.get(layout).map(|m| m.keys().cloned().collect()).unwrap_or_default();
            for a in st.assignments.iter().filter(|a| a.layout == layout) {
                if !slots.contains(&a.slot) {
                    slots.push(a.slot.clone());
                }
            }
            slots
        };
        slots.iter().filter_map(|slot| self.section_component(layout, slot)).collect()
    }

    /// The live version's components the route to `component` mounts:
    /// it, its sections' components and every component their trees name.
    pub fn reachable(&self, component: &str) -> Vec<String> {
        let (version, manifest) = {
            let st = self.st.borrow();
            (st.version.clone(), st.manifest.clone())
        };
        let mut seen: Vec<String> = Vec::new();
        let mut todo = vec![component.to_string()];
        while let Some(name) = todo.pop() {
            if seen.contains(&name) || !manifest.components.contains_key(&name) {
                continue;
            }
            seen.push(name.clone());
            if manifest.components.get(&name).is_some_and(|e| !e.is_rhx()) {
                todo.extend(self.module_sections(&name).into_iter().rev());
                continue;
            }
            let Some(tree) = self.tree_of(&version, &name) else { continue };
            let mut named = Vec::new();
            walk(&tree.tree, true, &mut |n, _| match n {
                Node::Component { name: c, .. } => named.push(c.clone()),
                Node::Slot { name: slot, .. } => named.extend(self.section_component(&name, slot)),
                _ => {}
            });
            todo.extend(named.into_iter().rev());
        }
        seen
    }

    /// The `live` specs the route to `component` with `props` asks first
    /// (see the module's words), in the order they are opened.
    pub fn boot_specs(&self, component: &str, props: Map<String, Value>) -> Vec<LiveSpec> {
        let version = self.version();
        let manifest = self.manifest();
        let rt = Runtime::new();
        let mut out: Vec<LiveSpec> = Vec::new();
        let mut todo: Vec<(String, Map<String, Value>)> = vec![(component.to_string(), props)];
        let mut visited = 0;
        while let Some((name, mut props)) = todo.pop() {
            visited += 1;
            if visited > 64 {
                break;
            }
            // FRAME-18: a module's own specs are its code's; its sections'
            // are read from `manifest.slots`, their props unknown (a mark's
            // `data-*` is read when it is drawn): each declared prop null.
            if manifest.components.get(&name).is_some_and(|e| !e.is_rhx()) {
                todo.extend(self.module_sections(&name).into_iter().rev().map(|c| (c, Map::new())));
                continue;
            }
            let Some(entry) = manifest.components.get(&name).filter(|e| e.is_rhx()) else { continue };
            let Some(tree) = self.tree_of(&version, &name) else { continue };
            for p in &tree.props {
                props.entry(p.clone()).or_insert(Value::Null);
            }
            let state = State::new(&rt, &tree.state);
            for d in tree.live.values() {
                if let Some(spec) = spec_at_boot(entry, d, &props, &state) {
                    if !out.contains(&spec) {
                        out.push(spec);
                    }
                }
            }
            let mut kids = Vec::new();
            walk(&tree.tree, false, &mut |n, _| match n {
                Node::Component { name: c, props: p } => kids.push((c.clone(), attrs(p, &props, &state))),
                Node::Slot { name: slot, props: p } => {
                    if let Some(c) = self.section_component(&name, slot) {
                        kids.push((c, attrs(p, &props, &state)));
                    }
                }
                _ => {}
            });
            todo.extend(kids.into_iter().rev());
        }
        // The largest page first; the rest as found.
        let limit = |s: &LiveSpec| s.params.get("limit").and_then(Value::as_u64);
        out.sort_by(|a, b| limit(b).cmp(&limit(a)));
        out
    }
}

/// `decl` as the mount will ask it at boot, or none: held by its `when`,
/// or a method its component's `uses` does not name.
fn spec_at_boot(entry: &ComponentEntry, d: &crate::tree::LiveDecl, props: &Map<String, Value>, state: &State) -> Option<LiveSpec> {
    let allowed = |m: &str| entry.uses.iter().any(|u| u == m);
    if !allowed(&d.snapshot) || d.changes.as_deref().is_some_and(|c| !allowed(c)) {
        return None;
    }
    if !eval_when(d.when.as_ref(), props, state) {
        return None;
    }
    let on: Vec<(&str, &str)> = d.on.iter().map(|(a, b)| (a.as_str(), b.as_str())).collect();
    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()
}

/// A component's or a slot's props, as its parent's scope gives them.
fn attrs(given: &BTreeMap<String, Attr>, props: &Map<String, Value>, state: &State) -> Map<String, Value> {
    let as_params: BTreeMap<String, Value> = given
        .iter()
        .map(|(k, a)| match a {
            Attr::Lit(s) => (k.clone(), Value::String(s.clone())),
            Attr::Expr(e) => (k.clone(), json!({ "expr": e })),
        })
        .collect();
    match eval_params(&as_params, props, state) {
        Value::Object(m) => m,
        _ => Map::new(),
    }
}

/// Every node of `nodes`, an `{#if}`'s and an `{#each}`'s too when `deep`.
fn walk(nodes: &[Node], deep: bool, f: &mut dyn FnMut(&Node, bool)) {
    for n in nodes {
        f(n, deep);
        match n {
            Node::El { children, .. } => walk(children, deep, f),
            Node::If { then, otherwise, .. } if deep => {
                walk(then, deep, f);
                walk(otherwise, deep, f);
            }
            Node::Each { body, .. } if deep => walk(body, deep, f),
            _ => {}
        }
    }
}

#[cfg(test)]
#[path = "tests_boot.rs"]
mod tests;