plexus-ui-engine 0.2.6

The plexus-ui engine — signals, live() over Plexus streams, the view tree over a renderer, Rhai folds, sections, hot-swap
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! FRAME-12: **the host's JS face, wasm side** — a module of any profile
//! but `rhx/1` is an ES module the page imports (`js/host.js`'s
//! `importModule`) and mounts through `mountModule(module, target, props,
//! handle)`: [`JsModule`] is the module contract over it, [`BusHandle`] the
//! member of the bus it is handed (wrapped by `busOf` in `host.js`), and
//! [`LiveHandle`] a `live` collection as a store — `subscribe(fn)` calls
//! `fn` before it returns, then on every change in the bus's turn, and
//! never after its unsubscribe; FRAME-19: `update(patch)` moves its params
//! and `when`. `markdown(text)` is the engine's sanitized render. Values
//! cross as JSON. FRAME-20: a subscriber is handed each move — the whole
//! collection first and after a resync, else the fold's change by key —
//! and `host.js`'s store applies it to the rows it keeps.

use crate::bus::{answer_sink, Answer, Bus, Member};
use crate::live::{Delta, ModuleLive, ModuleSpec};
use crate::module::{Module, ModuleInstance};
use crate::signals::Signal;
use crate::transport::Sink;
use crate::tree::dom::Dom;
use serde_json::{Map, Value};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;

#[wasm_bindgen(raw_module = "./host.js")]
extern "C" {
    #[wasm_bindgen(js_name = importModule)]
    fn import_module(url: &str) -> js_sys::Promise;
    #[wasm_bindgen(js_name = mountModule, catch)]
    fn mount_module(module: &JsValue, target: &web_sys::Node, props: &JsValue, handle: BusHandle) -> Result<JsValue, JsValue>;
    #[wasm_bindgen(js_name = updateModule, catch)]
    fn update_module(mounted: &JsValue, props: &JsValue) -> Result<(), JsValue>;
    #[wasm_bindgen(js_name = destroyModule, catch)]
    fn destroy_module(mounted: &JsValue) -> Result<(), JsValue>;
    #[wasm_bindgen(js_name = yieldTask)]
    fn yield_task(f: &JsValue);
    #[wasm_bindgen(js_name = fileUrl)]
    fn file_url_js(url: &str) -> String;
    #[wasm_bindgen(js_name = keepFiles)]
    fn keep_files_js(version: &str);
    #[wasm_bindgen(js_name = signedOut)]
    fn signed_out_js() -> String;
    #[wasm_bindgen(js_name = signedIn)]
    fn signed_in_js();
    #[wasm_bindgen(js_name = sessionGone)]
    fn session_gone_js() -> js_sys::Promise;
}

/// STUDIO-32: what [`signed_out`] did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignedOut {
    /// The page names no sign-in (`<meta name="plexus-login">`): nothing.
    None,
    /// The page is on its way to the sign-in, `next` the way back.
    Sent,
    /// The page came back from the sign-in still signed out: said, not sent.
    Said,
}

/// STUDIO-32: the page's session has ended — to the sign-in it names, once
/// (`host.js`'s `signedOut`).
pub fn signed_out() -> SignedOut {
    match signed_out_js().as_str() {
        "sent" => SignedOut::Sent,
        "said" => SignedOut::Said,
        _ => SignedOut::None,
    }
}

/// STUDIO-32: a call was answered — the page is signed in (`host.js`'s
/// `signedIn`).
pub fn signed_in() {
    signed_in_js()
}

/// STUDIO-32: whether the page itself wants a sign-in now (`host.js`'s
/// `sessionGone`) — asked when the socket cannot be opened.
pub async fn session_gone() -> bool {
    wasm_bindgen_futures::JsFuture::from(session_gone_js()).await.ok().and_then(|v| v.as_bool()).unwrap_or(false)
}

/// UI-19: where `url` (a version's file, `/app/<hash>/<path>`) is fetched —
/// its content URL when the page was served with it in its files map
/// (`host.js`'s `fileUrl`), else `url`.
pub fn file_url(url: &str) -> String {
    file_url_js(url)
}

/// UI-19: the page's files kept by the service worker (`host.js`'s
/// `keepFiles`): registered, and told this version's content URLs.
pub fn keep_files(version: &str) {
    keep_files_js(version)
}

/// FRAME-50: `f` in a task of its own, behind what the page has queued
/// (`host.js`'s `yieldTask`).
pub fn yield_then(f: Box<dyn FnOnce()>) {
    yield_task(&Closure::once_into_js(move || f()));
}

