plexus-ui-engine 0.2.3

The plexus-ui engine — signals, live() over Plexus streams, the view tree over a renderer, Rhai folds, sections, hot-swap
Documentation
//! COMPS-2: **a stored component drawn in a frame** (wasm32, `dom`) — the
//! engine's side of `bus.frame(target, { component: { version, name } })`.
//!
//! Someone else's component (one authored by a principal who is not the
//! reviewed bundle's signer) is never mounted in the page: the host frames
//! it. The frame is the service's `/frame` document — an opaque origin,
//! `connect-src 'none'` — and it imports this version's `host.js` and
//! `engine.js` by their paths (`/app/<version>/…`, public code), is handed
//! the version's `manifest.json`, `components.json` and `engine.wasm` by its
//! parent (it may fetch nothing), and calls [`boot_frame`]: the component
//! loaded from that version by hash, its modules imported, mounted into the
//! frame's body with its props.
//!
//! Its wire is [`FrameWire`]: no socket. Each call is posted to the parent
//! (`plexus:call { channel, id, method, params }`), which makes it through
//! the frame's member of its bus — held to this component's `uses`, sent
//! over the page's one socket as the viewer — and posts the answer back
//! (`plexus:answer { channel, id, ok, events, message }`), taken only from
//! the parent window on the frame's channel. A call is answered once, at
//! its end, so a stream that never ends (a watch) is never heard here: a
//! framed component's `live` reads its snapshot, and moves on no change.

use crate::entry::PageClock;
use crate::host_js;
use crate::signals::Runtime;
use crate::swap::{App, Files, Manifest};
use crate::transport::{CallId, Sink, Wire, WireItem};
use crate::tree::dom::Dom;
use serde_json::{json, Map, Value};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;

/// What the frame posts a call as, and what answers it.
pub const CALL: &str = "plexus:call";
/// The parent's answer to a call.
pub const ANSWER: &str = "plexus:answer";
/// What the frame says when its component could not be drawn.
pub const FAILED: &str = "plexus:failed";

struct Inner {
    channel: String,
    next: Cell<u64>,
    sinks: RefCell<HashMap<String, Sink>>,
}

/// The frame's wire: every call posted to the parent on the channel.
#[derive(Clone)]
pub struct FrameWire(Rc<Inner>);

fn window() -> web_sys::Window {
    web_sys::window().expect("a window")
}

fn parent() -> Option<web_sys::Window> {
    window().parent().ok().flatten()
}

fn post(message: &Value) {
    if let Some(p) = parent() {
        let _ = p.post_message(&host_js::to_js(message), "*");
    }
}

/// Engine calls are named `e<n>`, so they never meet a page's own
/// `plexus.call` ids (`p<n>`) on the same channel.
fn key(n: u64) -> String {
    format!("e{n}")
}

impl FrameWire {
    /// The wire on `channel`, listening for the parent's answers.
    pub fn new(channel: &str) -> Self {
        let wire = Self(Rc::new(Inner { channel: channel.into(), next: Cell::new(0), sinks: RefCell::new(HashMap::new()) }));
        let w = wire.clone();
        let on = Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |e: web_sys::MessageEvent| w.heard(&e));
        let _ = window().add_event_listener_with_callback("message", on.as_ref().unchecked_ref());
        on.forget();
        wire
    }

    /// An answer, if it is the parent's on this channel to a call of ours.
    fn heard(&self, e: &web_sys::MessageEvent) {
        let from_parent = match (e.source(), parent()) {
            (Some(s), Some(p)) => js_sys::Object::is(&s, &p),
            _ => false,
        };
        if !from_parent {
            return;
        }
        let d = host_js::from_js(&e.data());
        if d["type"] != ANSWER || d["channel"] != self.0.channel.as_str() {
            return;
        }
        let Some(id) = d["id"].as_str() else { return };
        let Some(mut sink) = self.0.sinks.borrow_mut().remove(id) else { return };
        let events: Vec<Value> = d["events"].as_array().cloned().unwrap_or_default();
        let message = d["message"].as_str().unwrap_or("refused").to_string();
        let in_band = events.iter().any(|v| v["type"] == "error" || v["type"] == "refused");
        if d["ok"] == true || in_band {
            for v in events {
                sink(WireItem::Data(v));
            }
            sink(WireItem::Done);
        } else if message == crate::bus::DISCONNECTED {
            sink(WireItem::Dropped);
        } else {
            sink(WireItem::Refused(message));
        }
    }
}

