plexus-ui-engine 0.2.2

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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
//! FRAME-12: **the bus** — what the host hands every mounted component,
//! whatever drew it (the rhx runtime, a module written by hand, FRAME-13's
//! Svelte): one [`Bus`] per page, one [`Member`] per mounted component.
//!
//! - `call(method, params)` — through the page's one socket, refused before
//!   it when the component's `uses` does not name the method; FRAME-37: its
//!   stream gathered into one [`Answer`] by [`answer_sink`] — what rhx's
//!   `call(method, params, "fold")` folds and a module's `bus.call` resolves;
//! - `live(spec)` — the page's live collection for that spec (the whole
//!   spec: snapshot, params, changes, changes params, key, folds), shared
//!   with every other reader of it, rhx or not; its methods held to `uses`;
//!   FRAME-19: a module's ([`Member::follow`]) held by its `when` and its
//!   param changes coalesced by its `debounce_ms`, as rhx's are;
//! - `emit(topic, data)` / `on(topic, f)` — page-wide, topics bare strings
//!   matched whole, `plexus.` the host's own (a component's emit under it is
//!   refused); a member never hears its own emit;
//! - FRAME-53: **a sticky topic** — [`Member::emit_sticky`] (and the host's
//!   [`Bus::say_sticky`], `plexus.booted`) keeps the topic's last event on
//!   the bus, one per topic; a later emit on it, sticky or not, replaces
//!   it, and it goes when the member that said it leaves (a remount says
//!   it again; the host's own are never cleared). [`Member::on_last`] hears
//!   the kept event at once (in the bus's turn: now, when nothing is under
//!   way or held), then as [`Member::on`]; [`Bus::last`] answers it — only
//!   what has been delivered. A topic never emitted sticky is kept for no
//!   one;
//! - `navigate(route)`; `slots_set(layout, slot, component, version?)` —
//!   `ui.slots.set`, a call like any other, held to `uses`; FRAME-29: a
//!   section a mark binds (`data-component`) is refused `bound` before it.
//!
//! **Delivery waits its turn.** Everything the bus hands out — each
//! listener's event, each deferred callback ([`Bus::defer`], a module's
//! `subscribe`) — goes through one queue, first in first out, and is run
//! only when nothing of the host's is under way: an emit made inside a
//! delivery, or inside an rhx fold ([`Bus::hold`] around it), is heard
//! after the one under way has reached every listener. Nothing is
//! re-entered, so no borrow of the host's is ever held across a component.
//!
//! FRAME-36: `keys(decls)` — a component's shortcuts into the page's one
//! registry ([`crate::keys::Keys`]), held until the answer is dropped or
//! the member leaves.
//!
//! A member that [`Member::leave`]s (its component unmounted or swapped
//! out) hears nothing more and reaches no one.

use crate::live::{LiveSpec, ModuleLive, ModuleSpec, Reader};
use crate::transport::{CallId, Sink, WireItem};
use serde_json::{json, Value};
use std::cell::{Cell, RefCell};
use std::collections::{BTreeSet, VecDeque};
use std::rc::{Rc, Weak};

/// The prefix of the host's own topics.
pub const RESERVED: &str = "plexus.";

/// FRAME-37: what `message` says when the socket dropped before the answer.
pub const DISCONNECTED: &str = "disconnected";

/// FRAME-37: a call's answer, whole, once its stream ended — `ok` when it
/// ended with no in-band `error` / `refused` event, no refusal, no failure
/// and no drop; `events` its data events in order (each a map with `type`);
/// `message` the error's, refusal's or failure's words (an in-band one's
/// `message`, else its `reason`), or [`DISCONNECTED`] for a drop, when not
/// `ok`.
#[derive(Debug, Clone, PartialEq)]
pub struct Answer {
    pub ok: bool,
    pub events: Vec<Value>,
    pub message: Option<String>,
}

impl Answer {
    /// `{ ok, events, message }` (`message` null when `ok`).
    pub fn to_value(&self) -> Value {
        json!({ "ok": self.ok, "events": self.events, "message": self.message })
    }
}

/// An in-band refusal's words: an event whose `type` is `error` or
/// `refused`, its `message`, else its `reason`, else its type.
fn in_band(event: &Value) -> Option<String> {
    let kind = event.get("type").and_then(Value::as_str).filter(|t| *t == "error" || *t == "refused")?;
    let words = ["message", "reason"].iter().find_map(|k| event.get(*k).filter(|v| !v.is_null()));
    Some(match words {
        Some(Value::String(s)) => s.clone(),
        Some(v) => v.to_string(),
        None => kind.to_string(),
    })
}