/// `v` as a JS value.
pub fn to_js(v: &Value) -> JsValue {
    js_sys::JSON::parse(&v.to_string()).unwrap_or(JsValue::NULL)
}

/// A JS value as JSON (`undefined` and what does not serialise: null).
pub fn from_js(v: &JsValue) -> Value {
    if v.is_undefined() {
        return Value::Null;
    }
    js_sys::JSON::stringify(v).ok().and_then(|s| s.as_string()).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or(Value::Null)
}

/// What a thrown value says: an Error's message, a string, else its debug.
pub fn words(e: &JsValue) -> String {
    js_sys::Reflect::get(e, &"message".into()).ok().and_then(|m| m.as_string()).or_else(|| e.as_string()).unwrap_or_else(|| format!("{e:?}"))
}

fn error(message: &str) -> JsValue {
    js_sys::Error::new(message).into()
}

/// Imports `/app/<version>/components/<name>.js`.
pub async fn import(version: &str, name: &str) -> Result<JsModule, String> {
    let url = format!("/app/{version}/components/{name}.js");
    let ns = wasm_bindgen_futures::JsFuture::from(import_module(&url)).await.map_err(|e| format!("{url}: {}", words(&e)))?;
    Ok(JsModule { ns })
}

/// An imported ES module, as the host mounts it.
pub struct JsModule {
    ns: JsValue,
}

impl Module<Dom> for JsModule {
    /// FRAME-30: the module's `export const css`, its sheet's text.
    fn css(&self) -> Option<String> {
        js_sys::Reflect::get(&self.ns, &"css".into()).ok().and_then(|v| v.as_string())
    }

    fn mount(&self, target: &web_sys::Node, props: &Map<String, Value>, bus: Member) -> Result<Box<dyn ModuleInstance>, String> {
        let shared = Rc::new(RefCell::new(props.clone()));
        let handle = BusHandle { member: bus, props: shared.clone() };
        match mount_module(&self.ns, target, &to_js(&Value::Object(props.clone())), handle) {
            Ok(mounted) => Ok(Box::new(JsInstance { mounted, target: target.clone(), props: shared })),
            Err(e) => {
                // Nothing of a mount that threw stays drawn.
                target.set_text_content(None);
                Err(words(&e))
            }
        }
    }
}

struct JsInstance {
    mounted: JsValue,
    target: web_sys::Node,
    props: Rc<RefCell<Map<String, Value>>>,
}

impl ModuleInstance for JsInstance {
    fn update(&mut self, props: &Map<String, Value>) {
        *self.props.borrow_mut() = props.clone();
        if let Err(e) = update_module(&self.mounted, &to_js(&Value::Object(props.clone()))) {
            web_sys::console::warn_1(&format!("update threw: {}", words(&e)).into());
        }
    }

    fn destroy(self: Box<Self>) {
        if let Err(e) = destroy_module(&self.mounted) {
            web_sys::console::warn_1(&format!("destroy threw: {}", words(&e)).into());
        }
        // Whatever it left behind goes with it.
        self.target.set_text_content(None);
    }
}

/// A mounted module's member of the bus, as `host.js`'s `busOf` wraps it.
#[wasm_bindgen]
pub struct BusHandle {
    member: Member,
    props: Rc<RefCell<Map<String, Value>>>,
}

/// `answer`'s three keys set on `target` (FRAME-37).
fn stamp(target: &JsValue, answer: &Answer, events: &JsValue) {
    let message = answer.message.as_deref().map_or(JsValue::NULL, JsValue::from_str);
    for (k, v) in [("ok", JsValue::from_bool(answer.ok)), ("events", events.clone()), ("message", message)] {
        let _ = js_sys::Reflect::set(target, &k.into(), &v);
    }
}

/// A promise of a call's answer, rejected only when `start` refuses it
/// before the socket (a method outside `uses`: a programming error).
/// FRAME-37: every call that left resolves its answer — the array of its
/// data events (what it always resolved) carrying `ok`, `events` (itself)
/// and `message`, so `const { ok, events, message } = await bus.call(…)`
/// reads what rhx's `call(…, "fold")` folds: `ok` false on an in-band
/// `error` / `refused`, on the service's refusal (its words) and when the
/// socket dropped under it (`"disconnected"`). Never sent again.
fn answered(start: impl FnOnce(Sink) -> Result<(), String>) -> js_sys::Promise {
    let mut start = Some(start);
    js_sys::Promise::new(&mut |resolve: js_sys::Function, reject: js_sys::Function| {
        let resolve = resolve.clone();
        let sink: Sink = answer_sink(move |answer| {
            let events = to_js(&Value::Array(answer.events.clone()));
            stamp(&events, &answer, &events);
            let _ = resolve.call1(&JsValue::NULL, &events);
        });
        if let Some(start) = start.take() {
            if let Err(why) = start(sink) {
                let _ = reject.call1(&JsValue::NULL, &error(&why));
            }
        }
    })
}

