Skip to main content

plexus_ui_engine/swap/
turns.rs

1//! FRAME-50: **the mount's turns** — while a yield is set ([`App::set_yield`]),
2//! a section drawn is not filled in the task that drew it: it waits its
3//! turn, and each turn fills one section in a task of its own. So the
4//! boot's mount is the layout's own draw, then one section per task, in the
5//! order they were drawn (FRAME-12: the layout, then its sections, outer
6//! before inner); between two turns the page handles whatever it already
7//! has — an answer's frame that arrived while a section mounted is folded
8//! before the next one mounts, never after the whole page.
9//!
10//! A section filled before its turn (an assignment, a `slot_changed`) is
11//! filled once: its turn finds it done. A section gone before its turn
12//! (its layout unmounted, a route changed) is skipped. Once no section
13//! waits, each [`App::when_settled`] runs, in order.
14//!
15//! **The hold**: a section drawn while the mount yields is held — its
16//! element carries `data-plexus-held`, which the engine's own sheet makes
17//! `content-visibility: hidden` (its size its own box's, its contents
18//! neither laid out nor painted) — until [`App::release`]. So a frame the
19//! browser draws between two turns lays out the layout alone, never a
20//! half-mounted page, and the page's first real layout is the one the
21//! release sets off: the boot releases once the snapshots the mount asked
22//! are answered (the rows there), or a cap after it settled.
23//!
24//! The page's yield is a task posted behind what is queued (`host.js`'s
25//! `yieldTask`: a `MessageChannel` message), never `scheduler.yield()`,
26//! whose continuation is put before the page's other tasks — the very
27//! answers the turn is for. (Measured, FRAME-50: Chromium runs a stream of
28//! the socket's frames still arriving before a posted message, so a turn
29//! waits out an answer of many frames — a timer or `scheduler.postTask`
30//! waits the same.)
31
32use super::App;
33use crate::live::Clock;
34use crate::transport::Wire;
35use crate::tree::Renderer;
36use std::cell::{Cell, RefCell};
37use std::collections::VecDeque;
38use std::rc::Rc;
39
40/// What runs `f` in a task of its own, after the tasks already queued.
41pub type Yield = Rc<dyn Fn(Box<dyn FnOnce()>)>;
42
43/// The turns' state: the yield, the sections waiting in order, whether a
44/// turn is asked, and what runs once none waits.
45pub(super) struct Turns<N> {
46    yielder: RefCell<Option<Yield>>,
47    queue: RefCell<VecDeque<u64>>,
48    asked: Cell<bool>,
49    settled: RefCell<Vec<Box<dyn FnOnce()>>>,
50    /// The sections' elements held, until the release.
51    held: RefCell<Vec<N>>,
52}
53
54impl<N> Default for Turns<N> {
55    fn default() -> Self {
56        Self { yielder: RefCell::default(), queue: RefCell::default(), asked: Cell::default(), settled: RefCell::default(), held: RefCell::default() }
57    }
58}
59
60/// The hold's attribute, and the engine's sheet that hides what carries it.
61pub const HELD: &str = "data-plexus-held";
62const HELD_SHEET: (&str, &str) = ("plexus-ui-held", "[data-plexus-held] { content-visibility: hidden; }");
63
64impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> App<R, W, C> {
65    /// FRAME-50: from now on, each section drawn waits its turn, `y` asking
66    /// for it; `None` fills every section as it is drawn again (the
67    /// sections already waiting keep their turns).
68    pub fn set_yield(&self, y: Option<Yield>) {
69        *self.turns.yielder.borrow_mut() = y;
70    }
71
72    /// FRAME-50: `f`, once no section waits its turn — now, when none does.
73    pub fn when_settled(&self, f: Box<dyn FnOnce()>) {
74        if self.turns.queue.borrow().is_empty() {
75            return f();
76        }
77        self.turns.settled.borrow_mut().push(f);
78    }
79
80    /// FRAME-50: how many sections wait their turn.
81    pub fn queued(&self) -> usize {
82        self.turns.queue.borrow().len()
83    }
84
85    /// Section `sid`, filled now — or, while a yield is set, in its turn.
86    pub(super) fn fill_soon(&self, sid: u64) {
87        if self.turns.yielder.borrow().is_none() {
88            return self.fill(sid);
89        }
90        let Some(div) = self.with_section(sid, |s| {
91            s.queued = true;
92            s.div.clone()
93        }) else {
94            return;
95        };
96        self.hold(&div);
97        self.turns.queue.borrow_mut().push_back(sid);
98        self.ask_turn();
99    }
100
101    /// `div` held until the release; the first one held puts the sheet up.
102    fn hold(&self, div: &R::Node) {
103        let first = {
104            let mut held = self.turns.held.borrow_mut();
105            held.push(div.clone());
106            held.len() == 1
107        };
108        if first {
109            self.renderer.sheet(HELD_SHEET.0, HELD_SHEET.1, true);
110        }
111        self.renderer.set_attr(div, HELD, "");
112    }
113
114    /// FRAME-50: every section held drawn — its attribute taken off, the
115    /// sheet down — in one change, so the page lays them out together.
116    pub fn release(&self) {
117        let held = std::mem::take(&mut *self.turns.held.borrow_mut());
118        if held.is_empty() {
119            return;
120        }
121        for div in &held {
122            self.renderer.remove_attr(div, HELD);
123        }
124        self.renderer.sheet(HELD_SHEET.0, "", false);
125    }
126
127    /// FRAME-50: how many sections are held.
128    pub fn held(&self) -> usize {
129        self.turns.held.borrow().len()
130    }
131
132    fn ask_turn(&self) {
133        if self.turns.asked.replace(true) {
134            return;
135        }
136        // The sections drawn before the yield was taken away keep theirs.
137        let y = self.turns.yielder.borrow().clone();
138        let me = self.me.clone();
139        let turn = Box::new(move || {
140            if let Some(app) = me.upgrade() {
141                app.turn();
142            }
143        });
144        match y {
145            Some(y) => y(turn),
146            None => turn(),
147        }
148    }
149
150    /// One turn: the first section waiting filled (unless it was meanwhile,
151    /// or is gone), then the next turn asked — or, none waiting, the
152    /// settled callbacks run.
153    fn turn(&self) {
154        self.turns.asked.set(false);
155        let next = self.turns.queue.borrow_mut().pop_front();
156        if let Some(sid) = next {
157            if self.with_section(sid, |s| s.queued).unwrap_or(false) {
158                self.fill(sid);
159                self.told_needs();
160            }
161        }
162        if !self.turns.queue.borrow().is_empty() {
163            return self.ask_turn();
164        }
165        let settled = std::mem::take(&mut *self.turns.settled.borrow_mut());
166        for f in settled {
167            f();
168        }
169    }
170}
171
172#[cfg(test)]
173#[path = "tests_turns.rs"]
174mod tests;