/// FRAME-37: a sink that gathers a call's stream and hands `done` its
/// [`Answer`] once, when the stream ends (`Done`, a refusal, or the socket
/// dropping under it). Nothing here sends anything: a call is sent once.
pub fn answer_sink(done: impl FnOnce(Answer) + 'static) -> Sink {
    let mut events = Vec::new();
    let mut done = Some(done);
    Box::new(move |item| {
        let ended = match item {
            WireItem::Data(v) => {
                events.push(v);
                return;
            }
            WireItem::Done => None,
            WireItem::Refused(m) => Some(m),
            WireItem::Failed(m) => Some(m),
            WireItem::Dropped => Some(DISCONNECTED.to_string()),
        };
        let Some(done) = done.take() else { return };
        let events = std::mem::take(&mut events);
        // An in-band refusal says more than how the stream ended.
        let message = events.iter().find_map(in_band).or(ended);
        done(Answer { ok: message.is_none(), events, message });
    })
}

/// What the bus refuses a member, before anything reaches the socket.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BusRefusal {
    /// The component's `uses` does not name the method.
    NotInUses { component: String, method: String },
    /// A topic under `plexus.`, the host's.
    Reserved { component: String, topic: String },
    /// FRAME-29: `slots_set` on a section its mark binds — early-bound, the
    /// component its code chose; no assignment reaches it.
    Bound { layout: String, slot: String, component: String },
}

impl std::fmt::Display for BusRefusal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BusRefusal::NotInUses { component, method } => write!(f, "{component} calls {method}, which its uses does not name"),
            BusRefusal::Reserved { component, topic } => write!(f, "{component} emits {topic}: topics under {RESERVED} are the host's"),
            BusRefusal::Bound { layout, slot, component } => {
                write!(f, "bound: {layout} · {slot} is bound to {component} by its mark (data-component); ui.slots.set does not reach it")
            }
        }
    }
}

/// What the bus needs of the host: the socket, the live cache, the router
/// and the live version.
pub trait BusHost {
    fn open(&self, method: &str, params: Value, sink: Sink) -> CallId;
    fn live(&self, spec: &LiveSpec) -> Reader;
    /// FRAME-19: a module's collection, held by `when`, coalesced by
    /// `debounce_ms`.
    fn follow(&self, spec: ModuleSpec) -> ModuleLive;
    fn navigate(&self, route: &str);
    /// The live version's hash (`slots_set` with no version names it).
    fn live_version(&self) -> String;
    /// FRAME-29: the component a mark binds `layout`'s `slot` to, when one
    /// does — `slots_set` on it is refused `bound`.
    fn bound(&self, _layout: &str, _slot: &str) -> Option<String> {
        None
    }
}

struct Listener {
    id: u64,
    member: u64,
    topic: String,
    f: Rc<dyn Fn(&Value)>,
}

enum Item {
    /// `keep`: whether its delivery may keep it (false once its member left).
    Message { from: u64, topic: String, data: Value, sticky: bool, keep: bool },
    Run(Box<dyn FnOnce()>),
}

/// FRAME-53: a sticky topic's last event, and the member that said it.
struct Kept {
    from: u64,
    data: Value,
}

struct Inner {
    host: RefCell<Option<Weak<dyn BusHost>>>,
    rt: crate::signals::Runtime,
    listeners: RefCell<Vec<Listener>>,
    /// FRAME-53: each sticky topic's last event, by topic.
    kept: RefCell<std::collections::BTreeMap<String, Kept>>,
    queue: RefCell<VecDeque<Item>>,
    holds: Cell<u32>,
    draining: Cell<bool>,
    next: Cell<u64>,
    /// FRAME-36: the page's keys.
    keys: crate::keys::Keys,
}

/// The page's one bus (a handle: clones are the same bus).
#[derive(Clone)]
pub struct Bus(Rc<Inner>);

impl std::fmt::Debug for Bus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Bus({} listeners, {} queued)", self.0.listeners.borrow().len(), self.0.queue.borrow().len())
    }
}