/// FRAME-53: `opts[key] === true` (an options object left out is none).
fn option(opts: &JsValue, key: &str) -> bool {
    opts.is_object() && js_sys::Reflect::get(opts, &key.into()).ok().and_then(|v| v.as_bool()).unwrap_or(false)
}

#[wasm_bindgen]
impl BusHandle {
    /// `bus.call(method, params)`.
    pub fn call(&self, method: String, params: JsValue) -> js_sys::Promise {
        let member = self.member.clone();
        let params = from_js(&params);
        answered(move |sink| member.call(&method, params, sink).map(|_| ()).map_err(|r| r.to_string()))
    }

    /// `bus.live(spec)`; a spec that is none, or methods outside `uses`,
    /// thrown. FRAME-19: `when` and `debounce_ms` held by the registry; the
    /// handle's `update(patch)` moves `params`, `changes_params`, `when`.
    pub fn live(&self, spec: JsValue) -> Result<LiveHandle, JsValue> {
        let spec = ModuleSpec::from_value(&from_js(&spec)).map_err(|e| error(&e))?;
        let live = self.member.follow(spec.clone()).map_err(|r| error(&r.to_string()))?;
        let signal = live.signal();
        Ok(LiveHandle(Rc::new(LiveInner { member: self.member.clone(), spec: RefCell::new(spec), signal: RefCell::new(signal), live: RefCell::new(Some(Rc::new(live))), subscribers: Cell::new(0) })))
    }

    /// FRAME-19: `bus.markdown(text)` — the engine's render, sanitized and
    /// written as HTML: what rhx's `{@html markdown(text)}` draws.
    pub fn markdown(&self, text: String) -> String {
        crate::html::to_html(&crate::html::sanitize(&crate::html::markdown(&text)))
    }

    /// `bus.emit(topic, data, { sticky }?)`; a topic under `plexus.`
    /// thrown. FRAME-53: `sticky: true` keeps it as the topic's last event.
    pub fn emit(&self, topic: String, data: JsValue, opts: JsValue) -> Result<(), JsValue> {
        let data = from_js(&data);
        let r = if option(&opts, "sticky") { self.member.emit_sticky(&topic, data) } else { self.member.emit(&topic, data) };
        r.map_err(|r| error(&r.to_string()))
    }

    /// FRAME-53: `bus.last(topic)` — the topic's kept event, or undefined.
    pub fn last(&self, topic: String) -> JsValue {
        self.member.last(&topic).map_or(JsValue::UNDEFINED, |v| to_js(&v))
    }

    /// `bus.on(topic, fn, { last }?)` → unsubscribe. FRAME-53: `last: true`
    /// calls `fn` at once with the topic's kept event, if any.
    pub fn on(&self, topic: String, f: js_sys::Function, opts: JsValue) -> js_sys::Function {
        let t = topic.clone();
        let heard = move |data: &Value| {
            if let Err(e) = f.call1(&JsValue::NULL, &to_js(data)) {
                web_sys::console::error_1(&format!("bus: a listener of {t} threw: {}", words(&e)).into());
            }
        };
        let listening = if option(&opts, "last") { self.member.on_last(&topic, heard) } else { self.member.on(&topic, heard) };
        let held = RefCell::new(Some(listening));
        Closure::<dyn FnMut()>::new(move || drop(held.borrow_mut().take())).into_js_value().unchecked_into()
    }

