mod boot;
mod turns;
pub use turns::{Yield, HELD};
use crate::bus::{answer_sink, Answer, Bus, BusHost, Listening, Member};
use crate::folds::{FoldError, Folds, Host};
use crate::live::{Clock, Follow, LiveCache, LiveQuery, LiveSpec, ModuleLive, ModuleSpec, Reader};
use crate::module::{Module, ModuleInstance, RHX};
use crate::transport::{CallId, Sink};
use crate::signals::{Runtime, Signal};
use crate::transport::Wire;
use crate::tree::{Children, ComponentTree, Mounted, Renderer, Scope, State};
use serde_json::{Map, Value};
use sha2::Digest;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::{Rc, Weak};
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ComponentEntry {
pub tree: String,
pub handlers: String,
pub uses: Vec<String>,
pub profile: String,
pub module: String,
pub css: String,
}
impl ComponentEntry {
pub fn is_rhx(&self) -> bool {
self.profile.is_empty() || self.profile == RHX
}
pub fn hashes(&self) -> (String, String) {
if self.is_rhx() {
(self.tree.clone(), self.handlers.clone())
} else {
(self.module.clone(), self.css.clone())
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Manifest {
pub abi: String,
pub contract: String,
pub commit: String,
pub routes: BTreeMap<String, String>,
pub components: BTreeMap<String, ComponentEntry>,
pub slots: BTreeMap<String, BTreeMap<String, String>>,
}
impl Manifest {
pub fn parse(json: &str) -> Result<Self, String> {
let v: Value = serde_json::from_str(json).map_err(|e| format!("manifest.json: {e}"))?;
let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
let map = |k: &str| -> BTreeMap<String, String> {
v.get(k).and_then(Value::as_object).map(|o| o.iter().filter_map(|(a, b)| Some((a.clone(), b.as_str()?.to_string()))).collect()).unwrap_or_default()
};
let components = v
.get("components")
.and_then(Value::as_object)
.ok_or("manifest.json names no components")?
.iter()
.map(|(name, e)| {
let f = |k: &str| e.get(k).and_then(Value::as_str).map(str::to_string).ok_or(format!("manifest.json: {name} has no {k}"));
let uses = e.get("uses").and_then(Value::as_array).map(|a| a.iter().filter_map(|u| u.as_str().map(str::to_string)).collect()).unwrap_or_default();
let profile = e.get("profile").and_then(Value::as_str).unwrap_or(RHX).to_string();
let css = e.get("css").and_then(Value::as_str).unwrap_or_default().to_string();
let entry = if profile == RHX {
ComponentEntry { tree: f("tree")?, handlers: f("handlers")?, uses, profile, module: String::new(), css }
} else {
ComponentEntry { module: f("module")?, uses, profile, css, ..ComponentEntry::default() }
};
Ok((name.clone(), entry))
})
.collect::<Result<_, String>>()?;
let slots = v
.get("slots")
.and_then(Value::as_object)
.map(|o| {
o.iter()
.map(|(layout, m)| {
let m = m.as_object().map(|m| m.iter().filter_map(|(a, b)| Some((a.clone(), b.as_str()?.to_string()))).collect()).unwrap_or_default();
(layout.clone(), m)
})
.collect()
})
.unwrap_or_default();
Ok(Self { abi: s("abi"), contract: s("contract"), commit: s("commit"), routes: map("routes"), components, slots })
}
}
#[derive(Debug, Clone, Default)]
pub struct Files {
by_version: BTreeMap<(String, String), (Rc<str>, Rc<str>)>,
sheets: BTreeMap<(String, String), Rc<str>>,
}
pub fn sha256_hex(text: &str) -> String {
sha2::Sha256::digest(text.as_bytes()).iter().map(|b| format!("{b:02x}")).collect()
}
impl Files {
pub fn put_version(&mut self, version: &str, name: &str, tree: &str, handlers: &str) {
self.by_version.insert((version.into(), name.into()), (Rc::from(tree), Rc::from(handlers)));
}
pub fn put_sheet(&mut self, version: &str, name: &str, css: &str) {
self.sheets.insert((version.into(), name.into()), Rc::from(css));
}
pub fn sheet(&self, version: &str, name: &str) -> Option<Rc<str>> {
self.sheets.get(&(version.to_string(), name.to_string())).cloned()
}
pub fn version(&self, version: &str, name: &str) -> Option<(&str, &str)> {
self.by_version.get(&(version.to_string(), name.to_string())).map(|(t, h)| (&**t, &**h))
}
pub fn share(&mut self, from: &str, to: &str, name: &str) -> bool {
let Some(files) = self.by_version.get(&(from.to_string(), name.to_string())).cloned() else { return false };
self.by_version.insert((to.into(), name.into()), files);
if let Some(css) = self.sheet(from, name) {
self.sheets.insert((to.into(), name.into()), css);
}
true
}
pub fn kept_bytes(&self) -> usize {
let mut seen = std::collections::BTreeSet::new();
let texts = self.by_version.values().flat_map(|(t, h)| [t, h]).chain(self.sheets.values());
texts.filter(|x| seen.insert(Rc::as_ptr(x) as *const u8 as usize)).map(|x| x.len()).sum()
}
pub fn extend(&mut self, other: &Files) {
self.by_version.extend(other.by_version.iter().map(|(k, v)| (k.clone(), v.clone())));
self.sheets.extend(other.sheets.iter().map(|(k, v)| (k.clone(), v.clone())));
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Assignment {
pub layout: String,
pub slot: String,
pub component: String,
pub version: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MountId(pub u64);
#[derive(Debug, Clone, PartialEq, Default)]
pub struct SwapReport {
pub remounted: Vec<MountId>,
pub failed: Vec<(MountId, String)>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum SwapError {
Unknown(String),
Missing(String, String),
Failed { component: String, message: String },
}
impl std::fmt::Display for SwapError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SwapError::Unknown(c) => write!(f, "no component {c} in this version"),
SwapError::Missing(v, n) => write!(f, "{n} of {v} is not fetched yet"),
SwapError::Failed { component, message } => write!(f, "{component} failed to mount: {message}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Menu {
pub component: String,
pub components: Vec<String>,
pub versions: Vec<String>,
}
type MemberSlot = Rc<RefCell<Option<(Member, MountId)>>>;
enum Prepared<R: Renderer> {
Rhx { version: String, tree: Rc<ComponentTree>, folds: Rc<Folds>, tree_hash: String, handlers_hash: String, slot: MemberSlot, css: Sheet },
Module { version: String, name: String, hash: String, css: String, uses: Vec<String>, module: Rc<dyn Module<R>> },
}
type Sheet = Option<(String, Rc<str>)>;
impl<R: Renderer> Prepared<R> {
fn version(&self) -> &str {
match self {
Prepared::Rhx { version, .. } | Prepared::Module { version, .. } => version,
}
}
fn sheet(&self) -> Sheet {
match self {
Prepared::Rhx { css, .. } => css.clone(),
Prepared::Module { name, css, module, .. } => (!css.is_empty()).then(|| module.css()).flatten().map(|text| (format!("{name}@{css}"), Rc::from(text.as_str()))),
}
}
}
enum Body<R: Renderer> {
Rhx {
tree_hash: String,
handlers_hash: String,
state: State,
live: BTreeMap<String, Signal<Value>>,
readers: Vec<Follow>,
folds: Rc<Folds>,
tree: Rc<ComponentTree>,
mounted: Option<Mounted<R>>,
slot: MemberSlot,
css: Sheet,
_listening: Vec<Listening>,
_keys: crate::keys::KeysHeld,
},
Module {
hash: String,
css: String,
uses: Vec<String>,
module: Rc<dyn Module<R>>,
mounted: Option<Box<dyn ModuleInstance>>,
observing: Option<crate::tree::Unlisten>,
},
}
struct Inst<R: Renderer> {
name: String,
version: String,
pinned: bool,
element: R::Node,
props: Map<String, Value>,
member: Member,
body: Body<R>,
failed: bool,
}
impl<R: Renderer> Inst<R> {
fn hashes(&self) -> (String, String) {
match &self.body {
Body::Rhx { tree_hash, handlers_hash, .. } => (tree_hash.clone(), handlers_hash.clone()),
Body::Module { hash, css, .. } => (hash.clone(), css.clone()),
}
}
fn prepared(&self) -> Prepared<R> {
match &self.body {
Body::Rhx { tree_hash, handlers_hash, folds, tree, slot, css, .. } => Prepared::Rhx {
version: self.version.clone(),
tree: tree.clone(),
folds: folds.clone(),
tree_hash: tree_hash.clone(),
handlers_hash: handlers_hash.clone(),
slot: slot.clone(),
css: css.clone(),
},
Body::Module { hash, css, uses, module, .. } => {
Prepared::Module { version: self.version.clone(), name: self.name.clone(), hash: hash.clone(), css: css.clone(), uses: uses.clone(), module: module.clone() }
}
}
}
fn state(&self) -> Option<Map<String, Value>> {
match &self.body {
Body::Rhx { state, .. } => Some(state.snapshot()),
Body::Module { .. } => None,
}
}
fn teardown(mut self) {
match &mut self.body {
Body::Rhx { mounted, readers, .. } => {
if let Some(m) = mounted.take() {
m.unmount();
}
drop(std::mem::take(readers));
}
Body::Module { mounted, observing, .. } => {
if let Some(off) = observing.take() {
off();
}
if let Some(m) = mounted.take() {
m.destroy();
}
}
}
self.member.leave();
}
}
struct Section<R: Renderer> {
sid: u64,
owner: Option<MountId>,
layout: String,
slot: String,
div: R::Node,
props: Map<String, Value>,
instance: Option<MountId>,
waiting: Option<(String, String, bool)>,
bound: Option<Binding>,
inline: bool,
queued: bool,
}
type Binding = (String, Option<String>);
type Provided<R> = (Rc<dyn Module<R>>, ComponentEntry);
struct St<R: Renderer> {
version: String,
manifest: Manifest,
files: Files,
modules: BTreeMap<(String, String), Provided<R>>,
needs: Vec<(String, String)>,
instances: BTreeMap<MountId, Inst<R>>,
next: u64,
assignments: Vec<Assignment>,
sections: Vec<Section<R>>,
console: Vec<String>,
warned: std::collections::BTreeSet<(String, String)>,
}
pub struct App<R: Renderer, W: Wire, C: Clock> {
rt: Runtime,
renderer: R,
wire: W,
cache: Rc<LiveCache<W, C>>,
bus: Bus,
st: RefCell<St<R>>,
navigate: RefCell<Option<Rc<dyn Fn(&str)>>>,
on_need: RefCell<Option<Rc<dyn Fn()>>>,
attaching: RefCell<Vec<String>>,
trees: RefCell<BTreeMap<String, Rc<ComponentTree>>>,
read_trees: RefCell<BTreeMap<String, Rc<ComponentTree>>>,
sheets: RefCell<BTreeMap<String, usize>>,
keys_off: RefCell<Option<crate::tree::Unlisten>>,
calls: RefCell<BTreeMap<MountId, Vec<CallId>>>,
turns: turns::Turns<R::Node>,
me: Weak<Self>,
}
impl<R: Renderer, W: Wire, C: Clock> Drop for App<R, W, C> {
fn drop(&mut self) {
if let Some(off) = self.keys_off.borrow_mut().take() {
off();
}
}
}
struct Kids<R: Renderer, W: Wire, C: Clock>(Weak<App<R, W, C>>, Option<String>, String);
impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> Children<R> for Kids<R, W, C> {
fn mount_component(&self, at: &R::Node, name: &str, props: Map<String, Value>) {
let Some(app) = self.0.upgrade() else { return };
let version = app.st.borrow().version.clone();
let pin = self.1.clone();
if pin.as_deref().is_none_or(|v| v == version) {
match app.instantiate(at, name, &version, pin.is_some(), props.clone()) {
Ok(_) => return,
Err(SwapError::Missing(..)) => {}
Err(e) => return app.say(&format!("{name} ({version}): {e}")),
}
}
let sid = app.next_id().0;
let s = Section { sid, owner: None, layout: self.2.clone(), slot: name.into(), div: at.clone(), props, instance: None, waiting: None, bound: Some((name.to_string(), pin)), inline: true, queued: false };
app.st.borrow_mut().sections.push(s);
app.fill(sid);
app.told_needs();
}
fn mount_slot(&self, at: &R::Node, layout: &str, slot: &str, props: Map<String, Value>) {
if let Some(app) = self.0.upgrade() {
let sid = app.next_id().0;
let s = Section { sid, owner: None, layout: layout.into(), slot: slot.into(), div: at.clone(), props, instance: None, waiting: None, bound: None, inline: false, queued: false };
app.st.borrow_mut().sections.push(s);
app.fill_soon(sid);
}
}
fn unmount(&self, at: &R::Node) {
if let Some(app) = self.0.upgrade() {
app.unmount_at(at);
}
}
fn binds(&self, name: &str) -> bool {
let Some(app) = self.0.upgrade() else { return false };
let st = app.st.borrow();
if let Some(v) = self.1.as_deref().filter(|v| *v != st.version) {
if st.modules.contains_key(&(v.to_string(), name.to_string())) {
return true;
}
if st.files.version(v, name).is_some() {
return false;
}
}
st.manifest.components.get(name).is_some_and(|e| !e.is_rhx())
}
fn mount_bound(&self, at: &R::Node, layout: &str, name: &str, props: Map<String, Value>) {
if let Some(app) = self.0.upgrade() {
let sid = app.next_id().0;
let bound = Some((name.to_string(), self.1.clone()));
let s = Section { sid, owner: None, layout: layout.into(), slot: name.into(), div: at.clone(), props, instance: None, waiting: None, bound, inline: false, queued: false };
app.st.borrow_mut().sections.push(s);
app.fill_soon(sid);
app.told_needs();
}
}
}
struct AppHost<R: Renderer, W: Wire, C: Clock>(Weak<App<R, W, C>>, MemberSlot);
impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> Host for AppHost<R, W, C> {
fn call(&self, method: &str, params: Value) {
if let Some(app) = self.0.upgrade() {
app.wire.open(method, params, Box::new(|_| {}));
}
}
fn call_then(&self, method: &str, params: Value, fold: &str) {
let Some(app) = self.0.upgrade() else { return };
let Some(id) = self.1.borrow().as_ref().map(|(_, id)| *id) else { return };
let (me, fold, m, p) = (self.0.clone(), fold.to_string(), method.to_string(), params.clone());
let open: Rc<std::cell::Cell<Option<CallId>>> = Rc::new(std::cell::Cell::new(None));
let ended = Rc::new(std::cell::Cell::new(false));
let (o, e) = (open.clone(), ended.clone());
let call = app.wire.open(
method,
params,
answer_sink(move |answer| {
e.set(true);
let Some(app) = me.upgrade() else { return };
if let Some(call) = o.get() {
app.forget_call(id, call);
}
app.bus.defer(move || {
if let Some(app) = me.upgrade() {
app.answered(id, &fold, &m, &p, answer);
}
});
}),
);
if !ended.get() {
open.set(Some(call));
app.calls.borrow_mut().entry(id).or_default().push(call);
}
}
fn navigate(&self, route: &str) {
let f = self.0.upgrade().and_then(|app| app.navigate.borrow().clone());
if let Some(f) = f {
f(route);
}
}
fn emit(&self, topic: &str, data: Value) -> Result<(), String> {
let member = self.1.borrow().as_ref().map(|(m, _)| m.clone());
member.ok_or("not mounted")?.emit(topic, data).map_err(|r| r.to_string())
}
fn last(&self, topic: &str) -> Value {
let member = self.1.borrow().as_ref().map(|(m, _)| m.clone());
member.and_then(|m| m.last(topic)).unwrap_or(Value::Null)
}
fn slots_set(&self, layout: &str, slot: &str, component: &str, version: Option<&str>) -> Result<(), String> {
let member = self.1.borrow().as_ref().map(|(m, _)| m.clone());
member.ok_or("not mounted")?.slots_set(layout, slot, component, version, Box::new(|_| {})).map(|_| ()).map_err(|r| r.to_string())
}
}
impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> BusHost for App<R, W, C> {
fn open(&self, method: &str, params: Value, sink: Sink) -> CallId {
self.wire.open(method, params, sink)
}
fn close(&self, call: CallId) {
self.wire.close(call)
}
fn live(&self, spec: &LiveSpec) -> Reader {
self.cache.acquire(spec)
}
fn follow(&self, spec: ModuleSpec) -> ModuleLive {
self.cache.follow_module(spec)
}
fn navigate(&self, route: &str) {
let f = self.navigate.borrow().clone();
if let Some(f) = f {
f(route);
}
}
fn live_version(&self) -> String {
self.version()
}
fn bound(&self, layout: &str, slot: &str) -> Option<String> {
let st = self.st.borrow();
st.sections.iter().filter(|s| s.layout == layout && s.slot == slot).find_map(|s| s.bound.as_ref()).map(|(c, _)| c.clone())
}
}
impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> App<R, W, C> {
pub fn new(rt: &Runtime, renderer: R, wire: W, clock: C) -> Rc<Self> {
let cache = LiveCache::new(rt, wire.clone(), clock);
let bus = Bus::new(rt);
let app = Rc::new_cyclic(|me| Self {
rt: rt.clone(),
renderer,
wire,
cache,
bus: bus.clone(),
st: RefCell::new(St {
version: String::new(),
manifest: Manifest::default(),
files: Files::default(),
modules: BTreeMap::new(),
needs: Vec::new(),
instances: BTreeMap::new(),
next: 0,
assignments: Vec::new(),
sections: Vec::new(),
console: Vec::new(),
warned: Default::default(),
}),
navigate: RefCell::new(None),
on_need: RefCell::new(None),
attaching: RefCell::new(Vec::new()),
trees: RefCell::new(BTreeMap::new()),
read_trees: RefCell::new(BTreeMap::new()),
sheets: RefCell::new(BTreeMap::new()),
keys_off: RefCell::new(None),
calls: RefCell::new(BTreeMap::new()),
turns: turns::Turns::default(),
me: me.clone(),
});
let host: Weak<dyn BusHost> = Rc::downgrade(&app) as Weak<dyn BusHost>;
bus.set_host(host);
let me = Rc::downgrade(&app);
let off = app.renderer.listen_keys(Rc::new(move |p: &crate::keys::Press| me.upgrade().is_some_and(|app| app.press(p))));
*app.keys_off.borrow_mut() = Some(off);
let me = Rc::downgrade(&app);
bus.keys().on_change(Rc::new(move || {
if let Some(app) = me.upgrade() {
app.overlay_follows();
}
}));
app
}
pub fn press(&self, p: &crate::keys::Press) -> bool {
let keys = self.bus.keys().clone();
let heard = keys.press(p);
if let crate::keys::Heard::Overlay(open) = heard {
self.renderer.keys_overlay(open.then(|| keys.groups()).as_ref());
}
heard.taken()
}
fn overlay_follows(&self) {
let keys = self.bus.keys();
if !keys.overlay() {
return;
}
if keys.is_empty() {
keys.close_overlay();
self.renderer.keys_overlay(None);
} else {
self.renderer.keys_overlay(Some(&keys.groups()));
}
}
pub fn bus(&self) -> Bus {
self.bus.clone()
}
pub fn provide_module(&self, version: &str, name: &str, entry: ComponentEntry, module: Rc<dyn Module<R>>) {
let waiting: Vec<u64> = {
let mut st = self.st.borrow_mut();
st.modules.insert((version.into(), name.into()), (module, entry));
st.needs.retain(|(v, n)| !(v == version && n == name));
st.sections.iter().filter(|s| s.waiting.as_ref().is_some_and(|(v, n, _)| v == version && n == name)).map(|s| s.sid).collect()
};
for sid in waiting {
self.fill(sid);
}
}
pub fn cache(&self) -> &Rc<LiveCache<W, C>> {
&self.cache
}
pub fn set_navigate(&self, f: Rc<dyn Fn(&str)>) {
*self.navigate.borrow_mut() = Some(f);
}
pub fn set_on_need(&self, f: Rc<dyn Fn()>) {
*self.on_need.borrow_mut() = Some(f);
}
pub fn load(&self, version: &str, manifest: Manifest) {
let mut st = self.st.borrow_mut();
st.version = version.into();
st.manifest = manifest;
}
pub fn version(&self) -> String {
self.st.borrow().version.clone()
}
pub fn manifest(&self) -> Manifest {
self.st.borrow().manifest.clone()
}
pub fn provide(&self, files: &Files) {
let waiting: Vec<u64> = {
let mut st = self.st.borrow_mut();
st.files.extend(files);
let have = st.files.clone();
st.needs.retain(|(v, n)| have.version(v, n).is_none());
st.sections.iter().filter(|s| s.waiting.as_ref().is_some_and(|(v, n, _)| have.version(v, n).is_some())).map(|s| s.sid).collect()
};
for sid in waiting {
self.fill(sid);
}
}
pub fn needs(&self) -> Vec<(String, String)> {
self.st.borrow().needs.clone()
}
fn say(&self, line: &str) {
#[cfg(feature = "dom")]
web_sys::console::warn_1(&line.into());
self.st.borrow_mut().console.push(line.to_string());
}
fn prepare(&self, version: &str, name: &str) -> Result<Prepared<R>, SwapError> {
let need = |st: &mut St<R>| {
let need = (version.to_string(), name.to_string());
if !st.needs.contains(&need) {
st.needs.push(need);
}
Err(SwapError::Missing(version.into(), name.into()))
};
let (files, entry) = {
let mut st = self.st.borrow_mut();
let entry = (version == st.version).then(|| st.manifest.components.get(name).cloned());
if let Some(None) = entry {
return Err(SwapError::Unknown(name.into()));
}
let entry = entry.flatten();
let module = st.modules.get(&(version.to_string(), name.to_string())).cloned();
match (&entry, module) {
(Some(e), Some((module, got))) if !e.is_rhx() => {
if got.module != e.module {
return Err(SwapError::Failed { component: name.into(), message: "its module is not the one the manifest names (their hashes differ)".into() });
}
return Ok(Prepared::Module { version: version.into(), name: name.into(), hash: e.module.clone(), css: e.css.clone(), uses: e.uses.clone(), module });
}
(Some(e), None) if !e.is_rhx() => return need(&mut st),
(None, Some((module, got))) if st.files.version(version, name).is_none() => {
return Ok(Prepared::Module { version: version.into(), name: name.into(), hash: got.module.clone(), css: got.css.clone(), uses: got.uses.clone(), module });
}
_ => {}
}
match st.files.version(version, name) {
Some((t, h)) => ((t.to_string(), h.to_string(), st.files.sheet(version, name)), entry),
None => return need(&mut st),
}
};
let failed = |message: String| SwapError::Failed { component: name.into(), message };
let (tree_hash, handlers_hash) = (sha256_hex(&files.0), sha256_hex(&files.1));
if let Some(e) = &entry {
if e.tree != tree_hash || e.handlers != handlers_hash {
return Err(failed("its files are not the ones the manifest names (their hashes differ)".into()));
}
}
let tree = self.parsed(&files.0).map_err(failed)?;
let slot: MemberSlot = Rc::new(RefCell::new(None));
let host: Rc<dyn Host> = Rc::new(AppHost(self.me.clone(), slot.clone()));
let folds = Folds::compile(&files.1, &tree.uses, host).map_err(|e| failed(e.to_string()))?;
crate::marks::mark(&format!("handlers-compiled:{name}"));
if tree.css.is_some() && files.2.is_none() {
self.say(&format!("{name} ({version}): its tree names a sheet, and none was fetched — drawn without it"));
}
let css = files.2.filter(|_| tree.css.is_some()).map(|text| (format!("{name}@{}", sha256_hex(&text)), text));
Ok(Prepared::Rhx { version: version.into(), tree, folds: Rc::new(folds), tree_hash, handlers_hash, slot, css })
}
fn attach(&self, id: MountId, element: &R::Node, p: Prepared<R>, props: Map<String, Value>, state: Option<Map<String, Value>>, pinned: bool) -> Result<(), SwapError> {
let name = match &p {
Prepared::Module { name, .. } => name.clone(),
Prepared::Rhx { tree, .. } => tree.name.clone(),
};
self.attaching.borrow_mut().push(name);
let r = self.attach_now(id, element, p, props, state, pinned);
self.attaching.borrow_mut().pop();
r
}
fn attach_now(&self, id: MountId, element: &R::Node, p: Prepared<R>, props: Map<String, Value>, state: Option<Map<String, Value>>, pinned: bool) -> Result<(), SwapError> {
let sheet = p.sheet();
self.sheet_up(&sheet);
if let Prepared::Rhx { tree, .. } = &p {
if let Some(mark) = &tree.css {
self.renderer.set_attr(element, "data-css", mark);
}
}
let r = self.draw(id, element, p, props, state, pinned);
if r.is_err() {
self.sheet_down(&sheet);
}
r
}
fn sheet_up(&self, sheet: &Sheet) {
let Some((key, text)) = sheet else { return };
let first = {
let mut sheets = self.sheets.borrow_mut();
let n = sheets.entry(key.clone()).or_insert(0);
*n += 1;
*n == 1
};
if first {
self.renderer.sheet(key, text, true);
}
}
fn sheet_down(&self, sheet: &Sheet) {
let Some((href, _)) = sheet else { return };
let last = {
let mut sheets = self.sheets.borrow_mut();
match sheets.get_mut(href) {
Some(n) if *n > 1 => {
*n -= 1;
false
}
Some(_) => {
sheets.remove(href);
true
}
None => false,
}
};
if last {
self.renderer.sheet(href, "", false);
}
}
pub fn sheets(&self) -> BTreeMap<String, usize> {
self.sheets.borrow().clone()
}
fn draw(&self, id: MountId, element: &R::Node, p: Prepared<R>, mut props: Map<String, Value>, state: Option<Map<String, Value>>, pinned: bool) -> Result<(), SwapError> {
let (version, tree, folds, tree_hash, handlers_hash, slot, css) = match p {
Prepared::Module { version, name, hash, css, uses, module } => {
let member = self.bus.join(&name, &uses);
let mounted = module.mount(element, &props, member.clone()).map_err(|message| {
member.leave();
SwapError::Failed { component: name.clone(), message }
})?;
let me = self.me.clone();
let observing = self.renderer.observe(
element,
Rc::new(move |targets: Vec<R::Node>| {
if let Some(app) = me.upgrade() {
app.observed(id, &targets);
}
}),
);
let body = Body::Module { hash, css, uses, module, mounted: Some(mounted), observing: Some(observing) };
let inst = Inst { name, version, pinned, element: element.clone(), props, member, body, failed: false };
self.st.borrow_mut().instances.insert(id, inst);
self.walk(id);
return Ok(());
}
Prepared::Rhx { version, tree, folds, tree_hash, handlers_hash, slot, css } => (version, tree, folds, tree_hash, handlers_hash, slot, css),
};
for name in &tree.props {
props.entry(name.clone()).or_insert(Value::Null);
}
let state = State::new(&self.rt, state.as_ref().unwrap_or(&tree.state));
let mut readers = Vec::new();
let mut live = BTreeMap::new();
for (name, d) in &tree.live {
for rule in d.on.values() {
rule.parse::<crate::live::FoldRule>().map_err(|message| SwapError::Failed { component: tree.name.clone(), message })?;
}
let query = LiveQuery {
snapshot: d.snapshot.clone(),
changes: d.changes.clone(),
key: d.key.clone(),
on: d.on.iter().map(|(a, b)| (a.clone(), b.clone())).collect(),
debounce_ms: d.debounce_ms,
};
let (pp, cp, pr, st, when) = (d.params.clone(), d.changes_params.clone(), props.clone(), state.clone(), d.when.clone());
let r = self.cache.follow_held(query, move || {
crate::tree::eval_when(when.as_ref(), &pr, &st).then(|| (crate::tree::eval_params(&pp, &pr, &st), crate::tree::eval_params(&cp, &pr, &st)))
});
live.insert(name.clone(), r.signal());
readers.push(r);
}
let me = self.me.clone();
let on_event: Rc<dyn Fn(&str, Value)> = Rc::new(move |handler: &str, ev: Value| {
if let Some(app) = me.upgrade() {
if let Err(e) = app.dispatch(id, handler, ev) {
app.say(&e.to_string());
}
}
});
let member = self.bus.join(&tree.name, &tree.uses);
*slot.borrow_mut() = Some((member.clone(), id));
let keys = member.keys(
tree.keys
.iter()
.map(|d| {
let (me, to) = (self.me.clone(), d.to.clone());
let run: crate::keys::KeyRun = Rc::new(move |ev: Value| {
if let Some(app) = me.upgrade() {
if let Err(e) = app.dispatch(id, &to, ev) {
app.say(&e.to_string());
}
}
});
(d.clone(), run)
})
.collect(),
);
let scope = Scope { props: props.clone(), state: state.clone(), live: live.clone(), on_event };
let kids: Rc<dyn Children<R>> = Rc::new(Kids(self.me.clone(), pinned.then(|| version.clone()), tree.name.clone()));
let mounted = crate::tree::mount(&self.rt, &self.renderer, &tree, scope, element, kids).map_err(|e| {
member.leave();
SwapError::Failed { component: tree.name.clone(), message: e.to_string() }
})?;
for (d, r) in tree.live.values().zip(&readers) {
let Some(at) = r.answered_at().filter(|_| r.live().status == crate::live::Status::Live && !r.live().rows.is_empty()) else { continue };
crate::marks::once_at("first-answer", at);
crate::marks::once("first-row");
crate::marks::once_at(&format!("answered:{}", d.snapshot), at);
crate::marks::once(&format!("drawn:{}", d.snapshot));
}
let listening = tree
.bus
.iter()
.map(|(topic, fold)| {
let (me, fold, topic2) = (self.me.clone(), fold.clone(), topic.clone());
member.on(topic, move |data: &Value| {
if let Some(app) = me.upgrade() {
app.dispatch_bus(id, &fold, &topic2, data);
}
})
})
.collect();
let inst = Inst {
name: tree.name.clone(),
version,
pinned,
element: element.clone(),
props,
member,
body: Body::Rhx { tree_hash, handlers_hash, state, live, readers, folds, tree, mounted: Some(mounted), slot, css, _listening: listening, _keys: keys },
failed: false,
};
self.st.borrow_mut().instances.insert(id, inst);
Ok(())
}
fn next_id(&self) -> MountId {
let mut st = self.st.borrow_mut();
st.next += 1;
MountId(st.next)
}
fn instantiate(&self, element: &R::Node, name: &str, version: &str, pinned: bool, props: Map<String, Value>) -> Result<MountId, SwapError> {
let p = match self.prepare(version, name) {
Ok(p) => p,
Err(e) => {
if !matches!(e, SwapError::Missing(..)) {
self.renderer.set_attr(element, "data-failed", version);
}
return Err(e);
}
};
let id = self.next_id();
self.attach(id, element, p, props, None, pinned).inspect_err(|_| self.renderer.set_attr(element, "data-failed", version))?;
Ok(id)
}
pub fn mount(&self, parent: &R::Node, name: &str, props: Map<String, Value>) -> Result<MountId, SwapError> {
let el = self.renderer.create_element(name);
let version = self.version();
let r = self.instantiate(&el, name, &version, false, props);
self.renderer.insert(parent, &el, None);
r.inspect_err(|e| self.say(&format!("{name} ({version}): {e}")))
}
pub fn unmount(&self, id: MountId) {
let calls = self.calls.borrow_mut().remove(&id).unwrap_or_default();
for call in calls {
self.wire.close(call);
}
let inst = self.st.borrow_mut().instances.remove(&id);
if let Some(inst) = inst {
self.drop_sections_of(id);
let sheet = inst.prepared().sheet();
inst.teardown();
self.sheet_down(&sheet);
}
}
pub fn update(&self, id: MountId, props: Map<String, Value>) -> Result<(), SwapError> {
let module = {
let mut st = self.st.borrow_mut();
let Some(inst) = st.instances.get_mut(&id) else { return Err(SwapError::Unknown(format!("instance {}", id.0))) };
inst.props = props.clone();
match &mut inst.body {
Body::Module { mounted, .. } => Some(mounted.take()),
Body::Rhx { .. } => None,
}
};
match module {
Some(mounted) => {
let mut mounted = mounted;
if let Some(m) = mounted.as_mut() {
m.update(&props);
}
if let Some(Inst { body: Body::Module { mounted: slot, .. }, .. }) = self.st.borrow_mut().instances.get_mut(&id) {
*slot = mounted;
}
self.walk(id);
Ok(())
}
None => {
let inst = self.st.borrow_mut().instances.remove(&id).expect("an instance");
let (p, element, pinned) = (inst.prepared(), inst.element.clone(), inst.pinned);
let held = p.sheet();
inst.teardown();
let r = self.attach(id, &element, p, props, None, pinned);
self.sheet_down(&held);
r
}
}
}
fn unmount_at(&self, at: &R::Node) {
let ids: Vec<MountId> = self.st.borrow().instances.iter().filter(|(_, i)| &i.element == at).map(|(id, _)| *id).collect();
for id in ids {
self.unmount(id);
}
let gone: Vec<Option<MountId>> = {
let mut st = self.st.borrow_mut();
let (out, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut st.sections).into_iter().partition(|s| &s.div == at);
st.sections = keep;
out.into_iter().map(|s| s.instance).collect()
};
for id in gone.into_iter().flatten() {
self.unmount(id);
}
}
pub fn dispatch(&self, id: MountId, handler: &str, event: Value) -> Result<(), FoldError> {
let _hold = self.bus.hold();
let (folds, state, props, live) = {
let st = self.st.borrow();
let i = st.instances.get(&id).ok_or_else(|| FoldError::NoHandler(handler.into()))?;
match &i.body {
Body::Rhx { folds, state, live, .. } => (folds.clone(), state.clone(), i.props.clone(), live.clone()),
Body::Module { .. } => return Err(FoldError::NoHandler(handler.into())),
}
};
let rows: Map<String, Value> = live.iter().map(|(k, s)| (k.clone(), s.peek().get("rows").cloned().unwrap_or(Value::Null))).collect();
let next = folds.run(handler, &state.snapshot(), &event, &props, &rows)?;
state.replace(&next);
Ok(())
}
fn forget_call(&self, id: MountId, call: CallId) {
let mut calls = self.calls.borrow_mut();
if let Some(list) = calls.get_mut(&id) {
list.retain(|c| *c != call);
if list.is_empty() {
calls.remove(&id);
}
}
}
pub fn calls_of(&self, id: MountId) -> usize {
self.calls.borrow().get(&id).map_or(0, Vec::len)
}
fn answered(&self, id: MountId, fold: &str, method: &str, params: &Value, answer: Answer) {
if !self.st.borrow().instances.contains_key(&id) {
return;
}
let mut ev = answer.to_value();
ev["method"] = Value::String(method.into());
ev["params"] = params.clone();
if let Err(e) = self.dispatch(id, fold, ev) {
self.say(&e.to_string());
}
}
fn dispatch_bus(&self, id: MountId, fold: &str, topic: &str, data: &Value) {
let ev = serde_json::json!({ "bus": { "topic": topic, "data": data } });
if let Err(e) = self.dispatch(id, fold, ev) {
self.say(&e.to_string());
}
}
pub fn swap(&self, version: &str, manifest: Manifest) -> SwapReport {
let old = {
let mut st = self.st.borrow_mut();
let old = std::mem::replace(&mut st.version, version.into());
let before = std::mem::replace(&mut st.manifest, manifest.clone());
let same: Vec<String> = manifest.components.iter().filter(|(n, e)| before.components.get(*n) == Some(*e)).map(|(n, _)| n.clone()).collect();
for name in same {
if st.files.version(version, &name).is_none() {
st.files.share(&old, version, &name);
}
let key = (version.to_string(), name.clone());
if !st.modules.contains_key(&key) {
if let Some(m) = st.modules.get(&(old.clone(), name.clone())).cloned() {
st.modules.insert(key, m);
}
}
}
let St { files, modules, needs, .. } = &mut *st;
needs.retain(|(v, n)| files.version(v, n).is_none() && !modules.contains_key(&(v.clone(), n.clone())));
old
};
let candidates: Vec<(MountId, String, (String, String), bool)> = self
.st
.borrow()
.instances
.iter()
.filter(|(_, i)| !i.pinned)
.map(|(id, i)| (*id, i.name.clone(), i.hashes(), matches!(i.body, Body::Rhx { .. })))
.collect();
let mut report = SwapReport::default();
for (id, name, hashes, was_rhx) in candidates {
if !self.st.borrow().instances.contains_key(&id) {
continue;
}
let Some(entry) = manifest.components.get(&name) else {
self.fail(id, version, &old, &name, "not in the new version".into(), &mut report);
continue;
};
if entry.hashes() == hashes {
continue;
}
let p = match self.prepare(version, &name) {
Ok(p) => p,
Err(e) => {
self.fail(id, version, &old, &name, e.to_string(), &mut report);
continue;
}
};
let r = if was_rhx && matches!(p, Prepared::Rhx { .. }) { self.remount(id, p) } else { self.replace(id, p) };
match r {
Ok(()) => report.remounted.push(id),
Err(e) => self.fail(id, version, &old, &name, e.to_string(), &mut report),
}
}
let refill: Vec<u64> = {
let st = self.st.borrow();
st.sections
.iter()
.filter(|s| s.bound.is_none() && !st.assignments.iter().any(|a| a.layout == s.layout && a.slot == s.slot))
.filter(|s| {
let default = st.manifest.slots.get(&s.layout).and_then(|m| m.get(&s.slot));
let drawn = s.instance.and_then(|id| st.instances.get(&id)).map(|i| &i.name);
default != drawn
})
.map(|s| s.sid)
.collect()
};
for sid in refill {
self.fill(sid);
}
report
}
fn fail(&self, id: MountId, version: &str, old: &str, name: &str, why: String, report: &mut SwapReport) {
let drawn = {
let mut st = self.st.borrow_mut();
st.instances.get_mut(&id).map(|i| {
i.failed = true;
(i.element.clone(), i.version.clone())
})
};
let drawn_version = match drawn {
Some((element, v)) => {
self.renderer.set_attr(&element, "data-failed", version);
v
}
None => old.to_string(),
};
self.say(&format!("{name}: {version} failed to mount ({why}); keeping its last good version {drawn_version}"));
report.failed.push((id, why));
}
fn replace(&self, id: MountId, p: Prepared<R>) -> Result<(), SwapError> {
let inst = self.st.borrow_mut().instances.remove(&id).expect("an instance");
let (again, state, element, props, pinned, was_failed) = (inst.prepared(), inst.state(), inst.element.clone(), inst.props.clone(), inst.pinned, inst.failed);
let held = again.sheet();
self.drop_sections_of(id);
inst.teardown();
let r = self.replace_with(id, &element, p, again, props, state, pinned, was_failed);
self.sheet_down(&held);
r
}
#[allow(clippy::too_many_arguments)]
fn replace_with(&self, id: MountId, element: &R::Node, p: Prepared<R>, again: Prepared<R>, props: Map<String, Value>, state: Option<Map<String, Value>>, pinned: bool, was_failed: bool) -> Result<(), SwapError> {
let element = element.clone();
match self.attach(id, &element, p, props.clone(), None, pinned) {
Ok(()) => {
if was_failed {
self.renderer.set_attr(&element, "data-failed", "");
}
Ok(())
}
Err(e) => {
if let Err(again) = self.attach(id, &element, again, props, state, pinned) {
self.say(&format!("its last good version did not mount again either: {again}"));
}
Err(e)
}
}
}
fn remount(&self, id: MountId, p: Prepared<R>) -> Result<(), SwapError> {
let inst = self.st.borrow_mut().instances.remove(&id).expect("an instance");
let state = match (&inst.body, &p) {
(Body::Rhx { state, .. }, Prepared::Rhx { tree, .. }) => {
let shape: Vec<String> = tree.state.keys().cloned().collect();
(state.shape() == shape).then(|| state.snapshot())
}
_ => None,
};
let (element, props, pinned, was_failed) = (inst.element.clone(), inst.props.clone(), inst.pinned, inst.failed);
let held = inst.prepared().sheet();
self.drop_sections_of(id);
inst.teardown();
let r = self.attach(id, &element, p, props, state, pinned);
self.sheet_down(&held);
if r.is_ok() && was_failed {
self.renderer.set_attr(&element, "data-failed", "");
}
r
}
pub fn set_assignments(&self, assignments: Vec<Assignment>) {
self.warn_bound(&assignments);
let changed: Vec<u64> = {
let mut st = self.st.borrow_mut();
let before = std::mem::replace(&mut st.assignments, assignments);
let find = |list: &[Assignment], l: &str, s: &str| list.iter().find(|a| a.layout == l && a.slot == s).cloned();
st.sections
.iter()
.filter(|s| s.bound.is_none() && find(&before, &s.layout, &s.slot) != find(&st.assignments, &s.layout, &s.slot))
.map(|s| s.sid)
.collect()
};
for sid in changed {
self.fill(sid);
}
}
pub fn slot_changed(&self, change: Assignment) {
self.warn_bound(std::slice::from_ref(&change));
let idx = {
let mut st = self.st.borrow_mut();
st.assignments.retain(|a| !(a.layout == change.layout && a.slot == change.slot));
st.assignments.push(change.clone());
st.sections.iter().filter(|s| s.bound.is_none() && s.layout == change.layout && s.slot == change.slot).map(|s| s.sid).collect::<Vec<_>>()
};
for sid in idx {
self.fill(sid);
}
}
pub fn slot_reset(&self, layout: &str, slot: &str) {
let idx = {
let mut st = self.st.borrow_mut();
st.assignments.retain(|a| !(a.layout == layout && a.slot == slot));
st.sections.iter().filter(|s| s.bound.is_none() && s.layout == layout && s.slot == slot).map(|s| s.sid).collect::<Vec<_>>()
};
for sid in idx {
self.fill(sid);
}
}
fn fill(&self, sid: u64) {
self.with_section(sid, |s| s.queued = false);
let (div, props, old, want, inline) = {
let st = self.st.borrow();
let Some(s) = st.sections.iter().find(|s| s.sid == sid) else { return };
let want = match (&s.bound, st.assignments.iter().find(|a| a.layout == s.layout && a.slot == s.slot)) {
(Some((c, v)), _) => {
let parent = s.owner.and_then(|o| st.instances.get(&o)).filter(|i| i.pinned).map(|i| i.version.clone());
let v = v.clone().or(parent);
Some((c.clone(), v.clone().unwrap_or_else(|| st.version.clone()), v.is_some()))
}
(None, Some(a)) => Some((a.component.clone(), a.version.clone(), true)),
(None, None) => st.manifest.slots.get(&s.layout).and_then(|m| m.get(&s.slot)).map(|c| (c.clone(), st.version.clone(), false)),
};
let old = s.instance.and_then(|id| st.instances.get(&id).map(|inst| (id, inst.element.clone(), inst.version.clone())));
(s.div.clone(), s.props.clone(), old, want, s.inline)
};
let Some((component, version, pinned)) = want else {
if let Some((id, el, _)) = old {
self.unmount(id);
self.renderer.remove(&div, &el);
}
self.with_section(sid, |s| s.instance = None);
return;
};
if let Some(chain) = self.cycle(&div, &component) {
self.with_section(sid, |s| s.waiting = None);
self.say(&format!("cycle: {chain} → {component}; the section is left empty"));
return;
}
let p = match self.prepare(&version, &component) {
Ok(p) => p,
Err(SwapError::Missing(..)) => {
self.with_section(sid, |s| s.waiting = Some((version, component, pinned)));
return;
}
Err(e) => {
self.with_section(sid, |s| s.waiting = None);
if let Some((_, el, _)) = &old {
self.renderer.set_attr(el, "data-failed", &version);
}
self.say(&format!("{component} ({version}): {e}; the section keeps what it shows"));
return;
}
};
if inline {
self.with_section(sid, |s| s.waiting = None);
if old.is_some() {
return;
}
let id = self.next_id();
match self.attach(id, &div, p, props, None, pinned) {
Ok(()) => {
self.with_section(sid, |s| s.instance = Some(id));
}
Err(e) => {
self.renderer.set_attr(&div, "data-failed", &version);
self.say(&format!("{component} ({version}): {e}"));
}
}
return;
}
let el = self.renderer.create_element(&component);
let id = self.next_id();
let drawn_from = p.version().to_string();
match self.attach(id, &el, p, props, None, pinned) {
Ok(()) => {
self.renderer.insert(&div, &el, None);
if let Some((old_id, old_el, _)) = old {
self.unmount(old_id);
self.renderer.remove(&div, &old_el);
}
let slot = self.with_section(sid, |s| {
s.waiting = None;
s.instance = Some(id);
s.slot.clone()
});
if let Some(slot) = slot {
crate::marks::once(&format!("section-mounted:{slot}"));
}
}
Err(e) => {
self.with_section(sid, |s| s.waiting = None);
match old {
Some((old_id, old_el, old_version)) => {
self.renderer.set_attr(&old_el, "data-failed", &drawn_from);
if let Some(i) = self.st.borrow_mut().instances.get_mut(&old_id) {
i.failed = true;
}
self.say(&format!("{component}: {drawn_from} failed to mount ({e}); keeping its last good version {old_version}"));
}
None => {
self.renderer.insert(&div, &el, None);
self.renderer.set_attr(&el, "data-failed", &version);
self.with_section(sid, |s| s.instance = None);
self.say(&format!("{component} ({version}): {e}"));
}
}
}
}
}
fn cycle(&self, div: &R::Node, component: &str) -> Option<String> {
let st = self.st.borrow();
let mut chain: Vec<String> = Vec::new();
let mut at = div.clone();
for _ in 0..st.instances.len() + 1 {
let mut around: Vec<(&MountId, &Inst<R>)> = st.instances.iter().filter(|(_, i)| i.element != at && self.renderer.contains(&i.element, &at)).collect();
if around.is_empty() {
break;
}
around.sort_by_key(|(_, i)| around_count(&self.renderer, &st, &i.element));
for (_, i) in around.iter().rev() {
chain.push(i.name.clone());
}
let outer = *around[0].0;
match st.sections.iter().find(|s| s.instance == Some(outer)) {
Some(s) => at = s.div.clone(),
None => break,
}
}
chain.reverse();
let outer: Vec<String> = self.attaching.borrow().iter().filter(|n| !chain.contains(n)).cloned().collect();
let chain: Vec<String> = outer.into_iter().chain(chain).collect();
chain.iter().any(|n| n == component).then(|| chain.join(" → "))
}
fn warn_bound(&self, assignments: &[Assignment]) {
let lines: Vec<String> = {
let mut st = self.st.borrow_mut();
let mut lines = Vec::new();
for a in assignments {
let Some((c, _)) = st.sections.iter().filter(|s| s.layout == a.layout && s.slot == a.slot).find_map(|s| s.bound.clone()) else { continue };
if st.warned.insert((a.layout.clone(), a.slot.clone())) {
lines.push(format!("{} · {}: assignment {}@{} stored, but the mark binds {c}; it does nothing", a.layout, a.slot, a.component, a.version));
}
}
lines
};
for l in lines {
self.say(&l);
}
}
pub fn walk(&self, id: MountId) {
let (target, layout) = {
let st = self.st.borrow();
match st.instances.get(&id) {
Some(i) if matches!(i.body, Body::Module { .. }) => (i.element.clone(), i.name.clone()),
_ => return,
}
};
crate::marks::mark(&format!("walk:{layout}"));
let gone: Vec<Option<MountId>> = {
let mut st = self.st.borrow_mut();
let (out, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut st.sections).into_iter().partition(|s| {
s.owner == Some(id) && (!self.renderer.contains(&target, &s.div) || {
let (slot, bound, _) = mark_of(&self.renderer, &s.div);
slot != s.slot || bound != s.bound
})
});
st.sections = keep;
out.into_iter().map(|s| s.instance).collect()
};
for i in gone.into_iter().flatten() {
self.unmount(i);
}
let moved: Vec<(MountId, Map<String, Value>)> = {
let mut st = self.st.borrow_mut();
st.sections
.iter_mut()
.filter(|s| s.owner == Some(id))
.filter_map(|s| {
let (_, _, props) = mark_of(&self.renderer, &s.div);
if props == s.props {
return None;
}
s.props = props.clone();
s.instance.map(|i| (i, props))
})
.collect()
};
for (i, props) in moved {
if let Err(e) = self.update(i, props) {
self.say(&format!("{layout}: a section's props: {e}"));
}
}
let fresh: Vec<R::Node> = {
let st = self.st.borrow();
self.renderer
.marks(&target)
.into_iter()
.filter(|m| !st.sections.iter().any(|s| &s.div == m || (s.div != target && self.renderer.contains(&target, &s.div) && self.renderer.contains(&s.div, m))))
.collect()
};
for mark in fresh {
let (slot, bound, props) = mark_of(&self.renderer, &mark);
self.renderer.set_attr(&mark, "data-layout", &layout);
let sid = self.next_id().0;
let s = Section { sid, owner: Some(id), layout: layout.clone(), slot, div: mark, props, instance: None, waiting: None, bound, inline: false, queued: false };
self.st.borrow_mut().sections.push(s);
self.fill_soon(sid);
}
}
pub fn observed(&self, id: MountId, targets: &[R::Node]) {
let inside = {
let st = self.st.borrow();
let filled: Vec<&R::Node> = st.sections.iter().filter(|s| s.owner == Some(id) && s.instance.is_some()).map(|s| &s.div).collect();
targets.iter().all(|t| filled.iter().any(|d| d != &t && self.renderer.contains(d, t)))
};
if !inside {
self.walk(id);
self.told_needs();
}
}
fn told_needs(&self) {
let on_need = self.on_need.borrow().clone();
if let Some(f) = on_need.filter(|_| !self.st.borrow().needs.is_empty()) {
f();
}
}
fn drop_sections_of(&self, id: MountId) {
let gone: Vec<Option<MountId>> = {
let mut st = self.st.borrow_mut();
let (out, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut st.sections).into_iter().partition(|s| s.owner == Some(id));
st.sections = keep;
out.into_iter().map(|s| s.instance).collect()
};
for i in gone.into_iter().flatten() {
self.unmount(i);
}
}
fn with_section<T>(&self, sid: u64, f: impl FnOnce(&mut Section<R>) -> T) -> Option<T> {
self.st.borrow_mut().sections.iter_mut().find(|s| s.sid == sid).map(f)
}
pub fn here(&self, name: &str) -> bool {
let st = self.st.borrow();
match st.manifest.components.get(name) {
None => true,
Some(e) if e.is_rhx() => st.files.version(&st.version, name).is_some(),
Some(_) => st.modules.contains_key(&(st.version.clone(), name.to_string())),
}
}
pub fn ensure(&self, name: &str) -> bool {
let here = self.here(name);
let mut st = self.st.borrow_mut();
let need = (st.version.clone(), name.to_string());
if !here && !st.needs.contains(&need) {
st.needs.push(need);
}
here
}
pub fn section(&self, layout: &str, slot: &str) -> Option<MountId> {
self.st.borrow().sections.iter().find(|s| s.layout == layout && s.slot == slot).and_then(|s| s.instance)
}
pub fn sections(&self) -> Vec<(String, String)> {
self.st.borrow().sections.iter().map(|s| (s.layout.clone(), s.slot.clone())).collect()
}
pub fn menu(&self, layout: &str, slot: &str, versions: &[(String, Option<ComponentEntry>)]) -> Menu {
let st = self.st.borrow();
let drawn = st.sections.iter().find(|s| s.layout == layout && s.slot == slot).and_then(|s| s.instance).and_then(|id| st.instances.get(&id));
let component = drawn
.map(|i| i.name.clone())
.or_else(|| st.manifest.slots.get(layout).and_then(|m| m.get(slot)).cloned())
.unwrap_or_default();
let live = st.manifest.components.get(&component).map(ComponentEntry::hashes);
let versions = versions
.iter()
.filter(|(v, _)| *v != st.version)
.filter_map(|(v, e)| {
let e = e.as_ref()?;
(Some(e.hashes()) != live).then(|| v.clone())
})
.collect();
Menu { component, components: st.manifest.components.keys().cloned().collect(), versions }
}
pub fn instances(&self) -> Vec<(MountId, String)> {
self.st.borrow().instances.iter().map(|(id, i)| (*id, i.name.clone())).collect()
}
pub fn element_of(&self, id: MountId) -> R::Node {
self.st.borrow().instances[&id].element.clone()
}
pub fn props_of(&self, id: MountId) -> Map<String, Value> {
self.st.borrow().instances[&id].props.clone()
}
pub fn state_of(&self, id: MountId) -> Map<String, Value> {
self.st.borrow().instances[&id].state().unwrap_or_default()
}
pub fn drawn_from(&self, id: MountId) -> (String, String, String) {
let st = self.st.borrow();
let i = &st.instances[&id];
let (a, b) = i.hashes();
(i.version.clone(), a, b)
}
pub fn name_of(&self, id: MountId) -> Option<String> {
self.st.borrow().instances.get(&id).map(|i| i.name.clone())
}
pub fn console(&self) -> Vec<String> {
self.st.borrow().console.clone()
}
}
fn around_count<R: Renderer>(r: &R, st: &St<R>, e: &R::Node) -> usize {
st.instances.values().filter(|i| r.contains(&i.element, e)).count()
}
pub const MARK_NAMES: [&str; 8] = ["slot", "component", "version", "layout", "failed", "css", "refused", "plexus-held"];
fn mark_of<R: Renderer>(r: &R, mark: &R::Node) -> (String, Option<Binding>, Map<String, Value>) {
let mut slot = String::new();
let (mut component, mut version) = (None, None);
let mut props = Map::new();
for (k, v) in r.attrs(mark) {
match k.as_str() {
"data-slot" => slot = v,
"data-component" => component = Some(v),
"data-version" => version = Some(v),
"data-layout" => {}
_ => {
if let Some(name) = k.strip_prefix("data-").filter(|n| !MARK_NAMES.contains(n)) {
props.insert(name.to_string(), Value::String(v));
}
}
}
}
let bound = match component.filter(|c| !c.is_empty()) {
Some(c) => Some((c, version.filter(|v| !v.is_empty()))),
None => {
if let Some(v) = version {
props.insert("version".into(), Value::String(v));
}
None
}
};
(slot, bound, props)
}
#[cfg(test)]
mod tests;