1mod containers;
19pub mod fields;
20mod misc;
21mod overlays;
22pub use overlays::is_context_menu;
23pub mod search;
24mod table;
25
26use std::collections::HashMap;
27
28use indexmap::IndexMap;
29use serde::{Deserialize, Serialize};
30use serde_json::{json, Map, Value};
31
32use crate::catalog::CatalogView;
33use crate::data::{resolve_value, ResolveContext};
34use crate::list::{ListWindow, VisibleRange};
35use crate::overlay::{OverlayAlign, OverlaySide};
36use crate::recipes::RecipeIndex;
37use crate::strings::StringTable;
38use crate::theme::RecipeQuery;
39use crate::types::{Props, UiNode};
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "lowercase")]
43pub enum NodeKind {
44 Container,
45 Leaf,
46}
47
48#[derive(Debug, Clone, PartialEq)]
51pub struct LNode {
52 pub index: u32,
55 pub id: String,
56 pub component: String,
58 pub part: Option<String>,
60 pub owner: Option<String>,
62 pub owner_component: Option<String>,
63 pub catalog_id: Option<String>,
65 pub extension_kind: Option<String>,
66 pub depth: u32,
67 pub parent: Option<u32>,
68 pub children: Vec<u32>,
69 pub layer: u32,
70 pub kind: NodeKind,
71 pub props: Props,
73 pub base_style: Props,
76 pub default_keys: Vec<String>,
80 pub own_query: Option<RecipeQuery>,
82 pub part_query: Option<RecipeQuery>,
84 pub authored_keys: Vec<String>,
87 pub hidden: bool,
88 pub lines: Option<u32>,
89 pub pressable: bool,
90 pub scope: String,
92 pub source: Option<SourceRef>,
97 pub on: Option<IndexMap<String, Value>>,
99 pub accessibility: Option<Value>,
100 pub trigger_for: Option<String>,
102 pub form: Option<String>,
104 pub live: Option<String>,
106}
107
108#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct SourceRef {
112 pub id: String,
113 pub template: Option<String>,
114}
115
116#[derive(Debug, Clone, PartialEq)]
118pub enum LayerPlacement {
119 Centered,
121 Edge(OverlaySide),
123 Anchored { anchor: u32, side: OverlaySide, align: OverlayAlign },
125 AtPoint { x: f32, y: f32 },
127 Toast { order: u32 },
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
134#[serde(rename_all = "lowercase")]
135pub enum LayerClass {
136 Overlay,
137 Toast,
138}
139
140#[derive(Debug, Clone, PartialEq)]
141pub struct LayerSpec {
142 pub layer: u32,
143 pub root: u32,
144 pub kind: String,
145 pub owner: String,
146 pub placement: LayerPlacement,
147 pub class: LayerClass,
148 pub modal: bool,
150 pub dismissible: bool,
152 pub match_anchor_width: bool,
154 pub scroll_body: Option<u32>,
157 pub mirror: bool,
160}
161
162#[derive(Debug, Clone, PartialEq)]
164pub struct ListSpec {
165 pub node: u32,
166 pub id: String,
168 pub keys: std::sync::Arc<Vec<String>>,
169 pub range: VisibleRange,
170 pub offsets: std::sync::Arc<Vec<f32>>,
171 pub content_height: f32,
174 pub windowed: bool,
175 pub horizontal: bool,
177 pub gap: f32,
179 pub data_index: Option<std::sync::Arc<Vec<Option<usize>>>>,
182 pub headers: std::sync::Arc<Vec<usize>>,
184 pub sticky: bool,
186 pub static_count: usize,
188}
189
190#[derive(Debug, Clone, PartialEq)]
192pub enum ListViewSource {
193 Own,
195 Ancestor { id: String, rel: f32 },
198 Host { rel: f32 },
201}
202
203#[derive(Debug, Clone, PartialEq)]
205pub struct ListView {
206 pub source: ListViewSource,
207 pub viewport: f32,
208}
209
210#[derive(Debug, Clone, Default, PartialEq)]
212pub struct FieldErrors {
213 pub name: String,
214 pub messages: Vec<String>,
215}
216
217#[derive(Debug, Clone, Default)]
219pub struct LocalState {
220 pub tabs: HashMap<String, String>,
221 pub accordion: HashMap<String, Vec<String>>,
222 pub carousel: HashMap<String, i64>,
223 pub open: HashMap<String, bool>,
224 pub pressed_toggles: HashMap<String, bool>,
225 pub holds: HashMap<String, crate::hold::HoldTracker>,
227 pub lists: HashMap<String, ListWindow>,
228 pub scroll: HashMap<String, (f32, f32)>,
230 pub query: HashMap<String, String>,
232 pub month: HashMap<String, (i32, u32)>,
234 pub range_anchor: HashMap<String, String>,
236 pub submenu: HashMap<String, usize>,
238 pub active: HashMap<String, usize>,
242 pub context_point: HashMap<String, (f32, f32)>,
244 pub field_values: HashMap<String, Value>,
246 pub errors: HashMap<String, FieldErrors>,
248 pub sort: HashMap<String, (String, String)>,
250 pub selected: HashMap<String, Vec<String>>,
251 pub chips: HashMap<String, Vec<String>>,
253 pub files: HashMap<String, Vec<Value>>,
254 pub copied: HashMap<String, bool>,
256 pub static_keys: HashMap<String, std::sync::Arc<Vec<String>>>,
258 pub list_views: HashMap<String, ListView>,
260 pub surface_scroll: Option<(f32, f32)>,
264 pub sizes: HashMap<String, Vec<f64>>,
267 pub drags: HashMap<String, Vec<f64>>,
269 pub sticky_any: bool,
271 pub key_cache: HashMap<String, (u64, std::sync::Arc<Vec<String>>)>,
275}
276
277pub struct BuildContext<'a> {
278 pub view: &'a CatalogView,
279 pub recipes: &'a RecipeIndex,
280 pub data: &'a Value,
281 pub local: &'a mut LocalState,
282 pub template: &'a dyn Fn(&str) -> Option<UiNode>,
284 pub viewport_height: f32,
285 pub viewport_width: f32,
287 pub hairline: f32,
290 pub row_extent: f32,
291 pub menu_row: f32,
294 pub tab_bar: f32,
297 pub gap_px: &'a dyn Fn(&str) -> f32,
299 pub expand_controls: bool,
302 pub strings: &'a StringTable,
304 pub breakpoint: Option<String>,
306 pub locale: &'a str,
308 pub wide: bool,
310 pub today: Option<String>,
312 pub formatter: &'a dyn crate::format::Formatter,
315 pub now: f64,
317 pub data_version: u64,
319}
320
321pub struct Built {
322 pub nodes: Vec<LNode>,
323 pub layers: Vec<LayerSpec>,
324 pub lists: Vec<ListSpec>,
325 pub responsive: bool,
327 pub toasts: Vec<ToastSpec>,
329 pub row_scopes: HashMap<String, Value>,
332 pub forms: HashMap<String, (bool, bool)>,
334 pub issues: Vec<crate::types::ReduceIssue>,
336}
337
338#[derive(Debug, Clone, Default)]
341pub struct BuildSeed {
342 pub row_scopes: HashMap<String, Value>,
343 pub forms: HashMap<String, (bool, bool)>,
344}
345
346#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
348pub struct ToastSpec {
349 pub id: String,
350 pub duration_ms: f64,
351 #[serde(rename = "type")]
352 pub kind: String,
353}
354
355pub(crate) struct Builder<'a, 'b> {
356 pub(crate) ctx: &'b mut BuildContext<'a>,
357 pub(crate) nodes: Vec<LNode>,
358 pub(crate) layers: Vec<LayerSpec>,
359 pub(crate) lists: Vec<ListSpec>,
360 pub(crate) responsive: bool,
361 pub(crate) toasts: Vec<ToastSpec>,
362 pub(crate) pending_toasts: Vec<(u32, UiNode)>,
364 pub(crate) next_layer: u32,
366 pub(crate) row_scopes: HashMap<String, Value>,
368 pub(crate) forms: HashMap<String, (bool, bool)>,
370 pub(crate) sources: HashMap<String, SourceRef>,
372 pub(crate) suffixes: HashMap<String, std::sync::Arc<Vec<String>>>,
374 pub(crate) flex_gaps: HashMap<u32, f32>,
376 pub(crate) template_items: usize,
378 pub(crate) template_nodes: usize,
382 pub(crate) template_refused: bool,
384 pub(crate) issues: Vec<crate::types::ReduceIssue>,
386}
387
388pub(crate) fn subtree_nodes(root: &UiNode) -> usize {
390 let mut count = 0;
391 let mut stack = vec![root];
392 while let Some(n) = stack.pop() {
393 count += 1;
394 stack.extend(n.children.iter());
395 stack.extend(n.slots.iter().flat_map(|s| s.values()));
396 }
397 count
398}
399
400pub(crate) fn obj(v: Value) -> Props {
401 match v {
402 Value::Object(m) => m,
403 _ => Map::new(),
404 }
405}
406
407fn with_suffix(node: &UiNode, suffix: &str, template: Option<&str>, sources: &mut HashMap<String, SourceRef>) -> UiNode {
408 let mut out = node.clone();
409 out.id = format!("{}{suffix}", node.id);
410 let source = sources.get(&node.id).cloned().unwrap_or_else(|| SourceRef { id: node.id.clone(), template: template.map(str::to_string) });
413 sources.insert(out.id.clone(), source);
414 out.children = node.children.iter().map(|c| with_suffix(c, suffix, template, sources)).collect();
415 if let Some(slots) = &node.slots {
416 out.slots = Some(slots.iter().map(|(k, v)| (k.clone(), with_suffix(v, suffix, template, sources))).collect());
417 }
418 out
419}
420
421pub const OVERLAYS: &[&str] = &["Dialog", "Drawer", "Popover", "Tooltip", "Menu"];
423
424pub const FORM_FIELDS: &[&str] =
426 &["Input", "Textarea", "NumberField", "Checkbox", "Radio", "ChoiceTiles", "Switch", "Select", "ChipInput", "DatePicker", "DateRangePicker", "TimePicker", "FileUpload", "Slider"];
427
428pub(crate) fn display_text_props(def: &crate::types::ComponentDef, props: &mut Props) {
432 for (k, v) in props.iter_mut() {
433 if matches!(v, Value::Number(_) | Value::Bool(_)) && def.props.get(k).is_some_and(|s| s.type_ == "string" || s.type_ == "markdown") {
434 *v = Value::String(crate::format::display_string(v));
435 }
436 }
437}
438
439pub(crate) fn str_prop<'p>(props: &'p Props, key: &str) -> Option<&'p str> {
440 props.get(key).and_then(Value::as_str)
441}
442
443pub(crate) fn bool_prop(props: &Props, key: &str) -> bool {
444 props.get(key).and_then(Value::as_bool).unwrap_or(false)
445}
446
447pub(crate) fn js(v: &Value) -> String {
448 crate::json::to_js_string(v)
449}
450
451impl<'a, 'b> Builder<'a, 'b> {
452 pub(crate) fn resolve_ctx<'s>(&'s self, scope: &'s str) -> ResolveContext<'s> {
453 let ctx = ResolveContext::new(self.ctx.data, scope).with_strings(self.ctx.strings).with_formatter(self.ctx.formatter).with_now(self.ctx.now);
454 match row_scope_root(scope).and_then(|root| self.row_scopes.get_key_value(root)) {
455 Some((root, row)) => ctx.with_overlay(root, row),
456 None => ctx,
457 }
458 }
459
460 pub(crate) fn resolve(&self, value: &Value, scope: &str) -> Option<Value> {
461 resolve_value(value, &self.resolve_ctx(scope))
462 }
463
464 pub(crate) fn resolve_map(&self, map: &Props, scope: &str) -> Props {
465 obj(resolve_value(&Value::Object(map.clone()), &self.resolve_ctx(scope)).unwrap_or(Value::Null))
466 }
467
468 pub(crate) fn string(&self, id: &str) -> String {
470 self.ctx.strings.get(id).cloned().unwrap_or_else(|| id.to_string())
471 }
472
473 pub(crate) fn string_with(&self, id: &str, params: &[(&str, &str)]) -> String {
476 let params: Map<String, Value> = params.iter().map(|(k, v)| (k.to_string(), Value::String(v.to_string()))).collect();
477 crate::strings::format_string(&self.string(id), ¶ms)
478 }
479
480 pub(crate) fn instance(&mut self, node: &UiNode, suffix: &str, template: Option<&str>) -> UiNode {
484 with_suffix(node, suffix, template, &mut self.sources)
485 }
486
487 pub(crate) fn push(&mut self, mut node: LNode) -> u32 {
488 let index = self.nodes.len() as u32;
489 node.index = index;
490 if let Some(p) = node.parent {
491 self.nodes[p as usize].children.push(index);
492 }
493 self.nodes.push(node);
494 index
495 }
496
497 pub(crate) fn blank(&self, id: &str, component: &str, parent: Option<u32>, layer: u32, kind: NodeKind, scope: &str) -> LNode {
498 let (depth, hidden, form) = parent
499 .map(|p| {
500 let pn = &self.nodes[p as usize];
501 (pn.depth + 1, pn.hidden, pn.form.clone())
502 })
503 .unwrap_or((0, false, None));
504 LNode {
505 index: 0,
506 id: id.to_string(),
507 component: component.to_string(),
508 part: None,
509 owner: None,
510 owner_component: None,
511 catalog_id: None,
512 extension_kind: None,
513 depth,
514 parent,
515 children: Vec::new(),
516 layer,
517 kind,
518 props: Map::new(),
519 base_style: Map::new(),
520 default_keys: Vec::new(),
521 own_query: None,
522 part_query: None,
523 authored_keys: Vec::new(),
524 hidden,
525 lines: None,
526 pressable: false,
527 scope: scope.to_string(),
528 source: None,
529 on: None,
530 accessibility: None,
531 trigger_for: None,
532 form,
533 live: None,
534 }
535 }
536
537 #[allow(clippy::too_many_arguments)]
540 pub(crate) fn part_in(&mut self, parent: u32, owner: &LNode, part: &str, component: &str, kind: NodeKind, style: Value, props: Value, suffix: &str) -> u32 {
541 let id = format!("{}.{part}{suffix}", owner.id);
542 let layer = self.nodes[parent as usize].layer;
543 let mut n = self.blank(&id, component, Some(parent), layer, kind, &owner.scope);
544 n.part = Some(part.to_string());
545 n.owner = Some(owner.id.clone());
546 n.owner_component = Some(owner.component.clone());
547 n.base_style = obj(style);
548 n.props = obj(props);
549 let query_props = self.ctx.recipes.native_recipe_props(&owner.component, &owner.props);
550 n.part_query = Some(RecipeQuery::new(owner.component.clone(), part, query_props, Vec::new()));
551 if let Some(l) = n.props.get("lines").and_then(Value::as_u64) {
552 n.lines = Some(l as u32);
553 }
554 self.push(n)
555 }
556
557 pub(crate) fn part(&mut self, owner: &LNode, part: &str, component: &str, kind: NodeKind, style: Value, props: Value) -> u32 {
559 self.part_in(owner.index, owner, part, component, kind, style, props, "")
560 }
561
562 pub(crate) fn text_part(&mut self, parent: u32, owner: &LNode, part: &str, text: &str, variant: &str, suffix: &str) -> u32 {
563 self.part_in(parent, owner, part, "Text", NodeKind::Leaf, json!({}), json!({"text": text, "variant": variant}), suffix)
564 }
565
566 pub(crate) fn icon_part(&mut self, parent: u32, owner: &LNode, part: &str, glyph_slot: &str, suffix: &str) -> u32 {
568 let name = builtin_icon(glyph_slot).unwrap_or("ui-icon-placeholder");
569 self.part_in(parent, owner, part, "Icon", NodeKind::Leaf, json!({"flexShrink": 0}), json!({"name": name, "size": "sm"}), suffix)
570 }
571
572 pub(crate) fn default_a11y(&mut self, index: u32, key: &str, value: Value) {
575 let a = self.nodes[index as usize].accessibility.get_or_insert_with(|| json!({}));
576 if let Some(m) = a.as_object_mut() {
577 m.entry(key.to_string()).or_insert(value);
578 }
579 }
580
581 pub(crate) fn add_state(&mut self, index: u32, state: &str) {
583 if let Some(q) = &mut self.nodes[index as usize].part_query {
584 if !q.states.iter().any(|s| s == state) {
585 q.states.push(state.to_string());
586 }
587 }
588 }
589
590 pub(crate) fn query_prop(&mut self, index: u32, key: &str, value: Value) {
592 if let Some(q) = &mut self.nodes[index as usize].part_query {
593 q.props.insert(key.to_string(), value);
594 }
595 }
596
597 pub(crate) fn style_default(&mut self, index: u32, entries: &[(&str, Value)]) {
598 let n = &mut self.nodes[index as usize];
599 for (k, v) in entries {
600 if !n.base_style.contains_key(*k) {
601 n.base_style.insert(k.to_string(), v.clone());
602 n.default_keys.push(k.to_string());
603 }
604 }
605 }
606
607 fn media_ratio(&mut self, index: u32) {
611 let n = &self.nodes[index as usize];
612 let given = n.props.get("aspectRatio").and_then(Value::as_f64).filter(|r| r.is_finite() && *r > 0.0);
613 let has_height = n.props.get("height").is_some_and(|v| !v.is_null()) || n.base_style.contains_key("height");
614 let ratio = given.or_else(|| (n.component == "Video" || !has_height).then_some(crate::layout::MEDIA_ASPECT_RATIO));
615 if let Some(r) = ratio {
616 self.style_default(index, &[("aspectRatio", json!(r))]);
617 }
618 }
619
620 pub(crate) fn is_overlay(component: &str) -> bool {
621 OVERLAYS.contains(&component)
622 }
623
624 fn visible(&self, node: &UiNode, scope: &str) -> bool {
626 crate::data::is_visible(node.visible.as_ref(), &self.resolve_ctx(scope))
627 }
628
629 pub(crate) fn add(&mut self, node: &UiNode, parent: Option<u32>, layer: u32, scope: &str, force_hidden: bool) -> Option<u32> {
631 crate::deep(|| self.add_node(node, parent, layer, scope, force_hidden))
632 }
633
634 fn add_node(&mut self, node: &UiNode, parent: Option<u32>, layer: u32, scope: &str, force_hidden: bool) -> Option<u32> {
635 if !self.visible(node, scope) {
636 return None;
637 }
638 let view = self.ctx.view;
639 let def = view.component(&node.component);
640 let mut props = crate::data::resolve_node_props(def, &node.props, &self.resolve_ctx(scope), &view.defs);
644 if let Some(def) = def {
645 display_text_props(def, &mut props);
646 }
647 self.local_overrides(&node.id, &node.component, &mut props);
648 let form = parent.and_then(|p| self.nodes[p as usize].form.clone());
651 if let Some((disabled, busy)) = form.as_ref().and_then(|f| self.forms.get(f)).copied() {
652 if disabled && (FORM_FIELDS.contains(&node.component.as_str()) || node.component == "Button") {
653 props.insert("disabled".into(), Value::Bool(true));
654 }
655 if busy && node.component == "Button" && bool_prop(&props, "submit") {
656 props.insert("loading".into(), Value::Bool(true));
657 }
658 }
659 let ext = view.extension_of(&node.component).map(str::to_string);
660 let children_rule = def.map(|d| d.children.as_str()).unwrap_or("none");
661 let has_children = !node.children.is_empty() || node.template.is_some();
662 let component = if ext.is_some() { "Extension".to_string() } else { node.component.clone() };
663 let kind = if ext.is_some() {
664 if has_children {
665 NodeKind::Container
666 } else {
667 NodeKind::Leaf
668 }
669 } else {
670 match (node.component.as_str(), children_rule) {
671 ("Box", _) => NodeKind::Container,
672 (_, "none") => NodeKind::Leaf,
673 ("Button", "one") => {
674 if has_children {
675 NodeKind::Container
676 } else {
677 NodeKind::Leaf
678 }
679 }
680 _ => NodeKind::Container,
681 }
682 };
683 let mut n = self.blank(&node.id, &component, parent, layer, kind, scope);
684 n.hidden |= force_hidden;
685 if let Some(e) = ext {
686 n.catalog_id = Some(e);
687 n.extension_kind = Some(node.component.clone());
688 }
689 let mut base: Props = props.get("style").and_then(Value::as_object).cloned().unwrap_or_default();
692 if let Some(s) = &node.style {
693 for (k, v) in self.resolve_map(s, scope) {
694 base.insert(k, v);
695 }
696 }
697 n.base_style = base;
698 n.lines = props.get("lines").and_then(Value::as_u64).map(|l| l as u32);
699 n.pressable = (node.on.as_ref().is_some_and(|o| o.contains_key("press")) || bool_prop(&props, "pressable") || (node.component == "Button" && (bool_prop(&props, "submit") || bool_prop(&props, "hold")))) && !bool_prop(&props, "disabled") && !bool_prop(&props, "loading");
700 n.on = node.on.clone();
701 n.source = self.sources.get(&node.id).cloned();
702 n.accessibility = node.accessibility.as_ref().and_then(|a| self.resolve(a, scope));
703 n.live = str_prop(&props, "live").filter(|l| *l != "off").map(str::to_string);
704 n.own_query = Some(RecipeQuery::new(node.component.clone(), "root", self.ctx.recipes.native_recipe_props(&node.component, &props), Vec::new()));
705 if let Some(r) = &node.recipe {
706 n.part_query = Some(RecipeQuery::new(r.macro_.clone(), r.part.clone(), self.resolve_map(&r.props, scope), Vec::new()));
707 n.authored_keys = r.authored.clone();
708 }
709 if node.component == "Form" {
710 n.form = Some(node.id.clone());
711 }
712 n.props = props;
713 let index = self.push(n);
714 if node.component == "Button" && self.ctx.local.holds.get(&node.id).is_some_and(crate::hold::HoldTracker::active) {
716 self.add_state_own(index, "pressed");
717 }
718 if let Some(errors) = self.ctx.local.errors.get(&node.id) {
719 if !errors.messages.is_empty() {
720 let _ = errors;
721 self.add_state_own(index, "invalid");
722 }
723 }
724
725 let expand = self.ctx.expand_controls;
728 match node.component.as_str() {
730 "Image" | "Video" => self.media_ratio(index),
731 "Segmented" if crate::segmented::is_rail(&self.nodes[index as usize].props) => {
736 let tall = crate::segmented::rail_height(&self.nodes[index as usize].props, self.ctx.tab_bar);
737 self.style_default(index, &[("alignSelf", json!("flex-start")), ("flexShrink", json!(0)), ("height", json!(tall))])
738 }
739 "Segmented" if str_prop(&self.nodes[index as usize].props, "variant") == Some("bar") => {
743 self.style_default(index, &[("width", json!("100%"))])
744 }
745 "Segmented" if !bool_prop(&self.nodes[index as usize].props, "fill") && str_prop(&self.nodes[index as usize].props, "variant") != Some("bar") => {
747 self.style_default(index, &[("alignSelf", json!("flex-start"))])
748 }
749 "Button" if self.nodes[index as usize].kind == NodeKind::Container => {
753 self.style_default(index, &[("display", json!("flex")), ("flexDirection", json!("row")), ("alignItems", json!("center")), ("justifyContent", json!("center"))])
754 }
755 "VoiceWave" => self.style_default(index, &[("display", json!("flex")), ("alignItems", json!("center")), ("justifyContent", json!("center"))]),
757 "TreeGuides" => {
759 let depth = self.nodes[index as usize].props.get("depth").and_then(Value::as_f64).unwrap_or(0.0).max(0.0);
760 self.style_default(index, &[("alignSelf", json!("stretch")), ("width", json!(depth * crate::layout::TREE_GUIDE_COLUMN)), ("flexShrink", json!(0))]);
761 }
762 _ => {}
763 }
764 match node.component.as_str() {
765 "Tabs" => self.tabs(index, node, scope),
766 "Accordion" => self.accordion(index, node, scope),
767 "Carousel" => self.carousel(index, node, scope),
768 "List" => self.list(index, node, scope),
769 "Resizable" => self.resizable(index, node, scope),
770 "Table" => self.table(index, node, scope),
771 "Toast" => self.toast(index, node),
772 c if Self::is_overlay(c) => self.overlay(index, node, scope),
773 "Form" => self.form(index, node, scope),
774 "Input" | "Textarea" if expand => self.field(index),
775 "Select" if expand => self.select(index),
776 "DatePicker" | "DateRangePicker" if expand => self.date_picker(index),
777 "TimePicker" if expand => self.time_picker(index),
778 "NumberField" if expand => self.number_field(index),
779 "ChipInput" if expand => self.chip_input(index),
780 "FileUpload" if expand => self.file_upload(index),
781 "CodeBlock" if expand => self.code_block(index),
782 "Checkbox" | "Switch" if expand => self.check(index),
783 "Radio" if expand => self.radio(index),
784 "ChoiceTiles" if expand => self.choice_tiles(index),
785 "Slider" if expand => self.slider(index),
786 "SearchList" if expand => self.search_list(index),
787 "Skeleton" => self.skeleton_rows(index),
788 "Chart" => self.chart(index),
789 _ => {
790 if let Some(slots) = &node.slots {
791 for slot in slots.values() {
792 self.add(slot, Some(index), layer, scope, false);
793 }
794 }
795 self.children_of(index, node, scope, false);
796 }
797 }
798 Some(index)
799 }
800
801 fn add_state_own(&mut self, index: u32, state: &str) {
803 if let Some(q) = &mut self.nodes[index as usize].own_query {
804 if !q.states.iter().any(|s| s == state) {
805 q.states.push(state.to_string());
806 }
807 }
808 }
809
810 fn local_overrides(&self, id: &str, component: &str, props: &mut Props) {
813 let local = &self.ctx.local;
814 if let Some(v) = local.field_values.get(id) {
815 match component {
816 "DateRangePicker" => {
817 for k in ["start", "end"] {
818 if let Some(x) = v.get(k) {
819 props.insert(k.into(), x.clone());
820 }
821 }
822 }
823 _ => {
824 let key = match component {
825 "Checkbox" | "Switch" => "checked",
826 "ChipInput" => "values",
827 "FileUpload" => "files",
828 _ => "value",
829 };
830 props.insert(key.into(), v.clone());
831 }
832 }
833 }
834 if component == "Button" && local.holds.get(id).is_some_and(crate::hold::HoldTracker::active) {
836 if let Some(label) = props.get("holdingLabel").and_then(Value::as_str).filter(|l| !l.is_empty()).map(str::to_string) {
837 props.insert("label".into(), Value::String(label));
838 }
839 }
840 if component == "Toggle" {
841 if let Some(pressed) = local.pressed_toggles.get(id) {
842 props.insert("pressed".into(), Value::Bool(*pressed));
843 }
844 }
845 if component == "ChipInput" {
846 if let Some(chips) = local.chips.get(id) {
847 props.insert("values".into(), Value::Array(chips.iter().cloned().map(Value::String).collect()));
848 }
849 }
850 if component == "FileUpload" {
851 if let Some(files) = local.files.get(id) {
852 props.insert("files".into(), Value::Array(files.clone()));
853 }
854 }
855 if component == "Table" {
856 if let Some((key, dir)) = local.sort.get(id) {
857 props.insert("sort".into(), json!({"key": key, "direction": dir}));
858 }
859 if let Some(sel) = local.selected.get(id) {
860 props.insert("selected".into(), Value::Array(sel.iter().cloned().map(Value::String).collect()));
861 }
862 }
863 }
864
865 fn item_suffixes(&mut self, t: &crate::types::Template, base: &str) -> std::sync::Arc<Vec<String>> {
871 let cache_key = format!("{base}\u{0}{}", t.key.as_deref().unwrap_or(""));
872 if let Some(s) = self.suffixes.get(&cache_key) {
873 return s.clone();
874 }
875 let version = self.ctx.data_version;
876 if let Some((v, keys)) = self.ctx.local.key_cache.get(&format!("s\u{0}{cache_key}")) {
877 if *v == version {
878 let keys = keys.clone();
879 self.suffixes.insert(cache_key, keys.clone());
880 return keys;
881 }
882 }
883 let items = crate::data::get_pointer(self.ctx.data, base).and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]);
884 let out: Vec<String> = crate::list::template_item_keys(items, t.key.as_deref()).into_iter().map(|k| format!(".{}", crate::list::instance_segment(&k))).collect();
885 let out = std::sync::Arc::new(out);
886 self.ctx.local.key_cache.insert(format!("s\u{0}{cache_key}"), (version, out.clone()));
887 self.suffixes.insert(cache_key, out.clone());
888 out
889 }
890
891 pub(crate) fn enclosing_suffix(&self, node: &UiNode) -> String {
895 match self.sources.get(&node.id) {
896 Some(src) if node.id.len() > src.id.len() && node.id.starts_with(src.id.as_str()) => node.id[src.id.len()..].to_string(),
897 _ => String::new(),
898 }
899 }
900
901 pub(crate) fn children_of(&mut self, parent: u32, node: &UiNode, scope: &str, hidden: bool) -> Vec<u32> {
903 let mut out = Vec::new();
904 let layer = self.nodes[parent as usize].layer;
905 for child in &node.children {
906 out.extend(self.add(child, Some(parent), layer, scope, hidden));
907 }
908 if let Some(t) = &node.template {
909 let base = crate::data::absolute_path(&t.path, scope);
910 let count = crate::data::get_pointer(self.ctx.data, &base).and_then(Value::as_array).map(Vec::len).unwrap_or(0);
911 if let Some(tpl) = (self.ctx.template)(&t.component) {
912 let suffixes = self.item_suffixes(t, &base);
913 let enclosing = self.enclosing_suffix(node);
914 for i in 0..count {
915 if !self.take_template_item(&t.component, &tpl) {
916 break;
917 }
918 let item_scope = format!("{base}/{i}");
919 let suffix = format!("{enclosing}{}", suffixes[i]);
920 let item = self.instance(&tpl, &suffix, Some(&t.component));
921 out.extend(self.add(&item, Some(parent), layer, &item_scope, hidden));
922 }
923 }
924 }
925 out
926 }
927
928 fn take_template_item(&mut self, template: &str, tpl: &UiNode) -> bool {
936 if self.template_refused {
937 return false;
938 }
939 let nodes = subtree_nodes(tpl);
940 let message = if self.template_items >= crate::limits::MAX_TEMPLATE_ITEMS {
941 crate::limits::template_items_issue()
942 } else if self.template_nodes + nodes > crate::limits::MAX_COMPONENTS {
943 crate::limits::components_issue()
944 } else {
945 self.template_items += 1;
946 self.template_nodes += nodes;
947 return true;
948 };
949 self.template_refused = true;
950 self.issues.push(crate::types::ReduceIssue { id: template.to_string(), message });
951 false
952 }
953
954 pub(crate) fn child_keys(&mut self, node: &UiNode, scope: &str) -> std::sync::Arc<Vec<String>> {
958 if node.template.is_none() {
959 if let Some(k) = self.ctx.local.static_keys.get(&node.id) {
960 if k.len() == node.children.len() {
961 return k.clone();
962 }
963 }
964 let keys = std::sync::Arc::new(node.children.iter().map(|c| c.id.clone()).collect::<Vec<_>>());
965 self.ctx.local.static_keys.insert(node.id.clone(), keys.clone());
966 return keys;
967 }
968 let enclosing = self.enclosing_suffix(node);
969 let cache_key = format!("c\u{0}{}\u{0}{scope}", node.id);
970 if let Some((v, keys)) = self.ctx.local.key_cache.get(&cache_key) {
971 if *v == self.ctx.data_version && keys.len() >= node.children.len() {
972 return keys.clone();
973 }
974 }
975 let mut keys: Vec<String> = node.children.iter().map(|c| c.id.clone()).collect();
976 if let Some(t) = &node.template {
977 let base = crate::data::absolute_path(&t.path, scope);
978 for suffix in self.item_suffixes(t, &base).iter() {
979 keys.push(format!("{}{enclosing}{suffix}", t.component));
980 }
981 }
982 let keys = std::sync::Arc::new(keys);
983 self.ctx.local.key_cache.insert(cache_key, (self.ctx.data_version, keys.clone()));
984 keys
985 }
986
987 pub(crate) fn one_child(&mut self, parent: u32, node: &UiNode, i: usize, scope: &str, hidden: bool) -> Option<u32> {
989 let layer = self.nodes[parent as usize].layer;
990 if let Some(child) = node.children.get(i) {
991 return self.add(child, Some(parent), layer, scope, hidden);
992 }
993 let t = node.template.as_ref()?;
994 let base = crate::data::absolute_path(&t.path, scope);
995 let count = crate::data::get_pointer(self.ctx.data, &base).and_then(Value::as_array).map(Vec::len)?;
996 let idx = i.checked_sub(node.children.len())?;
997 if idx >= count {
998 return None;
999 }
1000 let tpl = (self.ctx.template)(&t.component)?;
1001 if !self.take_template_item(&t.component, &tpl) {
1002 return None;
1003 }
1004 let item_scope = format!("{base}/{idx}");
1005 let suffix = format!("{}{}", self.enclosing_suffix(node), self.item_suffixes(t, &base).get(idx).cloned().unwrap_or_else(|| format!(".{idx}")));
1006 let item = self.instance(&tpl, &suffix, Some(&t.component));
1007 self.add(&item, Some(parent), layer, &item_scope, hidden)
1008 }
1009
1010 pub(crate) fn responsive_prop(&mut self, props: &Props, key: &str) -> Option<Value> {
1012 let v = props.get(key)?;
1013 if crate::macros::is_responsive_value(v) {
1014 self.responsive = true;
1015 return crate::macros::responsive_at(v, self.ctx.breakpoint.as_deref()).cloned();
1016 }
1017 Some(v.clone())
1018 }
1019
1020 pub(crate) fn is_open(&self, id: &str, props: &Props, default: bool) -> bool {
1022 self.ctx.local.open.get(id).copied().unwrap_or_else(|| props.get("open").and_then(Value::as_bool).unwrap_or(default))
1023 }
1024
1025 pub(crate) fn layer_root(&mut self, owner: &LNode, part: &str, style: Value) -> (u32, u32) {
1027 let layer = self.next_layer;
1028 self.next_layer += 1;
1029 let mut root = self.blank(&format!("{}.{part}", owner.id), "Box", None, layer, NodeKind::Container, &owner.scope);
1030 root.part = Some(part.to_string());
1031 root.owner = Some(owner.id.clone());
1032 root.owner_component = Some(owner.component.clone());
1033 root.form = owner.form.clone();
1034 root.base_style = obj(style);
1035 root.part_query = Some(RecipeQuery::new(owner.component.clone(), part, self.ctx.recipes.native_recipe_props(&owner.component, &owner.props), vec!["open".into()]));
1036 let index = self.push(root);
1037 (layer, index)
1038 }
1039
1040 #[allow(clippy::too_many_arguments)]
1041 pub(crate) fn push_layer(&mut self, layer: u32, root: u32, owner: &LNode, placement: LayerPlacement, modal: bool, dismissible: bool, match_anchor_width: bool, scroll_body: Option<u32>) {
1042 let class = if matches!(placement, LayerPlacement::Toast { .. }) { LayerClass::Toast } else { LayerClass::Overlay };
1043 self.layers.push(LayerSpec { layer, root, kind: owner.component.clone(), owner: owner.id.clone(), placement, class, modal, dismissible, match_anchor_width, scroll_body, mirror: false });
1044 }
1045}
1046
1047pub fn row_scope_root(scope: &str) -> Option<&str> {
1050 let rest = scope.strip_prefix("/$row/")?;
1051 let mut end = "/$row/".len();
1052 for (k, part) in rest.splitn(3, '/').enumerate().take(2) {
1053 end += part.len() + usize::from(k == 0);
1054 }
1055 Some(&scope[..end])
1056}
1057
1058pub fn builtin_icon(slot: &str) -> Option<&'static str> {
1060 let g = crate::generated::catalog::BUILTIN_ICON_SLOTS.iter().position(|s| *s == slot)?;
1061 crate::generated::catalog::BUILTIN_ICON_NAMES.get(g).copied()
1062}
1063
1064pub fn build(root: &UiNode, ctx: &mut BuildContext) -> Built {
1067 let mut b = Builder { ctx, nodes: Vec::new(), layers: Vec::new(), lists: Vec::new(), responsive: false, toasts: Vec::new(), pending_toasts: Vec::new(), next_layer: 1, row_scopes: HashMap::new(), forms: HashMap::new(), sources: HashMap::new(), suffixes: HashMap::new(), flex_gaps: HashMap::new(), template_items: 0, template_nodes: subtree_nodes(root), template_refused: false, issues: Vec::new() };
1068 if b.add(root, None, 0, "", false).is_none() {
1069 let mut n = b.blank(&root.id, "Box", None, 0, NodeKind::Container, "");
1071 n.hidden = true;
1072 b.push(n);
1073 }
1074 b.flush_toasts();
1075 b.layers.sort_by_key(|l| (l.class == LayerClass::Toast, l.layer));
1078 Built { nodes: b.nodes, layers: b.layers, lists: b.lists, responsive: b.responsive, toasts: b.toasts, row_scopes: b.row_scopes, forms: b.forms, issues: b.issues }
1079}
1080
1081pub fn build_subtree(node: &UiNode, parent: &LNode, scope: &str, seed: BuildSeed, ctx: &mut BuildContext) -> Built {
1087 let mut stub = parent.clone();
1088 stub.index = 0;
1089 stub.parent = None;
1090 stub.children.clear();
1091 let layer = stub.layer;
1092 let mut b = Builder { ctx, nodes: vec![stub], layers: Vec::new(), lists: Vec::new(), responsive: false, toasts: Vec::new(), pending_toasts: Vec::new(), next_layer: u32::MAX / 2, row_scopes: seed.row_scopes, forms: seed.forms, sources: HashMap::new(), suffixes: HashMap::new(), flex_gaps: HashMap::new(), template_items: 0, template_nodes: subtree_nodes(node), template_refused: false, issues: Vec::new() };
1093 b.add(node, Some(0), layer, scope, false);
1094 b.flush_toasts();
1095 Built { nodes: b.nodes, layers: b.layers, lists: b.lists, responsive: b.responsive, toasts: b.toasts, row_scopes: b.row_scopes, forms: b.forms, issues: b.issues }
1096}
1097
1098#[cfg(test)]
1099mod tests {
1100 use super::*;
1101
1102 #[test]
1103 fn builtin_glyphs_resolve() {
1104 assert_eq!(builtin_icon("CodeBlock.copy"), Some("ui-copy"));
1105 assert_eq!(builtin_icon("Table.sortIcon.asc"), Some("ui-chevron-up"));
1106 assert_eq!(builtin_icon("Nope.x"), None);
1107 }
1108}