    /// FRAME-36: `bus.keys({ "ctrl+k": fn, "j": { to: fn, label, in_inputs,
    /// only } })` → unsubscribe — the module's shortcuts in the page's one
    /// registry, rhx's rules; a chord it cannot read, or an entry that is no
    /// function, thrown naming it. They go with the module too (its member
    /// leaves the bus on destroy).
    pub fn keys(&self, map: JsValue) -> Result<js_sys::Function, JsValue> {
        let map = map.dyn_into::<js_sys::Object>().map_err(|_| error("bus.keys({ \"chord\": fn, … }): the keys are one object"))?;
        let mut decls = Vec::new();
        for pair in js_sys::Object::entries(&map).iter() {
            let pair: js_sys::Array = pair.unchecked_into();
            let chord = pair.get(0).as_string().unwrap_or_default();
            let v = pair.get(1);
            let get = |k: &str| js_sys::Reflect::get(&v, &k.into()).ok().filter(|x| !x.is_undefined() && !x.is_null());
            let flag = |k: &str| get(k).and_then(|b| b.as_bool()).unwrap_or(false);
            let (f, label, in_inputs, only, in_controls) = match v.dyn_ref::<js_sys::Function>() {
                Some(f) => (f.clone(), None, false, false, false),
                None => {
                    let f = get("to").and_then(|t| t.dyn_into::<js_sys::Function>().ok()).ok_or_else(|| error(&format!("bus.keys: `{chord}` is a function or {{ to: function, label, in_inputs, only, in_controls }}")))?;
                    (f, get("label").and_then(|l| l.as_string()), flag("in_inputs"), flag("only"), flag("in_controls"))
                }
            };
            // FRAME-38: `{ to: () => … }` names its arrow `to` — no name: the
            // overlay shows the chord.
            let decl = crate::keys::KeyDecl::new(&chord, "", label, in_inputs, only).map_err(|m| error(&format!("bus.keys: {m}")))?.controls(in_controls);
            let to = f.name().as_string().filter(|n| !n.is_empty() && n != "to").unwrap_or_else(|| decl.chord.clone());
            let decl = crate::keys::KeyDecl { to, ..decl };
            if let Some((other, _)) = decls.iter().find(|(d, _): &&(crate::keys::KeyDecl, crate::keys::KeyRun)| crate::keys::hides(&d.seq, &decl.seq) || crate::keys::hides(&decl.seq, &d.seq)) {
                return Err(error(&format!("bus.keys: `{}` and `{}` — one hides the other: a chord bound alone is matched before the sequence it begins", other.chord, decl.chord)));
            }
            let c = decl.chord.clone();
            let run: crate::keys::KeyRun = Rc::new(move |ev: Value| {
                if let Err(e) = f.call1(&JsValue::NULL, &to_js(&ev)) {
                    web_sys::console::error_1(&format!("keys: the function of {c} threw: {}", words(&e)).into());
                }
            });
            decls.push((decl, run));
        }
        let held = RefCell::new(Some(self.member.keys(decls)));
        Ok(Closure::<dyn FnMut()>::new(move || drop(held.borrow_mut().take())).into_js_value().unchecked_into())
    }

    /// `bus.navigate(route)`.
    pub fn navigate(&self, route: String) {
        self.member.navigate(&route);
    }

    /// `bus.slots.set(layout, slot, component, version?)`.
    pub fn slots_set(&self, layout: String, slot: String, component: String, version: Option<String>) -> js_sys::Promise {
        let member = self.member.clone();
        answered(move |sink| member.slots_set(&layout, &slot, &component, version.as_deref(), sink).map(|_| ()).map_err(|r| r.to_string()))
    }

    /// COMPS-2: the member a frame's bridge calls through (`bus.frame`,
    /// host.js) — named `name`, its calls held to `uses`: for a page the
    /// framer wrote (`within`), only what this member's own `uses` names
    /// too; for a stored component, its manifest entry's. Its `call` is the
    /// only one of its members the bridge uses; `leave` when the frame goes.
    pub fn framed(&self, name: String, uses: js_sys::Array, within: bool) -> BusHandle {
        let uses: Vec<String> = uses.iter().filter_map(|u| u.as_string()).collect();
        BusHandle { member: self.member.framed(&name, &uses, within), props: Rc::new(RefCell::new(Map::new())) }
    }

    /// COMPS-2: a frame's member leaves the bus (its frame destroyed).
    pub fn leave(&self) {
        self.member.leave();
    }

    /// `bus.props`: the props now.
    pub fn props(&self) -> JsValue {
        to_js(&Value::Object(self.props.borrow().clone()))
    }
}

struct LiveInner {
    member: Member,
    /// The spec, every update applied (a collection made again after its
    /// last subscriber left starts from it).
    spec: RefCell<ModuleSpec>,
    signal: RefCell<Signal<Value>>,
    /// Held while anyone subscribes (and from `live` until the first does).
    live: RefCell<Option<Rc<ModuleLive>>>,
    subscribers: Cell<usize>,
}

/// `bus.live(spec)`: a store of `{ rows, status }`.
#[wasm_bindgen]
pub struct LiveHandle(Rc<LiveInner>);