impl Bus {
    /// A bus over the signals of `rt`; the host is set by [`Self::set_host`].
    pub fn new(rt: &crate::signals::Runtime) -> Self {
        Self(Rc::new(Inner {
            host: RefCell::new(None),
            rt: rt.clone(),
            listeners: RefCell::new(Vec::new()),
            kept: RefCell::new(std::collections::BTreeMap::new()),
            queue: RefCell::new(VecDeque::new()),
            holds: Cell::new(0),
            draining: Cell::new(false),
            next: Cell::new(0),
            keys: crate::keys::Keys::default(),
        }))
    }

    pub fn set_host(&self, host: Weak<dyn BusHost>) {
        *self.0.host.borrow_mut() = Some(host);
    }

    fn host(&self) -> Option<Rc<dyn BusHost>> {
        self.0.host.borrow().as_ref().and_then(Weak::upgrade)
    }

    /// FRAME-36: the page's keys — every mounted component's shortcuts.
    pub fn keys(&self) -> &crate::keys::Keys {
        &self.0.keys
    }

    /// The signals the bus's collections live on.
    pub fn runtime(&self) -> &crate::signals::Runtime {
        &self.0.rt
    }

    fn next(&self) -> u64 {
        let n = self.0.next.get() + 1;
        self.0.next.set(n);
        n
    }

    /// A member: what the mounted component `name`, whose `uses` is
    /// `uses`, is handed.
    pub fn join(&self, name: &str, uses: &[String]) -> Member {
        Member(Rc::new(MemberInner { bus: self.clone(), id: self.next(), name: name.into(), uses: uses.iter().cloned().collect(), left: Cell::new(false) }))
    }

    /// FRAME-50: the host's own word — `data` on `topic` (under `plexus.`)
    /// to every member listening, in the bus's turn.
    pub fn say(&self, topic: &str, data: Value) {
        self.send(self.next(), topic, data, false);
    }

    /// FRAME-53: the host's word, kept as the topic's last event — what a
    /// late [`Member::on_last`] hears (`plexus.booted`).
    pub fn say_sticky(&self, topic: &str, data: Value) {
        self.send(self.next(), topic, data, true);
    }

    /// FRAME-53: `topic`'s kept event, if it is sticky and was said.
    pub fn last(&self, topic: &str) -> Option<Value> {
        self.0.kept.borrow().get(topic).map(|k| k.data.clone())
    }

    fn send(&self, from: u64, topic: &str, data: Value, sticky: bool) {
        self.0.queue.borrow_mut().push_back(Item::Message { from, topic: topic.into(), data, sticky, keep: true });
        self.drain();
    }

    /// Runs `f` in the bus's turn: now when nothing is under way, else
    /// after what is.
    pub fn defer(&self, f: impl FnOnce() + 'static) {
        self.0.queue.borrow_mut().push_back(Item::Run(Box::new(f)));
        self.drain();
    }

    /// Holds every delivery until the guard is dropped (the host holds the
    /// bus while a fold runs).
    pub fn hold(&self) -> Hold {
        self.0.holds.set(self.0.holds.get() + 1);
        Hold(self.clone())
    }

    fn drain(&self) {
        if self.0.holds.get() > 0 || self.0.draining.get() {
            return;
        }
        self.0.draining.set(true);
        loop {
            let next = self.0.queue.borrow_mut().pop_front();
            match next {
                None => break,
                Some(Item::Run(f)) => f(),
                Some(Item::Message { from, topic, data, sticky, keep }) => {
                    // FRAME-53: kept as it is delivered — a sticky emit, or
                    // any later emit on a topic once made sticky, replaces
                    // the topic's last event.
                    if keep {
                        let mut kept = self.0.kept.borrow_mut();
                        if sticky || kept.contains_key(&topic) {
                            kept.insert(topic.clone(), Kept { from, data: data.clone() });
                        }
                    }
                    let hit: Vec<(u64, Rc<dyn Fn(&Value)>)> =
                        self.0.listeners.borrow().iter().filter(|l| l.topic == topic && l.member != from).map(|l| (l.id, l.f.clone())).collect();
                    for (id, f) in hit {
                        // One that stopped listening meanwhile hears nothing.
                        if self.0.listeners.borrow().iter().any(|l| l.id == id) {
                            f(&data);
                        }
                    }
                }
            }
        }
        self.0.draining.set(false);
    }
}

/// [`Bus::hold`]'s guard: dropping it lets the queue run.
pub struct Hold(Bus);

impl Drop for Hold {
    fn drop(&mut self) {
        let inner = &self.0 .0;
        inner.holds.set(inner.holds.get().saturating_sub(1));
        self.0.drain();
    }
}