impl Wire for FrameWire {
    fn open(&self, method: &str, params: Value, sink: Sink) -> CallId {
        let n = self.0.next.get() + 1;
        self.0.next.set(n);
        self.0.sinks.borrow_mut().insert(key(n), sink);
        post(&json!({ "type": CALL, "channel": self.0.channel, "id": key(n), "method": method, "params": params }));
        CallId(n)
    }

    fn close(&self, call: CallId) {
        self.0.sinks.borrow_mut().remove(&key(call.0));
    }
}

type FrameApp = App<Dom, FrameWire, PageClock>;

thread_local! {
    static FRAMED: RefCell<Option<Rc<FrameApp>>> = const { RefCell::new(None) };
}

/// COMPS-2: draws version `version`'s component `name` in this frame with
/// `props` (JSON), from what the parent handed over — the version's
/// `manifest` and `components.json` text — its calls over [`FrameWire`] on
/// `channel`. A component that cannot be drawn says `plexus:failed`.
#[wasm_bindgen]
pub fn boot_frame(version: String, name: String, props: String, manifest: String, components: Option<String>, channel: String) {
    wasm_bindgen_futures::spawn_local(async move {
        if let Err(e) = run(&version, &name, &props, &manifest, components.as_deref(), &channel).await {
            web_sys::console::error_1(&format!("ui: the framed {name}: {e}").into());
            post(&json!({ "type": FAILED, "channel": channel, "message": e }));
        }
    });
}

async fn run(version: &str, name: &str, props: &str, manifest: &str, components: Option<&str>, channel: &str) -> Result<(), String> {
    let document = window().document().ok_or("no document")?;
    let root: web_sys::Node = document.body().ok_or("no body")?.into();
    let m = Manifest::parse(manifest)?;
    if !m.components.contains_key(name) {
        return Err(format!("version {version} has no component {name}"));
    }
    let app = App::new(&Runtime::new(), Dom::new(document), FrameWire::new(channel), PageClock);
    app.load(version, m.clone());
    // Every rhx component's files from components.json: the frame fetches nothing.
    let mut files = Files::default();
    let doc: Map<String, Value> = components.and_then(|t| serde_json::from_str::<Value>(t).ok()).and_then(|v| v.as_object().cloned()).unwrap_or_default();
    for (n, e) in m.components.iter().filter(|(_, e)| e.is_rhx()) {
        let entry = doc.get(n);
        if let (Some(t), Some(h)) = (entry.and_then(|e| e["tree"].as_str()), entry.and_then(|e| e["handlers"].as_str())) {
            files.put_version(version, n, t, h);
            if let Some(css) = entry.and_then(|e| e["css"].as_str()) {
                files.put_sheet(version, n, css);
            }
        } else if e.is_rhx() && n == name {
            return Err(format!("{name}'s tree is not in components.json"));
        }
    }
    app.provide(&files);
    // Its modules (and those of every component its tree names), imported by path.
    for n in app.reachable(name) {
        let Some(entry) = m.components.get(&n).filter(|e| !e.is_rhx()) else { continue };
        let module = host_js::import(version, &n).await?;
        app.provide_module(version, &n, entry.clone(), Rc::new(module));
    }
    let props = serde_json::from_str::<Value>(props).ok().and_then(|v| v.as_object().cloned()).unwrap_or_default();
    app.mount(&root, name, props).map_err(|e| e.to_string())?;
    FRAMED.with(|f| *f.borrow_mut() = Some(app));
    Ok(())
}