plexus-ui-engine 0.2.7

The plexus-ui engine — signals, live() over Plexus streams, the view tree over a renderer, Rhai folds, sections, hot-swap
Documentation
//! FRAME-50: **the mount's turns** — while a yield is set ([`App::set_yield`]),
//! a section drawn is not filled in the task that drew it: it waits its
//! turn, and each turn fills one section in a task of its own. So the
//! boot's mount is the layout's own draw, then one section per task, in the
//! order they were drawn (FRAME-12: the layout, then its sections, outer
//! before inner); between two turns the page handles whatever it already
//! has — an answer's frame that arrived while a section mounted is folded
//! before the next one mounts, never after the whole page.
//!
//! A section filled before its turn (an assignment, a `slot_changed`) is
//! filled once: its turn finds it done. A section gone before its turn
//! (its layout unmounted, a route changed) is skipped. Once no section
//! waits, each [`App::when_settled`] runs, in order.
//!
//! **The hold**: a section drawn while the mount yields is held — its
//! element carries `data-plexus-held`, which the engine's own sheet makes
//! `content-visibility: hidden` (its size its own box's, its contents
//! neither laid out nor painted) — until [`App::release`]. So a frame the
//! browser draws between two turns lays out the layout alone, never a
//! half-mounted page, and the page's first real layout is the one the
//! release sets off: the boot releases once the snapshots the mount asked
//! are answered (the rows there), or a cap after it settled.
//!
//! The page's yield is a task posted behind what is queued (`host.js`'s
//! `yieldTask`: a `MessageChannel` message), never `scheduler.yield()`,
//! whose continuation is put before the page's other tasks — the very
//! answers the turn is for. (Measured, FRAME-50: Chromium runs a stream of
//! the socket's frames still arriving before a posted message, so a turn
//! waits out an answer of many frames — a timer or `scheduler.postTask`
//! waits the same.)

use super::App;
use crate::live::Clock;
use crate::transport::Wire;
use crate::tree::Renderer;
use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::rc::Rc;

/// What runs `f` in a task of its own, after the tasks already queued.
pub type Yield = Rc<dyn Fn(Box<dyn FnOnce()>)>;

/// The turns' state: the yield, the sections waiting in order, whether a
/// turn is asked, and what runs once none waits.
pub(super) struct Turns<N> {
    yielder: RefCell<Option<Yield>>,
    queue: RefCell<VecDeque<u64>>,
    asked: Cell<bool>,
    settled: RefCell<Vec<Box<dyn FnOnce()>>>,
    /// The sections' elements held, until the release.
    held: RefCell<Vec<N>>,
}

impl<N> Default for Turns<N> {
    fn default() -> Self {
        Self { yielder: RefCell::default(), queue: RefCell::default(), asked: Cell::default(), settled: RefCell::default(), held: RefCell::default() }
    }
}

/// The hold's attribute, and the engine's sheet that hides what carries it.
pub const HELD: &str = "data-plexus-held";
const HELD_SHEET: (&str, &str) = ("plexus-ui-held", "[data-plexus-held] { content-visibility: hidden; }");

impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> App<R, W, C> {
    /// FRAME-50: from now on, each section drawn waits its turn, `y` asking
    /// for it; `None` fills every section as it is drawn again (the
    /// sections already waiting keep their turns).
    pub fn set_yield(&self, y: Option<Yield>) {
        *self.turns.yielder.borrow_mut() = y;
    }

    /// FRAME-50: `f`, once no section waits its turn — now, when none does.
    pub fn when_settled(&self, f: Box<dyn FnOnce()>) {
        if self.turns.queue.borrow().is_empty() {
            return f();
        }
        self.turns.settled.borrow_mut().push(f);
    }

    /// FRAME-50: how many sections wait their turn.
    pub fn queued(&self) -> usize {
        self.turns.queue.borrow().len()
    }

    /// Section `sid`, filled now — or, while a yield is set, in its turn.
    pub(super) fn fill_soon(&self, sid: u64) {
        if self.turns.yielder.borrow().is_none() {
            return self.fill(sid);
        }
        let Some(div) = self.with_section(sid, |s| {
            s.queued = true;
            s.div.clone()
        }) else {
            return;
        };
        self.hold(&div);
        self.turns.queue.borrow_mut().push_back(sid);
        self.ask_turn();
    }

    /// `div` held until the release; the first one held puts the sheet up.
    fn hold(&self, div: &R::Node) {
        let first = {
            let mut held = self.turns.held.borrow_mut();
            held.push(div.clone());
            held.len() == 1
        };
        if first {
            self.renderer.sheet(HELD_SHEET.0, HELD_SHEET.1, true);
        }
        self.renderer.set_attr(div, HELD, "");
    }

    /// FRAME-50: every section held drawn — its attribute taken off, the
    /// sheet down — in one change, so the page lays them out together.
    pub fn release(&self) {
        let held = std::mem::take(&mut *self.turns.held.borrow_mut());
        if held.is_empty() {
            return;
        }
        for div in &held {
            self.renderer.remove_attr(div, HELD);
        }
        self.renderer.sheet(HELD_SHEET.0, "", false);
    }

    /// FRAME-50: how many sections are held.
    pub fn held(&self) -> usize {
        self.turns.held.borrow().len()
    }

    fn ask_turn(&self) {
        if self.turns.asked.replace(true) {
            return;
        }
        // The sections drawn before the yield was taken away keep theirs.
        let y = self.turns.yielder.borrow().clone();
        let me = self.me.clone();
        let turn = Box::new(move || {
            if let Some(app) = me.upgrade() {
                app.turn();
            }
        });
        match y {
            Some(y) => y(turn),
            None => turn(),
        }
    }

    /// One turn: the first section waiting filled (unless it was meanwhile,
    /// or is gone), then the next turn asked — or, none waiting, the
    /// settled callbacks run.
    fn turn(&self) {
        self.turns.asked.set(false);
        let next = self.turns.queue.borrow_mut().pop_front();
        if let Some(sid) = next {
            if self.with_section(sid, |s| s.queued).unwrap_or(false) {
                self.fill(sid);
                self.told_needs();
            }
        }
        if !self.turns.queue.borrow().is_empty() {
            return self.ask_turn();
        }
        let settled = std::mem::take(&mut *self.turns.settled.borrow_mut());
        for f in settled {
            f();
        }
    }
}

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