struct MemberInner {
    bus: Bus,
    id: u64,
    name: String,
    uses: BTreeSet<String>,
    left: Cell<bool>,
}

/// One mounted component's side of the bus (a handle).
#[derive(Clone)]
pub struct Member(Rc<MemberInner>);

impl std::fmt::Debug for Member {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Member({} #{})", self.0.name, self.0.id)
    }
}

/// A listener held: dropping it stops it.
pub struct Listening {
    bus: Weak<Inner>,
    id: u64,
}

impl Drop for Listening {
    fn drop(&mut self) {
        if let Some(inner) = self.bus.upgrade() {
            inner.listeners.borrow_mut().retain(|l| l.id != self.id);
        }
    }
}

impl Member {
    /// The component's name.
    pub fn name(&self) -> &str {
        &self.0.name
    }

    /// The bus it is a member of.
    pub fn bus(&self) -> &Bus {
        &self.0.bus
    }

    /// COMPS-2: **a frame's member** — what a page or component this member
    /// frames (`bus.frame`) calls through: a member of the same bus named
    /// `name`, its calls held to `uses`. `within`: a page the framer wrote
    /// (`{ html }`), whose `uses` the framer declares, so only what the
    /// framer's own `uses` names is kept — a framer gives no more than it
    /// holds; not `within`: a stored component (`{ component }`), whose
    /// `uses` is its own manifest entry's. Either way the call goes over the
    /// page's one socket as the viewer, so the service's gate holds it to
    /// the viewer's grants too.
    pub fn framed(&self, name: &str, uses: &[String], within: bool) -> Member {
        let kept: Vec<String> = uses.iter().filter(|m| !within || self.0.uses.contains(*m)).cloned().collect();
        self.0.bus.join(name, &kept)
    }

    /// COMPS-2: whether `method` is one this member may call.
    pub fn holds(&self, method: &str) -> bool {
        self.0.uses.contains(method)
    }

    fn left(&self) -> bool {
        self.0.left.get()
    }

    fn held(&self, method: &str) -> Result<(), BusRefusal> {
        if self.0.uses.contains(method) {
            Ok(())
        } else {
            Err(BusRefusal::NotInUses { component: self.0.name.clone(), method: method.into() })
        }
    }

    /// `method` through the page's socket, its items into `sink`; refused
    /// before the socket when `uses` does not name it.
    pub fn call(&self, method: &str, params: Value, sink: Sink) -> Result<CallId, BusRefusal> {
        self.held(method)?;
        let host = self.0.bus.host().ok_or_else(|| BusRefusal::NotInUses { component: self.0.name.clone(), method: method.into() })?;
        Ok(host.open(method, params, sink))
    }

    /// The page's collection for `spec`, shared; its snapshot and changes
    /// methods held to `uses`.
    pub fn live(&self, spec: &LiveSpec) -> Result<Reader, BusRefusal> {
        self.held(&spec.snapshot)?;
        if let Some(c) = &spec.changes {
            self.held(c)?;
        }
        let host = self.0.bus.host().ok_or_else(|| BusRefusal::NotInUses { component: self.0.name.clone(), method: spec.snapshot.clone() })?;
        Ok(host.live(spec))
    }

    /// `data` on `topic` to every other member listening; `plexus.…`
    /// refused. A member that left reaches no one.
    pub fn emit(&self, topic: &str, data: Value) -> Result<(), BusRefusal> {
        self.emit_with(topic, data, false)
    }

    /// FRAME-53: [`Self::emit`], the event kept as the topic's last — what a
    /// member that listens later with [`Self::on_last`] hears at once.
    pub fn emit_sticky(&self, topic: &str, data: Value) -> Result<(), BusRefusal> {
        self.emit_with(topic, data, true)
    }

    fn emit_with(&self, topic: &str, data: Value, sticky: bool) -> Result<(), BusRefusal> {
        if topic.starts_with(RESERVED) {
            return Err(BusRefusal::Reserved { component: self.0.name.clone(), topic: topic.into() });
        }
        if self.left() {
            return Ok(());
        }
        self.0.bus.send(self.0.id, topic, data, sticky);
        Ok(())
    }

    /// FRAME-53: `topic`'s kept event (the page's, whoever said it).
    pub fn last(&self, topic: &str) -> Option<Value> {
        self.0.bus.last(topic)
    }

