1use crate::signals::{BindingId, Runtime, Signal};
25use serde_json::{Map, Value};
26use std::cell::RefCell;
27use std::collections::BTreeMap;
28use std::rc::Rc;
29
30pub mod expr;
31use expr::Expr;
32
33pub mod recording;
34pub use recording::{Call, Recording};
35
36#[cfg(feature = "dom")]
37pub mod dom;
38
39#[derive(Debug, Clone, PartialEq)]
42pub enum Attr {
43 Lit(String),
44 Expr(String),
45}
46
47#[derive(Debug, Clone, PartialEq)]
49pub enum Node {
50 El { el: String, attrs: BTreeMap<String, Attr>, on: BTreeMap<String, String>, children: Vec<Node> },
51 Text(Attr),
52 If { cond: String, then: Vec<Node>, otherwise: Vec<Node> },
53 Each { expr: String, as_: String, key: String, body: Vec<Node> },
54 Component { name: String, props: BTreeMap<String, Attr> },
55 Slot { name: String, props: BTreeMap<String, Attr> },
56 Html(String),
59}
60
61#[derive(Debug, Clone, PartialEq)]
65pub struct LiveDecl {
66 pub snapshot: String,
67 pub params: BTreeMap<String, Value>,
68 pub changes: Option<String>,
70 pub changes_params: BTreeMap<String, Value>,
71 pub key: String,
72 pub on: BTreeMap<String, String>,
73 pub debounce_ms: Option<u64>,
75 pub when: Option<Value>,
78}
79
80#[derive(Debug, Clone, PartialEq)]
82pub struct ComponentTree {
83 pub name: String,
84 pub abi: String,
85 pub props: Vec<String>,
86 pub state: Map<String, Value>,
88 pub live: BTreeMap<String, LiveDecl>,
89 pub uses: Vec<String>,
90 pub bus: BTreeMap<String, String>,
93 pub handlers: String,
95 pub tree: Vec<Node>,
96 pub css: Option<String>,
99 pub keys: Vec<crate::keys::KeyDecl>,
102}
103
104#[derive(Debug, Clone, PartialEq)]
106pub enum TreeError {
107 Malformed(String),
109 Expr { expr: String, message: String },
111}
112
113impl std::fmt::Display for TreeError {
114 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115 match self {
116 TreeError::Malformed(m) => write!(f, "a malformed tree: {m}"),
117 TreeError::Expr { expr, message } => write!(f, "the expression `{expr}`: {message}"),
118 }
119 }
120}
121
122fn bad(at: &str, what: &str) -> TreeError {
123 TreeError::Malformed(format!("{at}: {what}"))
124}
125
126fn attr(v: &Value, at: &str) -> Result<Attr, TreeError> {
127 match v {
128 Value::String(s) => Ok(Attr::Lit(s.clone())),
129 Value::Object(o) => match o.get("expr") {
130 Some(Value::String(e)) if o.len() == 1 => Ok(Attr::Expr(e.clone())),
131 _ => Err(bad(at, "a value is a string or { \"expr\": … }")),
132 },
133 Value::Number(_) | Value::Bool(_) => Ok(Attr::Lit(v.to_string())),
134 _ => Err(bad(at, "a value is a string or { \"expr\": … }")),
135 }
136}
137
138fn expr_of(v: Option<&Value>, at: &str) -> Result<String, TreeError> {
139 match v {
140 Some(Value::String(s)) => Ok(s.clone()),
141 Some(Value::Object(o)) => match o.get("expr") {
142 Some(Value::String(e)) => Ok(e.clone()),
143 _ => Err(bad(at, "an { \"expr\": … }")),
144 },
145 _ => Err(bad(at, "an { \"expr\": … }")),
146 }
147}
148
149fn attrs(v: Option<&Value>, at: &str) -> Result<BTreeMap<String, Attr>, TreeError> {
150 match v {
151 None => Ok(BTreeMap::new()),
152 Some(Value::Object(o)) => o.iter().map(|(k, v)| Ok((k.clone(), attr(v, &format!("{at}.{k}"))?))).collect(),
153 Some(_) => Err(bad(at, "a map")),
154 }
155}
156
157fn strings(v: Option<&Value>, at: &str) -> Result<BTreeMap<String, String>, TreeError> {
158 match v {
159 None => Ok(BTreeMap::new()),
160 Some(Value::Object(o)) => o
161 .iter()
162 .map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())).ok_or_else(|| bad(&format!("{at}.{k}"), "a string")))
163 .collect(),
164 Some(_) => Err(bad(at, "a map of strings")),
165 }
166}
167
168fn nodes(v: Option<&Value>, at: &str) -> Result<Vec<Node>, TreeError> {
169 match v {
170 None => Ok(Vec::new()),
171 Some(Value::Array(a)) => a.iter().enumerate().map(|(i, n)| node(n, &format!("{at}[{i}]"))).collect(),
172 Some(_) => Err(bad(at, "a list of nodes")),
173 }
174}
175
176fn node(v: &Value, at: &str) -> Result<Node, TreeError> {
177 let o = v.as_object().ok_or_else(|| bad(at, "a node is a map"))?;
178 if let Some(el) = o.get("el") {
179 let el = el.as_str().ok_or_else(|| bad(at, "el is a tag"))?;
180 return Ok(Node::El {
181 el: el.to_string(),
182 attrs: attrs(o.get("attrs"), &format!("{at}.attrs"))?,
183 on: strings(o.get("on"), &format!("{at}.on"))?,
184 children: nodes(o.get("children"), &format!("{at}.children"))?,
185 });
186 }
187 if let Some(t) = o.get("text") {
188 return Ok(Node::Text(attr(t, &format!("{at}.text"))?));
189 }
190 if o.contains_key("if") {
191 return Ok(Node::If {
192 cond: expr_of(o.get("if"), &format!("{at}.if"))?,
193 then: nodes(o.get("then"), &format!("{at}.then"))?,
194 otherwise: nodes(o.get("else"), &format!("{at}.else"))?,
195 });
196 }
197 if let Some(each) = o.get("each") {
198 let e = each.as_object().ok_or_else(|| bad(at, "each is a map"))?;
199 let s = |k: &str| e.get(k).and_then(Value::as_str).map(str::to_string).ok_or_else(|| bad(&format!("{at}.each"), &format!("each has a {k}")));
200 return Ok(Node::Each { expr: s("expr")?, as_: s("as")?, key: s("key")?, body: nodes(o.get("body"), &format!("{at}.body"))? });
201 }
202 if let Some(c) = o.get("component") {
203 let name = c.as_str().ok_or_else(|| bad(at, "component is a name"))?;
204 return Ok(Node::Component { name: name.to_string(), props: attrs(o.get("props"), &format!("{at}.props"))? });
205 }
206 if o.contains_key("html") {
207 return Ok(Node::Html(expr_of(o.get("html"), &format!("{at}.html"))?));
208 }
209 if let Some(sl) = o.get("slot") {
210 let name = sl.as_str().ok_or_else(|| bad(at, "slot is a name"))?;
211 return Ok(Node::Slot { name: name.to_string(), props: attrs(o.get("props"), &format!("{at}.props"))? });
212 }
213 Err(bad(at, "a node is el, text, if, each, component or slot"))
214}
215
216fn keys(v: Option<&Value>) -> Result<Vec<crate::keys::KeyDecl>, TreeError> {
219 let Some(v) = v else { return Ok(Vec::new()) };
220 let o = v.as_object().ok_or_else(|| bad("keys", "a map of chord → { to, label, in_inputs, only }"))?;
221 let mut out = Vec::new();
222 for (chord, e) in o {
223 let at = format!("keys.{chord}");
224 let e = e.as_object().ok_or_else(|| bad(&at, "a map"))?;
225 let to = e.get("to").and_then(Value::as_str).ok_or_else(|| bad(&at, "to is a string"))?;
226 let label = match e.get("label") {
227 None => None,
228 Some(Value::String(l)) => Some(l.clone()),
229 Some(_) => return Err(bad(&at, "label is a string")),
230 };
231 let flag = |k: &str| match e.get(k) {
232 None => Ok(false),
233 Some(Value::Bool(b)) => Ok(*b),
234 Some(_) => Err(bad(&at, &format!("{k} is true or false"))),
235 };
236 out.push(crate::keys::KeyDecl::new(chord, to, label, flag("in_inputs")?, flag("only")?).map_err(|m| bad(&at, &m))?.controls(flag("in_controls")?));
237 }
238 Ok(out)
239}
240
241fn params(v: Option<&Value>, at: &str) -> Result<BTreeMap<String, Value>, TreeError> {
242 match v {
243 None | Some(Value::Null) => Ok(BTreeMap::new()),
244 Some(Value::Object(o)) => Ok(o.iter().map(|(k, v)| (k.clone(), v.clone())).collect()),
245 Some(_) => Err(bad(at, "params are a map")),
246 }
247}
248
249impl ComponentTree {
250 pub fn parse(json: &str) -> Result<Self, TreeError> {
253 let tree = Self::read(json)?;
254 tree.check()?;
255 Ok(tree)
256 }
257
258 pub fn read(json: &str) -> Result<Self, TreeError> {
262 let v: Value = serde_json::from_str(json).map_err(|e| TreeError::Malformed(e.to_string()))?;
263 let o = v.as_object().ok_or_else(|| bad("the tree", "a map"))?;
264 let s = |k: &str| o.get(k).and_then(Value::as_str).map(str::to_string).ok_or_else(|| bad("the tree", &format!("{k} is a string")));
265 let list = |k: &str| -> Result<Vec<String>, TreeError> {
266 match o.get(k) {
267 None => Ok(Vec::new()),
268 Some(Value::Array(a)) => a.iter().map(|x| x.as_str().map(str::to_string).ok_or_else(|| bad(k, "a list of strings"))).collect(),
269 Some(_) => Err(bad(k, "a list of strings")),
270 }
271 };
272 let mut live = BTreeMap::new();
273 if let Some(l) = o.get("live") {
274 for (name, d) in l.as_object().ok_or_else(|| bad("live", "a map"))? {
275 let at = format!("live.{name}");
276 let d = d.as_object().ok_or_else(|| bad(&at, "a map"))?;
277 let ds = |k: &str| d.get(k).and_then(Value::as_str).map(str::to_string).ok_or_else(|| bad(&at, &format!("{k} is a string")));
278 live.insert(
279 name.clone(),
280 LiveDecl {
281 snapshot: ds("snapshot")?,
282 params: params(d.get("params"), &at)?,
283 changes: d.get("changes").and_then(Value::as_str).map(str::to_string),
284 changes_params: params(d.get("changes_params"), &at)?,
285 key: ds("key")?,
286 on: strings(d.get("on"), &format!("{at}.on"))?,
287 debounce_ms: d.get("debounce_ms").and_then(Value::as_u64),
288 when: d.get("when").cloned(),
289 },
290 );
291 }
292 }
293 let state = match o.get("state") {
294 None => Map::new(),
295 Some(Value::Object(m)) => m.clone(),
296 Some(_) => return Err(bad("state", "a map")),
297 };
298 let tree = Self {
299 name: s("name")?,
300 abi: s("abi")?,
301 props: list("props")?,
302 state,
303 live,
304 uses: list("uses")?,
305 bus: strings(o.get("bus"), "bus")?,
306 handlers: o.get("handlers").and_then(Value::as_str).unwrap_or_default().to_string(),
307 tree: nodes(Some(o.get("tree").ok_or_else(|| bad("the tree", "tree is a list"))?), "tree")?,
308 css: o.get("css").and_then(Value::as_str).map(str::to_string),
309 keys: keys(o.get("keys"))?,
310 };
311 Ok(tree)
312 }
313
314 pub fn check(&self) -> Result<(), TreeError> {
316 fn walk(nodes: &[Node], out: &mut Vec<String>) {
317 for n in nodes {
318 match n {
319 Node::El { attrs, children, .. } => {
320 out.extend(attrs.values().filter_map(|a| if let Attr::Expr(e) = a { Some(e.clone()) } else { None }));
321 walk(children, out);
322 }
323 Node::Text(Attr::Expr(e)) => out.push(e.clone()),
324 Node::Text(_) => {}
325 Node::If { cond, then, otherwise } => {
326 out.push(cond.clone());
327 walk(then, out);
328 walk(otherwise, out);
329 }
330 Node::Each { expr, key, body, .. } => {
331 out.push(expr.clone());
332 out.push(key.clone());
333 walk(body, out);
334 }
335 Node::Component { props, .. } | Node::Slot { props, .. } => {
336 out.extend(props.values().filter_map(|a| if let Attr::Expr(e) = a { Some(e.clone()) } else { None }));
337 }
338 Node::Html(e) => out.push(e.clone()),
339 }
340 }
341 }
342 let mut all = Vec::new();
343 walk(&self.tree, &mut all);
344 for e in all {
345 Expr::compile(&e).map_err(|message| TreeError::Expr { expr: e.clone(), message })?;
346 }
347 Ok(())
348 }
349}
350
351pub trait Renderer: Clone + 'static {
354 type Node: Clone + PartialEq + std::fmt::Debug + 'static;
355 fn create_element(&self, tag: &str) -> Self::Node;
356 fn create_text(&self, text: &str) -> Self::Node;
358 fn set_attr(&self, node: &Self::Node, name: &str, value: &str);
359 fn remove_attr(&self, node: &Self::Node, name: &str);
361 fn set_text(&self, node: &Self::Node, text: &str);
362 fn insert(&self, parent: &Self::Node, child: &Self::Node, before: Option<&Self::Node>);
364 fn remove(&self, parent: &Self::Node, child: &Self::Node);
365 fn listen(&self, node: &Self::Node, event: &str, handler: Rc<dyn Fn(Value)>) -> Unlisten;
370 fn marks(&self, root: &Self::Node) -> Vec<Self::Node>;
373 fn attrs(&self, node: &Self::Node) -> Vec<(String, String)>;
375 fn contains(&self, ancestor: &Self::Node, node: &Self::Node) -> bool;
377 fn observe(&self, root: &Self::Node, f: Rc<dyn Fn(Vec<Self::Node>)>) -> Unlisten;
384 fn sheet(&self, key: &str, css: &str, on: bool) {
389 let _ = (key, css, on);
390 }
391 fn listen_keys(&self, f: Rc<dyn Fn(&crate::keys::Press) -> bool>) -> Unlisten {
397 let _ = f;
398 Box::new(|| {})
399 }
400 fn keys_overlay(&self, groups: Option<&crate::keys::KeyGroups>) {
403 let _ = groups;
404 }
405}
406
407pub type Unlisten = Box<dyn FnOnce()>;
409
410pub trait Children<R: Renderer> {
413 fn mount_component(&self, at: &R::Node, name: &str, props: Map<String, Value>);
415 fn mount_slot(&self, at: &R::Node, layout: &str, slot: &str, props: Map<String, Value>);
417 fn unmount(&self, at: &R::Node);
419 fn binds(&self, _name: &str) -> bool {
422 false
423 }
424 fn mount_bound(&self, at: &R::Node, _layout: &str, name: &str, props: Map<String, Value>) {
427 self.mount_component(at, name, props)
428 }
429}
430
431#[derive(Clone, Debug)]
434pub struct State {
435 rt: Runtime,
436 keys: Rc<RefCell<BTreeMap<String, Signal<Value>>>>,
437}
438
439impl State {
440 pub fn new(rt: &Runtime, initial: &Map<String, Value>) -> Self {
442 let keys = initial.iter().map(|(k, v)| (k.clone(), rt.signal(v.clone()))).collect();
443 Self { rt: rt.clone(), keys: Rc::new(RefCell::new(keys)) }
444 }
445
446 pub fn snapshot(&self) -> Map<String, Value> {
448 self.keys.borrow().iter().map(|(k, s)| (k.clone(), s.peek())).collect()
449 }
450
451 pub fn shape(&self) -> Vec<String> {
453 self.keys.borrow().keys().cloned().collect()
454 }
455
456 pub fn replace(&self, next: &Map<String, Value>) {
459 self.rt.batch(|| {
460 for (k, v) in next {
461 let existing = self.keys.borrow().get(k).cloned();
462 match existing {
463 Some(sig) => sig.set(v.clone()),
464 None => {
465 let sig = self.rt.signal(v.clone());
466 self.keys.borrow_mut().insert(k.clone(), sig);
467 }
468 }
469 }
470 });
471 }
472
473 fn read(&self, keys: Option<&std::collections::BTreeSet<String>>) -> Map<String, Value> {
475 let all = self.keys.borrow();
476 match keys {
477 None => all.iter().map(|(k, s)| (k.clone(), s.get())).collect(),
478 Some(keys) => keys.iter().filter_map(|k| all.get(k).map(|s| (k.clone(), s.get()))).collect(),
479 }
480 }
481}
482
483pub fn eval_when(when: Option<&Value>, props: &Map<String, Value>, state: &State) -> bool {
491 let Some(w) = when else { return true };
492 let mut one = BTreeMap::new();
493 one.insert("when".to_string(), w.clone());
494 match eval_params(&one, props, state).get("when") {
495 None | Some(Value::Null) | Some(Value::Bool(false)) => false,
496 Some(Value::String(s)) => !s.is_empty(),
497 Some(Value::Number(n)) => n.as_f64() != Some(0.0),
498 Some(_) => true,
499 }
500}
501
502pub fn eval_params(params: &BTreeMap<String, Value>, props: &Map<String, Value>, state: &State) -> Value {
503 let mut out = Map::new();
504 for (k, v) in params {
505 let text = v.as_object().and_then(|o| o.get("expr")).and_then(Value::as_str);
506 if let Some(path) = text.and_then(expr::path_of) {
509 let fields = &path[1..];
510 let found = if path[0] == "state" {
511 let keys: Option<std::collections::BTreeSet<String>> = fields.first().map(|k| [k.clone()].into());
512 Some(expr::walk(&Value::Object(state.read(keys.as_ref())), fields).cloned().unwrap_or(Value::Null))
513 } else {
514 props.get(&path[0]).map(|p| expr::walk(p, fields).cloned().unwrap_or(Value::Null))
515 };
516 if let Some(found) = found {
517 out.insert(k.clone(), found);
518 continue;
519 }
520 }
521 let value = match text {
522 None => v.clone(),
523 Some(text) => match Expr::compile(text) {
524 Err(m) => {
525 warn(&format!("the param {k}: `{text}`: {m}"));
526 Value::Null
527 }
528 Ok(e) => {
529 let mut scope = rhai::Scope::new();
530 for (pk, pv) in props {
531 if e.reads.names.contains(pk) {
532 scope.push_constant_dynamic(pk.clone(), expr::to_dynamic(pv));
533 }
534 }
535 if e.reads.names.contains("state") {
536 scope.push_dynamic("state", expr::to_dynamic(&Value::Object(state.read(e.reads.state_keys.as_ref()))));
537 }
538 e.eval(&mut scope).map(|d| expr::to_value(&d)).unwrap_or_else(|m| {
539 warn(&format!("the param {k}: `{text}`: {m}"));
540 Value::Null
541 })
542 }
543 },
544 };
545 out.insert(k.clone(), value);
546 }
547 Value::Object(out)
548}
549
550pub struct Scope {
553 pub props: Map<String, Value>,
554 pub state: State,
555 pub live: BTreeMap<String, Signal<Value>>,
556 pub on_event: Rc<dyn Fn(&str, Value)>,
558}
559
560struct Ctx<R: Renderer> {
562 rt: Runtime,
563 renderer: R,
564 layout: String,
565 scope: Scope,
566 children: Rc<dyn Children<R>>,
567}
568
569type Memo = Rc<RefCell<Memoed>>;
574
575#[derive(Default)]
576enum Memoed {
577 #[default]
578 Empty,
579 Seen(std::rc::Weak<dyn std::any::Any>),
580 Kept(std::rc::Weak<dyn std::any::Any>, rhai::Dynamic),
581}
582
583#[derive(Clone)]
587struct Var {
588 name: String,
589 sig: Signal<Value>,
590 memo: Memo,
591}
592
593type Env = Rc<Vec<Var>>;
595
596fn memoized(sig: &Signal<Value>, memo: &Memo) -> rhai::Dynamic {
598 let held = sig.shared();
599 let again = match &*memo.borrow() {
600 Memoed::Kept(was, d) if std::rc::Weak::ptr_eq(was, &Rc::downgrade(&held)) => return d.clone(),
601 Memoed::Seen(was) => std::rc::Weak::ptr_eq(was, &Rc::downgrade(&held)),
602 _ => false,
603 };
604 let d = expr::to_dynamic(held.downcast_ref::<Value>().expect("a value"));
605 let was = Rc::downgrade(&held);
606 *memo.borrow_mut() = if again { Memoed::Kept(was, d.clone()) } else { Memoed::Seen(was) };
607 d
608}
609
610struct Block<R: Renderer> {
614 top: Vec<R::Node>,
615 bindings: Vec<BindingId>,
616 unlisten: Vec<Unlisten>,
618 hosts: Vec<R::Node>,
619 dyns: Vec<Rc<RefCell<Dyn<R>>>>,
620}
621
622impl<R: Renderer> Default for Block<R> {
623 fn default() -> Self {
624 Self { top: Vec::new(), bindings: Vec::new(), unlisten: Vec::new(), hosts: Vec::new(), dyns: Vec::new() }
625 }
626}
627
628struct Dyn<R: Renderer> {
630 parent: R::Node,
631 top: bool,
634 rows: Vec<(String, Block<R>, Option<Signal<Value>>)>,
635}
636
637impl<R: Renderer> Ctx<R> {
638 fn expr(&self, text: &str) -> Option<Expr> {
639 match Expr::compile(text) {
641 Ok(e) => Some(e),
642 Err(m) => {
643 warn(&format!("{}: the expression `{text}`: {m}", self.layout));
644 None
645 }
646 }
647 }
648
649 fn eval(&self, env: &Env, text: &str) -> rhai::Dynamic {
652 self.eval_with(env, None, text)
653 }
654
655 fn eval_with(&self, env: &Env, extra: Option<(&str, &Value)>, text: &str) -> rhai::Dynamic {
657 let Some(e) = self.expr(text) else { return rhai::Dynamic::UNIT };
658 if let Some(v) = e.path.as_ref().and_then(|p| self.path_value(env, extra, &e, p)) {
659 return expr::to_dynamic(&v);
660 }
661 let mut scope = rhai::Scope::new();
662 for (k, v) in &self.scope.props {
663 if e.reads.names.contains(k) {
664 scope.push_constant_dynamic(k.clone(), expr::to_dynamic(v));
665 }
666 }
667 if e.reads.names.contains("state") {
668 let state = self.scope.state.read(e.reads.state_keys.as_ref());
669 scope.push_dynamic("state", expr::to_dynamic(&Value::Object(state)));
670 }
671 for (k, sig) in &self.scope.live {
672 if e.reads.names.contains(k) {
673 scope.push_dynamic(k.clone(), sig.with(expr::to_dynamic));
679 }
680 }
681 for v in env.iter() {
682 if e.reads.names.contains(&v.name) {
683 scope.push_dynamic(v.name.clone(), memoized(&v.sig, &v.memo));
684 }
685 }
686 if let Some((k, v)) = extra {
687 scope.push_constant_dynamic(k.to_string(), expr::to_dynamic(v));
688 }
689 match e.eval(&mut scope) {
690 Ok(d) => d,
691 Err(m) => {
692 warn(&format!("{}: `{text}`: {m}", self.layout));
693 rhai::Dynamic::UNIT
694 }
695 }
696 }
697
698 fn path_value(&self, env: &Env, extra: Option<(&str, &Value)>, e: &Expr, path: &[String]) -> Option<Value> {
703 let (name, fields) = (&path[0], &path[1..]);
704 let null = || Value::Null;
705 if let Some((k, v)) = extra {
706 if k == name {
707 return Some(expr::walk(v, fields).cloned().unwrap_or_else(null));
708 }
709 }
710 if let Some(v) = env.iter().rev().find(|v| &v.name == name) {
711 return Some(v.sig.with(|row| expr::walk(row, fields).cloned().unwrap_or_else(null)));
712 }
713 if let Some(sig) = self.scope.live.get(name) {
714 return Some(sig.with(|l| expr::walk(l, fields).cloned().unwrap_or_else(null)));
715 }
716 if name == "state" {
717 let state = Value::Object(self.scope.state.read(e.reads.state_keys.as_ref()));
718 return Some(expr::walk(&state, fields).cloned().unwrap_or_else(null));
719 }
720 self.scope.props.get(name).map(|v| expr::walk(v, fields).cloned().unwrap_or_else(null))
721 }
722
723 fn eval_value(&self, env: &Env, extra: Option<(&str, &Value)>, text: &str) -> Value {
725 if let Some(e) = self.expr(text) {
726 if let Some(v) = e.path.as_ref().and_then(|p| self.path_value(env, extra, &e, p)) {
727 return v;
728 }
729 }
730 expr::to_value(&self.eval_with(env, extra, text))
731 }
732
733 fn props(&self, env: &Env, props: &BTreeMap<String, Attr>) -> Map<String, Value> {
734 self.rt.untracked(|| {
735 props
736 .iter()
737 .map(|(k, a)| {
738 let v = match a {
739 Attr::Lit(s) => Value::String(s.clone()),
740 Attr::Expr(e) => expr::to_value(&self.eval(env, e)),
741 };
742 (k.clone(), v)
743 })
744 .collect()
745 })
746 }
747}
748
749fn warn(msg: &str) {
750 #[cfg(feature = "dom")]
751 web_sys::console::warn_1(&msg.into());
752 #[cfg(not(feature = "dom"))]
753 let _ = msg;
754}
755
756fn watch<T: PartialEq + Clone + 'static>(rt: &Runtime, mut compute: impl FnMut() -> T + 'static, mut changed: impl FnMut(T) + 'static) -> (BindingId, T) {
759 let last: Rc<RefCell<Option<T>>> = Rc::default();
760 let (l, r) = (last.clone(), rt.clone());
761 let id = rt.bind(move || {
762 let v = compute();
763 let mut held = l.borrow_mut();
764 match held.as_ref() {
765 None => *held = Some(v),
766 Some(old) if *old == v => {}
767 Some(_) => {
768 *held = Some(v.clone());
769 drop(held);
770 r.untracked(|| changed(v));
771 }
772 }
773 });
774 let first = last.borrow().clone().expect("a binding runs when made");
775 (id, first)
776}
777
778fn build<R: Renderer>(ctx: &Rc<Ctx<R>>, env: &Env, nodes: &[Node], parent: &R::Node, before: Option<&R::Node>, block: &mut Block<R>, top: bool) {
779 for n in nodes {
780 build_node(ctx, env, n, parent, before, block, top);
781 }
782}
783
784fn place<R: Renderer>(ctx: &Ctx<R>, parent: &R::Node, node: &R::Node, before: Option<&R::Node>, block: &mut Block<R>, top: bool) {
785 ctx.renderer.insert(parent, node, before);
786 if top {
787 block.top.push(node.clone());
788 }
789}
790
791fn build_node<R: Renderer>(ctx: &Rc<Ctx<R>>, env: &Env, node: &Node, parent: &R::Node, before: Option<&R::Node>, block: &mut Block<R>, top: bool) {
792 let r = &ctx.renderer;
793 match node {
794 Node::El { el, attrs, on, children } => {
795 let e = r.create_element(el);
796 for (name, a) in attrs {
797 match a {
798 Attr::Lit(v) => r.set_attr(&e, name, v),
799 Attr::Expr(x) => {
800 let (c, env2, x2) = (ctx.clone(), env.clone(), x.clone());
801 let (c2, e2, name2) = (ctx.clone(), e.clone(), name.clone());
802 let (id, first) = watch(&ctx.rt, move || expr::as_text(&c.eval(&env2, &x2)), move |v: String| c2.renderer.set_attr(&e2, &name2, &v));
803 r.set_attr(&e, name, &first);
804 block.bindings.push(id);
805 }
806 }
807 }
808 for (event, handler) in on {
809 let (on_event, handler) = (ctx.scope.on_event.clone(), handler.clone());
810 block.unlisten.push(r.listen(&e, event, Rc::new(move |payload: Value| on_event(&handler, payload))));
811 }
812 build(ctx, env, children, &e, None, block, false);
813 place(ctx, parent, &e, before, block, top);
814 }
815 Node::Text(Attr::Lit(t)) => {
816 let t = r.create_text(t);
817 place(ctx, parent, &t, before, block, top);
818 }
819 Node::Text(Attr::Expr(x)) => {
820 let cell: Rc<RefCell<Option<R::Node>>> = Rc::default();
821 let (c, env2, x2) = (ctx.clone(), env.clone(), x.clone());
822 let (c2, cell2) = (ctx.clone(), cell.clone());
823 let (id, first) = watch(&ctx.rt, move || expr::as_text(&c.eval(&env2, &x2)), move |v: String| {
824 if let Some(n) = cell2.borrow().as_ref() {
825 c2.renderer.set_text(n, &v);
826 }
827 });
828 let t = r.create_text(&first);
829 *cell.borrow_mut() = Some(t.clone());
830 block.bindings.push(id);
831 place(ctx, parent, &t, before, block, top);
832 }
833 Node::If { cond, then, otherwise } => {
834 let anchor = r.create_text("");
835 place(ctx, parent, &anchor, before, block, top);
836 let d = Rc::new(RefCell::new(Dyn { parent: parent.clone(), top, rows: Vec::new() }));
837 let branches = Rc::new((then.clone(), otherwise.clone()));
838 let (c, env2, cond2) = (ctx.clone(), env.clone(), cond.clone());
839 let (c2, env3, d2, a2, b2) = (ctx.clone(), env.clone(), d.clone(), anchor.clone(), branches.clone());
840 let (id, first) = watch(&ctx.rt, move || expr::truthy(&c.eval(&env2, &cond2)), move |v: bool| {
841 fill_if(&c2, &env3, &d2, &a2, &b2, v);
842 });
843 block.bindings.push(id);
844 ctx.rt.untracked(|| fill_if(ctx, env, &d, &anchor, &branches, first));
845 block.dyns.push(d);
846 }
847 Node::Each { expr: list, as_, key, body } => {
848 let anchor = r.create_text("");
849 place(ctx, parent, &anchor, before, block, top);
850 let d = Rc::new(RefCell::new(Dyn { parent: parent.clone(), top, rows: Vec::new() }));
851 let spec = Rc::new((as_.clone(), body.clone()));
852 let (c, env2, list2, as2, key2) = (ctx.clone(), env.clone(), list.clone(), as_.clone(), key.clone());
853 let (c2, env3, d2, a2, s2) = (ctx.clone(), env.clone(), d.clone(), anchor.clone(), spec.clone());
854 let (id, first) = watch(
855 &ctx.rt,
856 move || keyed(&c, &env2, &list2, &as2, &key2),
857 move |rows: Vec<(String, Value)>| reconcile(&c2, &env3, &d2, &a2, &s2, rows),
858 );
859 block.bindings.push(id);
860 ctx.rt.untracked(|| reconcile(ctx, env, &d, &anchor, &spec, first));
861 block.dyns.push(d);
862 }
863 Node::Component { name, props } => {
864 let props = ctx.props(env, props);
865 let e = if ctx.children.binds(name) {
866 let e = r.create_element("div");
867 r.set_attr(&e, "data-layout", &ctx.layout);
868 r.set_attr(&e, "data-slot", name);
869 r.set_attr(&e, "data-component", name);
870 ctx.children.mount_bound(&e, &ctx.layout, name, props);
871 e
872 } else {
873 let e = r.create_element(name);
874 ctx.children.mount_component(&e, name, props);
875 e
876 };
877 block.hosts.push(e.clone());
878 place(ctx, parent, &e, before, block, top);
879 }
880 Node::Html(x) => {
881 let anchor = r.create_text("");
882 place(ctx, parent, &anchor, before, block, top);
883 let d = Rc::new(RefCell::new(Dyn { parent: parent.clone(), top, rows: Vec::new() }));
884 let (c, env2, x2) = (ctx.clone(), env.clone(), x.clone());
885 let (c2, d2, a2) = (ctx.clone(), d.clone(), anchor.clone());
886 let (id, first) = watch(&ctx.rt, move || expr::as_text(&c.eval(&env2, &x2)), move |html: String| fill_html(&c2, &d2, &a2, &html));
887 block.bindings.push(id);
888 ctx.rt.untracked(|| fill_html(ctx, &d, &anchor, &first));
889 block.dyns.push(d);
890 }
891 Node::Slot { name, props } => {
892 let e = r.create_element("div");
893 r.set_attr(&e, "data-layout", &ctx.layout);
894 r.set_attr(&e, "data-slot", name);
895 let props = ctx.props(env, props);
896 ctx.children.mount_slot(&e, &ctx.layout, name, props);
897 block.hosts.push(e.clone());
898 place(ctx, parent, &e, before, block, top);
899 }
900 }
901}
902
903fn fill_html<R: Renderer>(ctx: &Rc<Ctx<R>>, d: &Rc<RefCell<Dyn<R>>>, anchor: &R::Node, html: &str) {
906 let (old, parent) = {
907 let mut d = d.borrow_mut();
908 (std::mem::take(&mut d.rows), d.parent.clone())
909 };
910 for (_, b, _) in old {
911 dispose(ctx, b, Some(&parent));
912 }
913 fn draw<R: Renderer>(r: &R, nodes: &[crate::html::HNode], parent: &R::Node, before: Option<&R::Node>, top: &mut Vec<R::Node>) {
914 for n in nodes {
915 let node = match n {
916 crate::html::HNode::Text(t) => r.create_text(t),
917 crate::html::HNode::Element { tag, attrs, children } => {
918 let e = r.create_element(tag);
919 for (k, v) in attrs {
920 r.set_attr(&e, k, v);
921 }
922 draw(r, children, &e, None, &mut Vec::new());
923 e
924 }
925 };
926 r.insert(parent, &node, before);
927 top.push(node);
928 }
929 }
930 let mut b = Block::default();
931 draw(&ctx.renderer, &crate::html::sanitize(html), &parent, Some(anchor), &mut b.top);
932 d.borrow_mut().rows.push((String::new(), b, None));
933}
934
935fn fill_if<R: Renderer>(ctx: &Rc<Ctx<R>>, env: &Env, d: &Rc<RefCell<Dyn<R>>>, anchor: &R::Node, branches: &(Vec<Node>, Vec<Node>), on: bool) {
936 let (old, parent) = {
937 let mut d = d.borrow_mut();
938 (std::mem::take(&mut d.rows), d.parent.clone())
939 };
940 for (_, b, _) in old {
941 dispose(ctx, b, Some(&parent));
942 }
943 let nodes = if on { &branches.0 } else { &branches.1 };
944 if nodes.is_empty() {
945 return;
946 }
947 let mut b = Block::default();
948 build(ctx, env, nodes, &parent, Some(anchor), &mut b, true);
949 d.borrow_mut().rows.push((String::new(), b, None));
950}
951
952fn keyed<R: Renderer>(ctx: &Ctx<R>, env: &Env, list: &str, as_: &str, key: &str) -> Vec<(String, Value)> {
955 let items = match ctx.eval_value(env, None, list) {
956 Value::Array(a) => a,
957 _ => Vec::new(),
958 };
959 ctx.rt.untracked(|| {
960 let mut seen = std::collections::BTreeSet::new();
961 items
962 .into_iter()
963 .enumerate()
964 .map(|(i, item)| {
965 let mut k = match ctx.eval_value(env, Some((as_, &item)), key) {
966 Value::String(s) => s,
967 other => expr::as_text(&expr::to_dynamic(&other)),
968 };
969 if !seen.insert(k.clone()) {
970 k = format!("{k}#{i}");
971 }
972 (k, item)
973 })
974 .collect()
975 })
976}
977
978fn reconcile<R: Renderer>(ctx: &Rc<Ctx<R>>, env: &Env, d: &Rc<RefCell<Dyn<R>>>, anchor: &R::Node, spec: &(String, Vec<Node>), rows: Vec<(String, Value)>) {
979 let (mut old, parent) = {
980 let mut d = d.borrow_mut();
981 (std::mem::take(&mut d.rows), d.parent.clone())
982 };
983 let wanted: std::collections::BTreeSet<&String> = rows.iter().map(|(k, _)| k).collect();
985 let mut kept = Vec::new();
986 for (k, b, s) in old.drain(..) {
987 if wanted.contains(&k) {
988 kept.push((k, b, s));
989 } else {
990 dispose(ctx, b, Some(&parent));
991 }
992 }
993 let kept_order: Vec<&String> = kept.iter().map(|(k, _, _)| k).collect();
995 let new_order: Vec<&String> = rows.iter().map(|(k, _)| k).filter(|k| kept_order.contains(k)).collect();
996 let moved = kept_order != new_order;
997 let mut by_key: BTreeMap<String, (Block<R>, Option<Signal<Value>>)> = kept.into_iter().map(|(k, b, s)| (k, (b, s))).collect();
998 let mut next: Vec<(String, Block<R>, Option<Signal<Value>>)> = Vec::with_capacity(rows.len());
999 let mut before = anchor.clone();
1000 for (k, item) in rows.into_iter().rev() {
1001 match by_key.remove(&k) {
1002 Some((b, s)) => {
1003 if let Some(s) = &s {
1004 s.set(item);
1005 }
1006 if moved {
1007 for n in &b.top {
1008 ctx.renderer.insert(&parent, n, Some(&before));
1009 }
1010 }
1011 if let Some(first) = b.top.first() {
1012 before = first.clone();
1013 }
1014 next.push((k, b, s));
1015 }
1016 None => {
1017 let sig = ctx.rt.signal(item);
1018 let mut inner = (**env).clone();
1019 inner.push(Var { name: spec.0.clone(), sig: sig.clone(), memo: Memo::default() });
1020 let mut b = Block::default();
1021 build(ctx, &Rc::new(inner), &spec.1, &parent, Some(&before), &mut b, true);
1022 if let Some(first) = b.top.first() {
1023 before = first.clone();
1024 }
1025 next.push((k, b, Some(sig)));
1026 }
1027 }
1028 }
1029 next.reverse();
1030 d.borrow_mut().rows = next;
1031}
1032
1033fn dispose<R: Renderer>(ctx: &Ctx<R>, block: Block<R>, parent: Option<&R::Node>) {
1036 for id in block.bindings {
1037 ctx.rt.dispose(id);
1038 }
1039 for off in block.unlisten {
1040 off();
1041 }
1042 for d in block.dyns {
1043 let (rows, dparent, top) = {
1044 let mut d = d.borrow_mut();
1045 (std::mem::take(&mut d.rows), d.parent.clone(), d.top)
1046 };
1047 for (_, b, _) in rows {
1048 dispose(ctx, b, if top && parent.is_some() { Some(&dparent) } else { None });
1049 }
1050 }
1051 for h in &block.hosts {
1052 ctx.children.unmount(h);
1053 }
1054 if let Some(p) = parent {
1055 for n in &block.top {
1056 ctx.renderer.remove(p, n);
1057 }
1058 }
1059}
1060
1061pub struct Mounted<R: Renderer> {
1063 pub parent: R::Node,
1064 ctx: Rc<Ctx<R>>,
1065 block: Block<R>,
1066}
1067
1068impl<R: Renderer> Mounted<R> {
1069 pub fn unmount(self) {
1072 dispose(&self.ctx, self.block, Some(&self.parent));
1073 }
1074
1075 pub fn top(&self) -> Vec<R::Node> {
1077 self.block.top.clone()
1078 }
1079}
1080
1081pub fn mount<R: Renderer>(
1084 rt: &Runtime,
1085 renderer: &R,
1086 tree: &ComponentTree,
1087 scope: Scope,
1088 parent: &R::Node,
1089 children: Rc<dyn Children<R>>,
1090) -> Result<Mounted<R>, TreeError> {
1091 tree.check()?;
1092 let ctx = Rc::new(Ctx { rt: rt.clone(), renderer: renderer.clone(), layout: tree.name.clone(), scope, children });
1093 let mut block = Block::default();
1094 rt.untracked(|| build(&ctx, &Rc::new(Vec::new()), &tree.tree, parent, None, &mut block, true));
1095 Ok(Mounted { parent: parent.clone(), ctx, block })
1096}
1097
1098#[cfg(test)]
1099mod tests;