fn deliver(f: &js_sys::Function, v: &JsValue) {
    if let Err(e) = f.call1(&JsValue::NULL, v) {
        web_sys::console::error_1(&format!("live: a subscriber threw: {}", words(&e)).into());
    }
}

/// FRAME-20: what crosses to `host.js`'s store for one move of the
/// collection `v` — `{ status, message?, replace: rows }` whole, or
/// `{ status, message?, upsert: [rows], remove: [keys] }`: only the rows
/// the fold touched become JSON.
fn crossing(v: &Value, delta: &Delta) -> JsValue {
    let mut o = Map::new();
    o.insert("status".into(), v.get("status").cloned().unwrap_or(Value::Null));
    if let Some(m) = v.get("message") {
        o.insert("message".into(), m.clone());
    }
    match delta {
        Delta::Whole => {
            o.insert("replace".into(), v.get("rows").cloned().unwrap_or_else(|| Value::Array(Vec::new())));
        }
        Delta::Change { upsert, remove } => {
            o.insert("upsert".into(), Value::Array(upsert.clone()));
            o.insert("remove".into(), Value::Array(remove.iter().cloned().map(Value::String).collect()));
        }
    }
    to_js(&Value::Object(o))
}

#[wasm_bindgen]
impl LiveHandle {
    /// FRAME-19: `update(patch)` — `{ params?, changes_params?, when? }`
    /// over what the collection follows; refused (thrown) naming anything
    /// else. The registry waits `debounce_ms` and holds it while `when` is
    /// false.
    pub fn update(&self, patch: JsValue) -> Result<(), JsValue> {
        let patch = from_js(&patch);
        let inner = &self.0;
        let next = inner.spec.borrow().patched(&patch).map_err(|e| error(&e))?;
        *inner.spec.borrow_mut() = next;
        // No borrow held across it: a subscriber woken by the update may
        // update or unsubscribe.
        let live = inner.live.borrow().clone();
        match live {
            Some(l) => l.update(&patch).map_err(|e| error(&e)),
            None => Ok(()),
        }
    }

    /// The collection now.
    pub fn get(&self) -> JsValue {
        to_js(&self.0.signal.borrow().peek())
    }

    /// `fn` now (before this returns), then on every change in the bus's
    /// turn; the answer unsubscribes, after which `fn` hears nothing.
    /// FRAME-20: `fn` is handed the move, not the collection — [`crossing`]:
    /// the first call and any move it cannot follow whole, else the change;
    /// `host.js`'s store keeps the rows and applies it.
    pub fn subscribe(&self, f: js_sys::Function) -> js_sys::Function {
        let inner = self.0.clone();
        if inner.live.borrow().is_none() {
            let spec = inner.spec.borrow().clone();
            if let Ok(l) = inner.member.follow(spec) {
                *inner.signal.borrow_mut() = l.signal();
                *inner.live.borrow_mut() = Some(Rc::new(l));
            }
        }
        inner.subscribers.set(inner.subscribers.get() + 1);
        let bus: Bus = inner.member.bus().clone();
        let rt = bus.runtime().clone();
        let alive = Rc::new(Cell::new(true));
        let first = Rc::new(Cell::new(true));
        let (sig, a) = (inner.signal.borrow().clone(), alive.clone());
        let live = inner.live.borrow().clone();
        // The move this subscriber saw last.
        let seen = Cell::new(0u64);
        let binding = rt.bind(move || {
            let was_first = first.replace(false);
            let delta = match &live {
                Some(l) if !was_first => {
                    let c = l.since(seen.get());
                    seen.set(c.seq);
                    c.delta
                }
                Some(l) => {
                    seen.set(l.seq());
                    Delta::Whole
                }
                None => Delta::Whole,
            };
            let out = sig.with(|v| a.get().then(|| crossing(v, &delta)));
            let Some(out) = out else { return };
            if was_first {
                deliver(&f, &out);
            } else {
                let (f, a) = (f.clone(), a.clone());
                bus.defer(move || {
                    if a.get() {
                        deliver(&f, &out);
                    }
                });
            }
        });
        Closure::<dyn FnMut()>::new(move || {
            if alive.replace(false) {
                rt.dispose(binding);
                let n = inner.subscribers.get().saturating_sub(1);
                inner.subscribers.set(n);
                if n == 0 {
                    let gone = inner.live.borrow_mut().take();
                    drop(gone);
                }
            }
        })
        .into_js_value()
        .unchecked_into()
    }
}