    /// FRAME-53: [`Self::on`], and first the topic's kept event, if any,
    /// at once — in the bus's turn: now when nothing is under way, else
    /// right after what is. Not the member's own, and not when an event of
    /// the topic reached `f` first (a newer one than the kept).
    pub fn on_last(&self, topic: &str, f: impl Fn(&Value) + 'static) -> Listening {
        let heard = Rc::new(Cell::new(false));
        let f: Rc<dyn Fn(&Value)> = Rc::new(f);
        let (h, g) = (heard.clone(), f.clone());
        let listening = self.on(topic, move |data: &Value| {
            h.set(true);
            g(data)
        });
        if !self.left() {
            let (bus, me, id, topic) = (Rc::downgrade(&self.0.bus.0), self.0.id, listening.id, topic.to_string());
            self.0.bus.defer(move || {
                let Some(inner) = bus.upgrade() else { return };
                if heard.get() || !inner.listeners.borrow().iter().any(|l| l.id == id) {
                    return;
                }
                let kept = inner.kept.borrow().get(&topic).filter(|k| k.from != me).map(|k| k.data.clone());
                if let Some(data) = kept {
                    f(&data);
                }
            });
        }
        listening
    }

    /// `f` on every `topic` another member emits, until the [`Listening`] is
    /// dropped or the member leaves.
    pub fn on(&self, topic: &str, f: impl Fn(&Value) + 'static) -> Listening {
        let id = self.0.bus.next();
        if !self.left() {
            self.0.bus.0.listeners.borrow_mut().push(Listener { id, member: self.0.id, topic: topic.into(), f: Rc::new(f) });
        }
        Listening { bus: Rc::downgrade(&self.0.bus.0), id }
    }

    /// Moves the page to `route`.
    pub fn navigate(&self, route: &str) {
        if let Some(host) = self.0.bus.host() {
            host.navigate(route);
        }
    }

    /// `ui.slots.set { layout, slot, component, version }` (the live
    /// version when none is named) — a call held to `uses`.
    pub fn slots_set(&self, layout: &str, slot: &str, component: &str, version: Option<&str>, sink: Sink) -> Result<CallId, BusRefusal> {
        self.held("ui.slots.set")?;
        if let Some(component) = self.0.bus.host().and_then(|h| h.bound(layout, slot)) {
            return Err(BusRefusal::Bound { layout: layout.into(), slot: slot.into(), component });
        }
        let version = match version {
            Some(v) => v.to_string(),
            None => self.0.bus.host().map(|h| h.live_version()).unwrap_or_default(),
        };
        self.call("ui.slots.set", json!({ "layout": layout, "slot": slot, "component": component, "version": version }), sink)
    }

    /// FRAME-19: a module's collection for `spec` — `when` and
    /// `debounce_ms` held by the registry as rhx's are, the module moving
    /// its params with [`ModuleLive::update`]; its methods held to `uses`.
    pub fn follow(&self, spec: ModuleSpec) -> Result<ModuleLive, BusRefusal> {
        self.held(&spec.query.snapshot)?;
        if let Some(c) = &spec.query.changes {
            self.held(c)?;
        }
        let host = self.0.bus.host().ok_or_else(|| BusRefusal::NotInUses { component: self.0.name.clone(), method: spec.query.snapshot.clone() })?;
        Ok(host.follow(spec))
    }

    /// FRAME-36: the component's shortcuts, each with what it runs, into
    /// the page's registry until the answer is dropped or the member leaves
    /// (one that left binds nothing).
    pub fn keys(&self, decls: Vec<(crate::keys::KeyDecl, crate::keys::KeyRun)>) -> crate::keys::KeysHeld {
        let decls = if self.left() { Vec::new() } else { decls };
        self.0.bus.0.keys.add(self.0.id, &self.0.name, decls)
    }

    /// Leaves the bus: every listener of it stops, its keys go, and its
    /// emits reach no one. FRAME-53: what it kept goes too — every sticky
    /// topic whose last event it said is kept for no one until said again,
    /// and an emit of its still queued keeps nothing.
    pub fn leave(&self) {
        self.0.left.set(true);
        let me = self.0.id;
        self.0.bus.0.kept.borrow_mut().retain(|_, k| k.from != me);
        for item in self.0.bus.0.queue.borrow_mut().iter_mut() {
            if let Item::Message { from, keep, .. } = item {
                if *from == me {
                    *keep = false;
                }
            }
        }
        self.0.bus.0.keys.remove_member(self.0.id);
        self.0.bus.0.listeners.borrow_mut().retain(|l| l.member != self.0.id);
    }
}