Skip to main content

eui_core/layout_tree/
mod.rs

1//! The LAYOUT tree: the normalized `UiNode` tree (macros already expanded)
2//! becomes a flat pre-order list of layout nodes the engine and the painters
3//! work on. Here the core adds what painters must not invent: the BIND pass
4//! (bindings, calls and `$string.<id>` copy resolved in props, styles and
5//! recipe props; a node whose `visible` resolves falsy is dropped with its
6//! subtree), template children instantiated per item (ids `<template>.<key>`
7//! with the template `key`, else `<template>.<i>`), natives with structure
8//! of their own get synthetic PART nodes (ids `<owner>.<part>`, recipes keyed
9//! on the owner's component so a theme styles them), overlay natives and
10//! every popup (Select, the pickers, menus and submenus, tooltips, hover
11//! cards, toasts) put their content into LAYERS with their own roots, and
12//! extension natives arrive as `Extension` leaves.
13//!
14//! The builder numbers nodes in pre-order; the surface maps them onto
15//! STABLE SLOTS by id afterwards (`surface::reconcile`), so a re-windowed
16//! list or an opened overlay keeps every other node's index.
17
18mod 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/// One layout node. `style` keeps tokens UNRESOLVED and conditions NESTED;
49/// the surface resolves them per theme/mode and flattens per pass.
50#[derive(Debug, Clone, PartialEq)]
51pub struct LNode {
52    /// The SLOT (stable across rebuilds by id) once the surface reconciled;
53    /// the pre-order position inside a fresh `Built`.
54    pub index: u32,
55    pub id: String,
56    /// The native kind painted (`Box`, `Text`, `Button`, …, `Extension`).
57    pub component: String,
58    /// The synthetic part of a native (`Tabs/tab`, `Input/label`).
59    pub part: Option<String>,
60    /// The id of the native that owns the part.
61    pub owner: Option<String>,
62    pub owner_component: Option<String>,
63    /// For `Extension` nodes: the extension's catalog id and native kind.
64    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    /// Props with bindings, calls and `$string.<id>` resolved.
72    pub props: Props,
73    /// The structural style (author's + template's), bindings resolved,
74    /// token refs NOT resolved, conditions nested.
75    pub base_style: Props,
76    /// The keys of `base_style` a builder only DEFAULTED (`style_default`):
77    /// the native's own root recipe wins over them (an author's key wins
78    /// over the recipe).
79    pub default_keys: Vec<String>,
80    /// The native's own root recipe (Text/root for its variant).
81    pub own_query: Option<RecipeQuery>,
82    /// The macro or native PART recipe (Badge/label, Tabs/tab).
83    pub part_query: Option<RecipeQuery>,
84    /// VAPP-163: the `base_style` keys the author wrote ON the macro node
85    /// (`recipe.authored`): they win over the part recipe.
86    pub authored_keys: Vec<String>,
87    pub hidden: bool,
88    pub lines: Option<u32>,
89    pub pressable: bool,
90    /// The data scope (template item pointer) bindings resolved against.
91    pub scope: String,
92    /// Where the node's SOURCE `UiNode` lives when its id is an instance id
93    /// (a template item's descendants, a Table slot cell's controls carry
94    /// `<sourceId><suffix>`). `None` = the id itself names a node of the
95    /// surface's tree (or the node is a synthetic part).
96    pub source: Option<SourceRef>,
97    /// The `on` map of the source node (events route through the owner).
98    pub on: Option<IndexMap<String, Value>>,
99    pub accessibility: Option<Value>,
100    /// The overlay node this node opens (a trigger slot's root).
101    pub trigger_for: Option<String>,
102    /// The enclosing Form's id (fields and submit buttons).
103    pub form: Option<String>,
104    /// A live region: `polite | assertive` (Text `live`, Toast, Form errors).
105    pub live: Option<String>,
106}
107
108/// The source of an instance node: the source node's id and the template
109/// component whose reduced tree holds it (`None` = the surface's tree).
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct SourceRef {
112    pub id: String,
113    pub template: Option<String>,
114}
115
116/// How an overlay layer is placed.
117#[derive(Debug, Clone, PartialEq)]
118pub enum LayerPlacement {
119    /// Centred in the viewport (Dialog).
120    Centered,
121    /// Pinned to one viewport edge (Drawer).
122    Edge(OverlaySide),
123    /// Against the anchor node's frame (Popover, Tooltip, menus, pickers).
124    Anchored { anchor: u32, side: OverlaySide, align: OverlayAlign },
125    /// Against a point (a context Menu opened at the pointer).
126    AtPoint { x: f32, y: f32 },
127    /// The toast stack (bottom-centre on phones, bottom-end from `md`),
128    /// `order` 0 = nearest the edge.
129    Toast { order: u32 },
130}
131
132/// Which band a layer stacks in: base < overlay < toast.
133#[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    /// Dialog/Drawer: a scrim under it, the focus trapped inside.
149    pub modal: bool,
150    /// Escape / a scrim press / a drag closes it.
151    pub dismissible: bool,
152    /// The popup is at least as wide as its anchor (Select, pickers).
153    pub match_anchor_width: bool,
154    /// The layer's body that scrolls when the content is taller than the
155    /// viewport (Dialog/Drawer `body`, a popup list).
156    pub scroll_body: Option<u32>,
157    /// The side is LOGICAL (a submenu opens at the inline end): right in
158    /// LTR, left in RTL.
159    pub mirror: bool,
160}
161
162/// A windowed list's state for one build.
163#[derive(Debug, Clone, PartialEq)]
164pub struct ListSpec {
165    pub node: u32,
166    /// The scroll key (the List's or the Table's id).
167    pub id: String,
168    pub keys: std::sync::Arc<Vec<String>>,
169    pub range: VisibleRange,
170    pub offsets: std::sync::Arc<Vec<f32>>,
171    /// The content extent on the list's axis (height, or width when
172    /// `horizontal`).
173    pub content_height: f32,
174    pub windowed: bool,
175    /// Round 2: a horizontal List windows on x.
176    pub horizontal: bool,
177    /// The gap the offsets use (a `divided` list adds the hairline).
178    pub gap: f32,
179    /// The DATA index of each row position (`scrollToIndex` takes data
180    /// indices): `None` = position i is item i (minus static children).
181    pub data_index: Option<std::sync::Arc<Vec<Option<usize>>>>,
182    /// Row positions of the section headers (ascending).
183    pub headers: std::sync::Arc<Vec<usize>>,
184    /// `stickyHeaders`: the header pinned at the scroll offset.
185    pub sticky: bool,
186    /// Static children before the template items (List).
187    pub static_count: usize,
188}
189
190/// Round 2 (§5): where a windowed list's viewport comes from.
191#[derive(Debug, Clone, PartialEq)]
192pub enum ListViewSource {
193    /// The list scrolls itself (bounded and taller content).
194    Own,
195    /// Its nearest scrolling ancestor `id`; `rel` = the list's content
196    /// start inside that ancestor's content.
197    Ancestor { id: String, rel: f32 },
198    /// The host viewport (`Surface::set_surface_scroll`); `rel` = the
199    /// list's content start in the surface.
200    Host { rel: f32 },
201}
202
203/// A list's viewport on its axis, recorded after each pass.
204#[derive(Debug, Clone, PartialEq)]
205pub struct ListView {
206    pub source: ListViewSource,
207    pub viewport: f32,
208}
209
210/// A form field's validation state after a submit: its failed messages.
211#[derive(Debug, Clone, Default, PartialEq)]
212pub struct FieldErrors {
213    pub name: String,
214    pub messages: Vec<String>,
215}
216
217/// Local UI state the core owns (never sent to the producer unless bound).
218#[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    /// VAPP-162: Button `hold` gestures per button id (`Surface::hold`).
226    pub holds: HashMap<String, crate::hold::HoldTracker>,
227    pub lists: HashMap<String, ListWindow>,
228    /// Any scroll container's offset by node id (x, y).
229    pub scroll: HashMap<String, (f32, f32)>,
230    /// A searchable Select's query / a ChipInput's typed text.
231    pub query: HashMap<String, String>,
232    /// A calendar's visible month (year, month 1–12).
233    pub month: HashMap<String, (i32, u32)>,
234    /// A DateRangePicker's first pick, waiting for the second.
235    pub range_anchor: HashMap<String, String>,
236    /// The open submenu of a menu (item index).
237    pub submenu: HashMap<String, usize>,
238    /// EXP-1259: the highlighted row of a SearchList (by its id) or of a
239    /// searchable submenu (by its `search` part's id), a position in the
240    /// FILTERED rows.
241    pub active: HashMap<String, usize>,
242    /// Where a context Menu was opened (surface coordinates).
243    pub context_point: HashMap<String, (f32, f32)>,
244    /// The host's latest value of a field (text inputs are host-owned).
245    pub field_values: HashMap<String, Value>,
246    /// Failed checks per field id, set by a refused submit.
247    pub errors: HashMap<String, FieldErrors>,
248    /// Unbound Table sort and selection.
249    pub sort: HashMap<String, (String, String)>,
250    pub selected: HashMap<String, Vec<String>>,
251    /// Unbound ChipInput values and FileUpload files.
252    pub chips: HashMap<String, Vec<String>>,
253    pub files: HashMap<String, Vec<Value>>,
254    /// CodeBlocks whose copy button shows `copied`.
255    pub copied: HashMap<String, bool>,
256    /// The child keys of a container with STATIC children (per reduce).
257    pub static_keys: HashMap<String, std::sync::Arc<Vec<String>>>,
258    /// Round 2: each windowed list's viewport (own, ancestor or host).
259    pub list_views: HashMap<String, ListView>,
260    /// The host's scroll offset of the whole surface (x, y); `None` = the
261    /// host never set one (a page-scrolled list then takes the offset the
262    /// host gives the list itself, `Surface::scroll`).
263    pub surface_scroll: Option<(f32, f32)>,
264    /// Resizable sizes moved by a drag or a key (unbound groups, and the
265    /// live sizes during a drag).
266    pub sizes: HashMap<String, Vec<f64>>,
267    /// Resizable drags in progress: handle id → the sizes at the START.
268    pub drags: HashMap<String, Vec<f64>>,
269    /// The last pass placed a `position: sticky` node (a scroll lays out again).
270    pub sticky_any: bool,
271    /// Template item keys and child keys per (array, key) / (node, scope),
272    /// valid while the data model's version holds: a scroll step over a
273    /// 100,000-item list never re-keys it.
274    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    /// Reduce a template component by id into a normalized subtree.
283    pub template: &'a dyn Fn(&str) -> Option<UiNode>,
284    pub viewport_height: f32,
285    /// Round 2: the viewport width (horizontal windows).
286    pub viewport_width: f32,
287    /// `$control.hairline` (Resizable handles, list dividers) and
288    /// `$control.row` (the extent of an unmeasured list item).
289    pub hairline: f32,
290    pub row_extent: f32,
291    /// EXP-1259: `$control.buttonSm`, a menu row's height (a searchable
292    /// submenu's list window).
293    pub menu_row: f32,
294    /// VAPP-162: `$control.tabBar`, the item height of a vertical `bar`
295    /// Segmented (the navigation rail).
296    pub tab_bar: f32,
297    /// EXP-1548: `$control.checkbox`, the width of a Table's selection
298    /// column (part of the table's minimum width).
299    pub checkbox: f32,
300    /// The theme's default gap for `List` items per `gap` enum, in px.
301    pub gap_px: &'a dyn Fn(&str) -> f32,
302    /// Expand form controls into label/field/description parts (a themed
303    /// surface); off = geometry mode, every native is ONE measured leaf.
304    pub expand_controls: bool,
305    /// The surface's built-in string table.
306    pub strings: &'a StringTable,
307    /// The active breakpoint (`None` = base) for responsive native props.
308    pub breakpoint: Option<String>,
309    /// The surface locale (week start).
310    pub locale: &'a str,
311    /// The surface is at least `md` wide (the toast stack sits bottom-end).
312    pub wide: bool,
313    /// Today as `yyyy-mm-dd` (the host's clock; calendars open on it).
314    pub today: Option<String>,
315    /// Round 2: the surface formatter (Table cells, NumberField, chart
316    /// ticks, pickers, calendar names, the format functions).
317    pub formatter: &'a dyn crate::format::Formatter,
318    /// The clock (epoch ms) relative times read.
319    pub now: f64,
320    /// Bumped on every write to the data model (the key caches' version).
321    pub data_version: u64,
322}
323
324pub struct Built {
325    pub nodes: Vec<LNode>,
326    pub layers: Vec<LayerSpec>,
327    pub lists: Vec<ListSpec>,
328    /// A native read a responsive prop: a breakpoint change rebuilds.
329    pub responsive: bool,
330    /// Text whose live region announces when it changes: id → (text, live).
331    pub toasts: Vec<ToastSpec>,
332    /// Literal Table rows as data scopes (`/$row/<table>/<i>` → the row):
333    /// events resolve against them after the build.
334    pub row_scopes: HashMap<String, Value>,
335    /// Form id → (disabled, busy), seeded into a later subtree rebuild.
336    pub forms: HashMap<String, (bool, bool)>,
337    /// VAPP-103: what the build refused (template items past the limit).
338    pub issues: Vec<crate::types::ReduceIssue>,
339}
340
341/// What a SUBTREE rebuild inherits from the full build: the enclosing
342/// Forms' flags and the literal Table rows.
343#[derive(Debug, Clone, Default)]
344pub struct BuildSeed {
345    pub row_scopes: HashMap<String, Value>,
346    pub forms: HashMap<String, (bool, bool)>,
347}
348
349/// An open Toast the host times (`duration` 0 = sticky).
350#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
351pub struct ToastSpec {
352    pub id: String,
353    pub duration_ms: f64,
354    #[serde(rename = "type")]
355    pub kind: String,
356}
357
358pub(crate) struct Builder<'a, 'b> {
359    pub(crate) ctx: &'b mut BuildContext<'a>,
360    pub(crate) nodes: Vec<LNode>,
361    pub(crate) layers: Vec<LayerSpec>,
362    pub(crate) lists: Vec<ListSpec>,
363    pub(crate) responsive: bool,
364    pub(crate) toasts: Vec<ToastSpec>,
365    /// Toast nodes waiting for the toast band (built after every overlay).
366    pub(crate) pending_toasts: Vec<(u32, UiNode)>,
367    /// The next layer number (layers nest: a submenu opens inside a menu).
368    pub(crate) next_layer: u32,
369    /// Literal Table rows as data scopes (`/$row/<table>/<i>` → the row).
370    pub(crate) row_scopes: HashMap<String, Value>,
371    /// Form id → (disabled, busy), for the fields and buttons inside.
372    pub(crate) forms: HashMap<String, (bool, bool)>,
373    /// Instance id → its source (filled by [`Builder::instance`]).
374    pub(crate) sources: HashMap<String, SourceRef>,
375    /// Template item suffixes per array (and key) for this build.
376    pub(crate) suffixes: HashMap<String, std::sync::Arc<Vec<String>>>,
377    /// The flex gap of each windowed container (its spacers subtract it).
378    pub(crate) flex_gaps: HashMap<u32, f32>,
379    /// VAPP-103: template items this build instantiated (`maxTemplateItems`).
380    pub(crate) template_items: usize,
381    /// VAPP-103 rfix: the nodes this build holds (`maxComponents`): the
382    /// reduced tree's, plus every instantiated item's template subtree (a
383    /// 500-node row × 1000 items never builds).
384    pub(crate) template_nodes: usize,
385    /// An item was refused: every later one is too (the rest).
386    pub(crate) template_refused: bool,
387    /// What the build refused (template items past the limit).
388    pub(crate) issues: Vec<crate::types::ReduceIssue>,
389}
390
391/// The nodes of a template subtree (children and slots; iterative).
392pub(crate) fn subtree_nodes(root: &UiNode) -> usize {
393    let mut count = 0;
394    let mut stack = vec![root];
395    while let Some(n) = stack.pop() {
396        count += 1;
397        stack.extend(n.children.iter());
398        stack.extend(n.slots.iter().flat_map(|s| s.values()));
399    }
400    count
401}
402
403pub(crate) fn obj(v: Value) -> Props {
404    match v {
405        Value::Object(m) => m,
406        _ => Map::new(),
407    }
408}
409
410fn with_suffix(node: &UiNode, suffix: &str, template: Option<&str>, sources: &mut HashMap<String, SourceRef>) -> UiNode {
411    let mut out = node.clone();
412    out.id = format!("{}{suffix}", node.id);
413    // An id that is already an instance keeps ITS source (a Table slot
414    // inside a template row); an original id is its own source.
415    let source = sources.get(&node.id).cloned().unwrap_or_else(|| SourceRef { id: node.id.clone(), template: template.map(str::to_string) });
416    sources.insert(out.id.clone(), source);
417    out.children = node.children.iter().map(|c| with_suffix(c, suffix, template, sources)).collect();
418    if let Some(slots) = &node.slots {
419        out.slots = Some(slots.iter().map(|(k, v)| (k.clone(), with_suffix(v, suffix, template, sources))).collect());
420    }
421    out
422}
423
424/// The overlay natives whose content lives in a layer.
425pub const OVERLAYS: &[&str] = &["Dialog", "Drawer", "Popover", "Tooltip", "Menu"];
426
427/// The form fields a Form collects (when they carry a `name`).
428pub const FORM_FIELDS: &[&str] =
429    &["Input", "Textarea", "NumberField", "Checkbox", "Radio", "ChoiceTiles", "Switch", "Select", "ChipInput", "DatePicker", "DateRangePicker", "TimePicker", "FileUpload", "Slider"];
430
431/// Text props (`string`/`markdown` schemas) bound to a number or a boolean
432/// show its [`crate::format::display_string`] (`412`, `true`): painters read
433/// strings.
434pub(crate) fn display_text_props(def: &crate::types::ComponentDef, props: &mut Props) {
435    for (k, v) in props.iter_mut() {
436        if matches!(v, Value::Number(_) | Value::Bool(_)) && def.props.get(k).is_some_and(|s| s.type_ == "string" || s.type_ == "markdown") {
437            *v = Value::String(crate::format::display_string(v));
438        }
439    }
440}
441
442pub(crate) fn str_prop<'p>(props: &'p Props, key: &str) -> Option<&'p str> {
443    props.get(key).and_then(Value::as_str)
444}
445
446pub(crate) fn bool_prop(props: &Props, key: &str) -> bool {
447    props.get(key).and_then(Value::as_bool).unwrap_or(false)
448}
449
450pub(crate) fn js(v: &Value) -> String {
451    crate::json::to_js_string(v)
452}
453
454impl<'a, 'b> Builder<'a, 'b> {
455    pub(crate) fn resolve_ctx<'s>(&'s self, scope: &'s str) -> ResolveContext<'s> {
456        let ctx = ResolveContext::new(self.ctx.data, scope).with_strings(self.ctx.strings).with_formatter(self.ctx.formatter).with_now(self.ctx.now);
457        match row_scope_root(scope).and_then(|root| self.row_scopes.get_key_value(root)) {
458            Some((root, row)) => ctx.with_overlay(root, row),
459            None => ctx,
460        }
461    }
462
463    pub(crate) fn resolve(&self, value: &Value, scope: &str) -> Option<Value> {
464        resolve_value(value, &self.resolve_ctx(scope))
465    }
466
467    pub(crate) fn resolve_map(&self, map: &Props, scope: &str) -> Props {
468        obj(resolve_value(&Value::Object(map.clone()), &self.resolve_ctx(scope)).unwrap_or(Value::Null))
469    }
470
471    /// A built-in string by id.
472    pub(crate) fn string(&self, id: &str) -> String {
473        self.ctx.strings.get(id).cloned().unwrap_or_else(|| id.to_string())
474    }
475
476    /// A built-in string with its `{name}` placeholders filled
477    /// (`strings::format_string`), e.g. `removeItem` = "Remove {name}".
478    pub(crate) fn string_with(&self, id: &str, params: &[(&str, &str)]) -> String {
479        let params: Map<String, Value> = params.iter().map(|(k, v)| (k.to_string(), Value::String(v.to_string()))).collect();
480        crate::strings::format_string(&self.string(id), &params)
481    }
482
483    /// An INSTANCE of `node` (every id + `suffix`), its sources recorded:
484    /// `template` = the template component the original ids belong to
485    /// (`None` = the surface's tree).
486    pub(crate) fn instance(&mut self, node: &UiNode, suffix: &str, template: Option<&str>) -> UiNode {
487        with_suffix(node, suffix, template, &mut self.sources)
488    }
489
490    pub(crate) fn push(&mut self, mut node: LNode) -> u32 {
491        let index = self.nodes.len() as u32;
492        node.index = index;
493        if let Some(p) = node.parent {
494            self.nodes[p as usize].children.push(index);
495        }
496        self.nodes.push(node);
497        index
498    }
499
500    pub(crate) fn blank(&self, id: &str, component: &str, parent: Option<u32>, layer: u32, kind: NodeKind, scope: &str) -> LNode {
501        let (depth, hidden, form) = parent
502            .map(|p| {
503                let pn = &self.nodes[p as usize];
504                (pn.depth + 1, pn.hidden, pn.form.clone())
505            })
506            .unwrap_or((0, false, None));
507        LNode {
508            index: 0,
509            id: id.to_string(),
510            component: component.to_string(),
511            part: None,
512            owner: None,
513            owner_component: None,
514            catalog_id: None,
515            extension_kind: None,
516            depth,
517            parent,
518            children: Vec::new(),
519            layer,
520            kind,
521            props: Map::new(),
522            base_style: Map::new(),
523            default_keys: Vec::new(),
524            own_query: None,
525            part_query: None,
526            authored_keys: Vec::new(),
527            hidden,
528            lines: None,
529            pressable: false,
530            scope: scope.to_string(),
531            source: None,
532            on: None,
533            accessibility: None,
534            trigger_for: None,
535            form,
536            live: None,
537        }
538    }
539
540    /// A synthetic part of `owner` under `parent`, id `<owner>.<part><suffix>`,
541    /// with the owner's recipe for that part.
542    #[allow(clippy::too_many_arguments)]
543    pub(crate) fn part_in(&mut self, parent: u32, owner: &LNode, part: &str, component: &str, kind: NodeKind, style: Value, props: Value, suffix: &str) -> u32 {
544        let id = format!("{}.{part}{suffix}", owner.id);
545        let layer = self.nodes[parent as usize].layer;
546        let mut n = self.blank(&id, component, Some(parent), layer, kind, &owner.scope);
547        n.part = Some(part.to_string());
548        n.owner = Some(owner.id.clone());
549        n.owner_component = Some(owner.component.clone());
550        n.base_style = obj(style);
551        n.props = obj(props);
552        let query_props = self.ctx.recipes.native_recipe_props(&owner.component, &owner.props);
553        n.part_query = Some(RecipeQuery::new(owner.component.clone(), part, query_props, Vec::new()));
554        if let Some(l) = n.props.get("lines").and_then(Value::as_u64) {
555            n.lines = Some(l as u32);
556        }
557        self.push(n)
558    }
559
560    /// [`Self::part_in`] directly under the owner.
561    pub(crate) fn part(&mut self, owner: &LNode, part: &str, component: &str, kind: NodeKind, style: Value, props: Value) -> u32 {
562        self.part_in(owner.index, owner, part, component, kind, style, props, "")
563    }
564
565    pub(crate) fn text_part(&mut self, parent: u32, owner: &LNode, part: &str, text: &str, variant: &str, suffix: &str) -> u32 {
566        self.part_in(parent, owner, part, "Text", NodeKind::Leaf, json!({}), json!({"text": text, "variant": variant}), suffix)
567    }
568
569    /// An icon leaf part with the builtin glyph of `<Owner>.<slot>`.
570    pub(crate) fn icon_part(&mut self, parent: u32, owner: &LNode, part: &str, glyph_slot: &str, suffix: &str) -> u32 {
571        let name = builtin_icon(glyph_slot).unwrap_or("ui-icon-placeholder");
572        self.part_in(parent, owner, part, "Icon", NodeKind::Leaf, json!({"flexShrink": 0}), json!({"name": name, "size": "sm"}), suffix)
573    }
574
575    /// Round 2: an accessibility key the author did not set (a built-in
576    /// label such as `$string.dialog` on a title-less Dialog).
577    pub(crate) fn default_a11y(&mut self, index: u32, key: &str, value: Value) {
578        let a = self.nodes[index as usize].accessibility.get_or_insert_with(|| json!({}));
579        if let Some(m) = a.as_object_mut() {
580            m.entry(key.to_string()).or_insert(value);
581        }
582    }
583
584    /// Add a state to a node's part query (`selected`, `open`, `checked`…).
585    pub(crate) fn add_state(&mut self, index: u32, state: &str) {
586        if let Some(q) = &mut self.nodes[index as usize].part_query {
587            if !q.states.iter().any(|s| s == state) {
588                q.states.push(state.to_string());
589            }
590        }
591    }
592
593    /// Set a recipe prop on a node's part query (a part-level discriminator).
594    pub(crate) fn query_prop(&mut self, index: u32, key: &str, value: Value) {
595        if let Some(q) = &mut self.nodes[index as usize].part_query {
596            q.props.insert(key.to_string(), value);
597        }
598    }
599
600    pub(crate) fn style_default(&mut self, index: u32, entries: &[(&str, Value)]) {
601        let n = &mut self.nodes[index as usize];
602        for (k, v) in entries {
603            if !n.base_style.contains_key(*k) {
604                n.base_style.insert(k.to_string(), v.clone());
605                n.default_keys.push(k.to_string());
606            }
607        }
608    }
609
610    /// Image / Video (round 2 §7): the box takes `aspectRatio` (a Video
611    /// always, an Image without a `height`; default `mediaAspectRatio`), so
612    /// height = width / ratio before and after the media loads.
613    fn media_ratio(&mut self, index: u32) {
614        let n = &self.nodes[index as usize];
615        let given = n.props.get("aspectRatio").and_then(Value::as_f64).filter(|r| r.is_finite() && *r > 0.0);
616        let has_height = n.props.get("height").is_some_and(|v| !v.is_null()) || n.base_style.contains_key("height");
617        let ratio = given.or_else(|| (n.component == "Video" || !has_height).then_some(crate::layout::MEDIA_ASPECT_RATIO));
618        if let Some(r) = ratio {
619            self.style_default(index, &[("aspectRatio", json!(r))]);
620        }
621    }
622
623    /// EXP-1586: THE ZoomableImage box (catalog/style.json `zoomableImage`):
624    /// as wide as its parent; without a style `height` it takes
625    /// [`zoomable_aspect_ratio`].
626    fn zoomable_box(&mut self, index: u32) {
627        let n = &self.nodes[index as usize];
628        let has_height = n.base_style.contains_key("height");
629        let ratio = zoomable_aspect_ratio(&n.props);
630        self.style_default(index, &[("width", json!("100%"))]);
631        if !has_height {
632            self.style_default(index, &[("aspectRatio", json!(ratio))]);
633        }
634    }
635
636    /// EXP-1604: THE Motion box (eui-motion README "Painting a Motion" §4):
637    /// unstyled, the composition's px size, shrinking to the available
638    /// width with its aspect kept (`width: W`, `maxWidth: 100%`,
639    /// `aspectRatio: W/H`). A style `width` / `height` wins; a `src`
640    /// animation (size unknown until fetched) gets no default.
641    fn motion_box(&mut self, index: u32) {
642        let n = &self.nodes[index as usize];
643        let Some((w, h)) = motion_size(&n.props) else { return };
644        let (has_w, has_h) = (n.base_style.contains_key("width"), n.base_style.contains_key("height"));
645        if !has_w && !has_h {
646            self.style_default(index, &[("width", json!(w)), ("maxWidth", json!("100%"))]);
647        }
648        if !(has_w && has_h) {
649            self.style_default(index, &[("aspectRatio", json!(w / h))]);
650        }
651    }
652
653    pub(crate) fn is_overlay(component: &str) -> bool {
654        OVERLAYS.contains(&component)
655    }
656
657    /// Is a node visible under the data model (`visible` absent = yes)?
658    fn visible(&self, node: &UiNode, scope: &str) -> bool {
659        crate::data::is_visible(node.visible.as_ref(), &self.resolve_ctx(scope))
660    }
661
662    /// Add `node` under `parent`; `None` when its `visible` is falsy.
663    pub(crate) fn add(&mut self, node: &UiNode, parent: Option<u32>, layer: u32, scope: &str, force_hidden: bool) -> Option<u32> {
664        crate::deep(|| self.add_node(node, parent, layer, scope, force_hidden))
665    }
666
667    fn add_node(&mut self, node: &UiNode, parent: Option<u32>, layer: u32, scope: &str, force_hidden: bool) -> Option<u32> {
668        if !self.visible(node, scope) {
669            return None;
670        }
671        let view = self.ctx.view;
672        let def = view.component(&node.component);
673        // Round 2: props resolve ALONG THEIR SCHEMA (a literal Table `rows`
674        // holding `{path}` is data), then a bound number or boolean in a
675        // text prop shows as its display string.
676        let mut props = crate::data::resolve_node_props(def, &node.props, &self.resolve_ctx(scope), &view.defs);
677        if let Some(def) = def {
678            display_text_props(def, &mut props);
679        }
680        self.local_overrides(&node.id, &node.component, &mut props);
681        // Inside a disabled Form every field (and button) is inert; inside a
682        // busy one the submit buttons show loading.
683        let form = parent.and_then(|p| self.nodes[p as usize].form.clone());
684        if let Some((disabled, busy)) = form.as_ref().and_then(|f| self.forms.get(f)).copied() {
685            if disabled && (FORM_FIELDS.contains(&node.component.as_str()) || node.component == "Button") {
686                props.insert("disabled".into(), Value::Bool(true));
687            }
688            if busy && node.component == "Button" && bool_prop(&props, "submit") {
689                props.insert("loading".into(), Value::Bool(true));
690            }
691        }
692        let ext = view.extension_of(&node.component).map(str::to_string);
693        let children_rule = def.map(|d| d.children.as_str()).unwrap_or("none");
694        let has_children = !node.children.is_empty() || node.template.is_some();
695        let component = if ext.is_some() { "Extension".to_string() } else { node.component.clone() };
696        let kind = if ext.is_some() {
697            if has_children {
698                NodeKind::Container
699            } else {
700                NodeKind::Leaf
701            }
702        } else {
703            match (node.component.as_str(), children_rule) {
704                ("Box", _) => NodeKind::Container,
705                (_, "none") => NodeKind::Leaf,
706                ("Button", "one") => {
707                    if has_children {
708                        NodeKind::Container
709                    } else {
710                        NodeKind::Leaf
711                    }
712                }
713                _ => NodeKind::Container,
714            }
715        };
716        let mut n = self.blank(&node.id, &component, parent, layer, kind, scope);
717        n.hidden |= force_hidden;
718        if let Some(e) = ext {
719            n.catalog_id = Some(e);
720            n.extension_kind = Some(node.component.clone());
721        }
722        // The author's `style` (top level) wins over a `style` PROP; both may
723        // carry bound values after expansion (resolved here).
724        let mut base: Props = props.get("style").and_then(Value::as_object).cloned().unwrap_or_default();
725        if let Some(s) = &node.style {
726            for (k, v) in self.resolve_map(s, scope) {
727                base.insert(k, v);
728            }
729        }
730        n.base_style = base;
731        n.lines = props.get("lines").and_then(Value::as_u64).map(|l| l as u32);
732        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");
733        n.on = node.on.clone();
734        n.source = self.sources.get(&node.id).cloned();
735        n.accessibility = node.accessibility.as_ref().and_then(|a| self.resolve(a, scope));
736        n.live = str_prop(&props, "live").filter(|l| *l != "off").map(str::to_string);
737        n.own_query = Some(RecipeQuery::new(node.component.clone(), "root", self.ctx.recipes.native_recipe_props(&node.component, &props), Vec::new()));
738        if let Some(r) = &node.recipe {
739            n.part_query = Some(RecipeQuery::new(r.macro_.clone(), r.part.clone(), self.resolve_map(&r.props, scope), Vec::new()));
740            n.authored_keys = r.authored.clone();
741        }
742        if node.component == "Form" {
743            n.form = Some(node.id.clone());
744        }
745        n.props = props;
746        let index = self.push(n);
747        // VAPP-162: a held `hold` Button carries `pressed` (the core's state).
748        if node.component == "Button" && self.ctx.local.holds.get(&node.id).is_some_and(crate::hold::HoldTracker::active) {
749            self.add_state_own(index, "pressed");
750        }
751        if let Some(errors) = self.ctx.local.errors.get(&node.id) {
752            if !errors.messages.is_empty() {
753                let _ = errors;
754                self.add_state_own(index, "invalid");
755            }
756        }
757
758        // The component-specific structure; everything else: slots first
759        // (pre-order like the reference `preorder`), then children.
760        let expand = self.ctx.expand_controls;
761        // Round 2 §7: explicit sizes instead of browser defaults.
762        match node.component.as_str() {
763            "Image" | "Video" => self.media_ratio(index),
764            "ZoomableImage" => self.zoomable_box(index),
765            "Motion" => self.motion_box(index),
766            // VAPP-162: a vertical `bar` (THE navigation rail) is a column of
767            // fixed items: as wide as its root recipe (72), `items × tabBar`
768            // tall, never stretched across its parent (full height is the
769            // author's style). Painters stack the items top to bottom.
770            "Segmented" if crate::segmented::is_rail(&self.nodes[index as usize].props) => {
771                let tall = crate::segmented::rail_height(&self.nodes[index as usize].props, self.ctx.tab_bar);
772                self.style_default(index, &[("alignSelf", json!("flex-start")), ("flexShrink", json!(0)), ("height", json!(tall))])
773            }
774            // VAPP-164: a horizontal `bar` is `width: 100%` (base-css.ts), so
775            // it fills its parent even in an `align: start` column, with or
776            // without icons.
777            "Segmented" if str_prop(&self.nodes[index as usize].props, "variant") == Some("bar") => {
778                self.style_default(index, &[("width", json!("100%"))])
779            }
780            // A Segmented is content-sized unless `fill` (a `bar` always fills).
781            "Segmented" if !bool_prop(&self.nodes[index as usize].props, "fill") && str_prop(&self.nodes[index as usize].props, "variant") != Some("bar") => {
782                self.style_default(index, &[("alignSelf", json!("flex-start"))])
783            }
784            // VAPP-162: a Button's one custom child sits centred in its box
785            // (the web's inline-flex button; CallSurface's round 56 px
786            // buttons hold a 24 px Icon).
787            "Button" if self.nodes[index as usize].kind == NodeKind::Container => {
788                self.style_default(index, &[("display", json!("flex")), ("flexDirection", json!("row")), ("alignItems", json!("center")), ("justifyContent", json!("center"))])
789            }
790            // NEW-77: the one child sits centred in the wave box at its own size.
791            "VoiceWave" => self.style_default(index, &[("display", json!("flex")), ("alignItems", json!("center")), ("justifyContent", json!("center"))]),
792            // TreeGuides: depth × `treeGuideColumn` wide, stretched to its row.
793            "TreeGuides" => {
794                let depth = self.nodes[index as usize].props.get("depth").and_then(Value::as_f64).unwrap_or(0.0).max(0.0);
795                self.style_default(index, &[("alignSelf", json!("stretch")), ("width", json!(depth * crate::layout::TREE_GUIDE_COLUMN)), ("flexShrink", json!(0))]);
796            }
797            _ => {}
798        }
799        match node.component.as_str() {
800            "Tabs" => self.tabs(index, node, scope),
801            "Accordion" => self.accordion(index, node, scope),
802            "Carousel" => self.carousel(index, node, scope),
803            "List" => self.list(index, node, scope),
804            "Resizable" => self.resizable(index, node, scope),
805            "Table" => self.table(index, node, scope),
806            "Toast" => self.toast(index, node),
807            c if Self::is_overlay(c) => self.overlay(index, node, scope),
808            "Form" => self.form(index, node, scope),
809            "Input" | "Textarea" if expand => self.field(index),
810            "Select" if expand => self.select(index),
811            "DatePicker" | "DateRangePicker" if expand => self.date_picker(index),
812            "TimePicker" if expand => self.time_picker(index),
813            "NumberField" if expand => self.number_field(index),
814            "ChipInput" if expand => self.chip_input(index),
815            "FileUpload" if expand => self.file_upload(index),
816            "CodeBlock" if expand => self.code_block(index),
817            "Checkbox" | "Switch" if expand => self.check(index),
818            "Radio" if expand => self.radio(index),
819            "ChoiceTiles" if expand => self.choice_tiles(index),
820            "Slider" if expand => self.slider(index),
821            "SearchList" if expand => self.search_list(index),
822            "Skeleton" => self.skeleton_rows(index),
823            "Chart" => self.chart(index),
824            _ => {
825                if let Some(slots) = &node.slots {
826                    for slot in slots.values() {
827                        self.add(slot, Some(index), layer, scope, false);
828                    }
829                }
830                self.children_of(index, node, scope, false);
831            }
832        }
833        Some(index)
834    }
835
836    /// A state on a node's OWN recipe query (an invalid field's root).
837    fn add_state_own(&mut self, index: u32, state: &str) {
838        if let Some(q) = &mut self.nodes[index as usize].own_query {
839            if !q.states.iter().any(|s| s == state) {
840                q.states.push(state.to_string());
841            }
842        }
843    }
844
845    /// Local UI state that overrides an UNBOUND prop for this build (the
846    /// host's latest field value, unbound chips/files/sort/selection).
847    fn local_overrides(&self, id: &str, component: &str, props: &mut Props) {
848        let local = &self.ctx.local;
849        if let Some(v) = local.field_values.get(id) {
850            match component {
851                "DateRangePicker" => {
852                    for k in ["start", "end"] {
853                        if let Some(x) = v.get(k) {
854                            props.insert(k.into(), x.clone());
855                        }
856                    }
857                }
858                _ => {
859                    let key = match component {
860                        "Checkbox" | "Switch" => "checked",
861                        "ChipInput" => "values",
862                        "FileUpload" => "files",
863                        _ => "value",
864                    };
865                    props.insert(key.into(), v.clone());
866                }
867            }
868        }
869        // VAPP-162: a held `hold` Button paints its `holdingLabel`.
870        if component == "Button" && local.holds.get(id).is_some_and(crate::hold::HoldTracker::active) {
871            if let Some(label) = props.get("holdingLabel").and_then(Value::as_str).filter(|l| !l.is_empty()).map(str::to_string) {
872                props.insert("label".into(), Value::String(label));
873            }
874        }
875        if component == "Toggle" {
876            if let Some(pressed) = local.pressed_toggles.get(id) {
877                props.insert("pressed".into(), Value::Bool(*pressed));
878            }
879        }
880        if component == "ChipInput" {
881            if let Some(chips) = local.chips.get(id) {
882                props.insert("values".into(), Value::Array(chips.iter().cloned().map(Value::String).collect()));
883            }
884        }
885        if component == "FileUpload" {
886            if let Some(files) = local.files.get(id) {
887                props.insert("files".into(), Value::Array(files.clone()));
888            }
889        }
890        if component == "Table" {
891            if let Some((key, dir)) = local.sort.get(id) {
892                props.insert("sort".into(), json!({"key": key, "direction": dir}));
893            }
894            if let Some(sel) = local.selected.get(id) {
895                props.insert("selected".into(), Value::Array(sel.iter().cloned().map(Value::String).collect()));
896            }
897        }
898    }
899
900    /// The id suffixes of a template's items (the reference's
901    /// `templateItems`): `.<index>` without a `key`; with one, `.<value>`
902    /// (objects as JSON; `~`/`.` escaped as `~0`/`~1`), and `.#<index>` when the value is missing, null,
903    /// empty or a DUPLICATE of an earlier item's (more `#` until unique), so
904    /// instance ids never collide. Once per array per build.
905    fn item_suffixes(&mut self, t: &crate::types::Template, base: &str) -> std::sync::Arc<Vec<String>> {
906        let cache_key = format!("{base}\u{0}{}", t.key.as_deref().unwrap_or(""));
907        if let Some(s) = self.suffixes.get(&cache_key) {
908            return s.clone();
909        }
910        let version = self.ctx.data_version;
911        if let Some((v, keys)) = self.ctx.local.key_cache.get(&format!("s\u{0}{cache_key}")) {
912            if *v == version {
913                let keys = keys.clone();
914                self.suffixes.insert(cache_key, keys.clone());
915                return keys;
916            }
917        }
918        let items = crate::data::get_pointer(self.ctx.data, base).and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]);
919        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();
920        let out = std::sync::Arc::new(out);
921        self.ctx.local.key_cache.insert(format!("s\u{0}{cache_key}"), (version, out.clone()));
922        self.suffixes.insert(cache_key, out.clone());
923        out
924    }
925
926    /// The instance suffix `node` already wears (`.ops` for a node of the
927    /// `ops` item): a template inside it ACCUMULATES it (round 2,
928    /// `issue.title.ops.1`), so nested items never collide.
929    pub(crate) fn enclosing_suffix(&self, node: &UiNode) -> String {
930        match self.sources.get(&node.id) {
931            Some(src) if node.id.len() > src.id.len() && node.id.starts_with(src.id.as_str()) => node.id[src.id.len()..].to_string(),
932            _ => String::new(),
933        }
934    }
935
936    /// The node's children (static or from its template) under `parent`.
937    pub(crate) fn children_of(&mut self, parent: u32, node: &UiNode, scope: &str, hidden: bool) -> Vec<u32> {
938        let mut out = Vec::new();
939        let layer = self.nodes[parent as usize].layer;
940        for child in &node.children {
941            out.extend(self.add(child, Some(parent), layer, scope, hidden));
942        }
943        if let Some(t) = &node.template {
944            let base = crate::data::absolute_path(&t.path, scope);
945            let count = crate::data::get_pointer(self.ctx.data, &base).and_then(Value::as_array).map(Vec::len).unwrap_or(0);
946            if let Some(tpl) = (self.ctx.template)(&t.component) {
947                let suffixes = self.item_suffixes(t, &base);
948                let enclosing = self.enclosing_suffix(node);
949                for i in 0..count {
950                    if !self.take_template_item(&t.component, &tpl) {
951                        break;
952                    }
953                    let item_scope = format!("{base}/{i}");
954                    let suffix = format!("{enclosing}{}", suffixes[i]);
955                    let item = self.instance(&tpl, &suffix, Some(&t.component));
956                    out.extend(self.add(&item, Some(parent), layer, &item_scope, hidden));
957                }
958            }
959        }
960        out
961    }
962
963    /// Count one template item against `maxTemplateItems` and its template
964    /// subtree's nodes (the template node + every descendant through
965    /// children and slots; nested template items are charged when THEY are
966    /// instantiated) against `maxComponents`, on top of the reduced tree's
967    /// own nodes (the build starts there). The first item that does not
968    /// fit either is refused with ONE issue per build, and so is every
969    /// later item (the rest is not rendered).
970    fn take_template_item(&mut self, template: &str, tpl: &UiNode) -> bool {
971        if self.template_refused {
972            return false;
973        }
974        let nodes = subtree_nodes(tpl);
975        let message = if self.template_items >= crate::limits::MAX_TEMPLATE_ITEMS {
976            crate::limits::template_items_issue()
977        } else if self.template_nodes + nodes > crate::limits::MAX_COMPONENTS {
978            crate::limits::components_issue()
979        } else {
980            self.template_items += 1;
981            self.template_nodes += nodes;
982            return true;
983        };
984        self.template_refused = true;
985        self.issues.push(crate::types::ReduceIssue { id: template.to_string(), message });
986        false
987    }
988
989    /// The keys of a node's children without building them (the windowing
990    /// keys: static ids, then template items by key or index). Static lists
991    /// are computed once per reduce.
992    pub(crate) fn child_keys(&mut self, node: &UiNode, scope: &str) -> std::sync::Arc<Vec<String>> {
993        if node.template.is_none() {
994            if let Some(k) = self.ctx.local.static_keys.get(&node.id) {
995                if k.len() == node.children.len() {
996                    return k.clone();
997                }
998            }
999            let keys = std::sync::Arc::new(node.children.iter().map(|c| c.id.clone()).collect::<Vec<_>>());
1000            self.ctx.local.static_keys.insert(node.id.clone(), keys.clone());
1001            return keys;
1002        }
1003        let enclosing = self.enclosing_suffix(node);
1004        let cache_key = format!("c\u{0}{}\u{0}{scope}", node.id);
1005        if let Some((v, keys)) = self.ctx.local.key_cache.get(&cache_key) {
1006            if *v == self.ctx.data_version && keys.len() >= node.children.len() {
1007                return keys.clone();
1008            }
1009        }
1010        let mut keys: Vec<String> = node.children.iter().map(|c| c.id.clone()).collect();
1011        if let Some(t) = &node.template {
1012            let base = crate::data::absolute_path(&t.path, scope);
1013            for suffix in self.item_suffixes(t, &base).iter() {
1014                keys.push(format!("{}{enclosing}{suffix}", t.component));
1015            }
1016        }
1017        let keys = std::sync::Arc::new(keys);
1018        self.ctx.local.key_cache.insert(cache_key, (self.ctx.data_version, keys.clone()));
1019        keys
1020    }
1021
1022    /// Child `i` (static children first, then template items).
1023    pub(crate) fn one_child(&mut self, parent: u32, node: &UiNode, i: usize, scope: &str, hidden: bool) -> Option<u32> {
1024        let layer = self.nodes[parent as usize].layer;
1025        if let Some(child) = node.children.get(i) {
1026            return self.add(child, Some(parent), layer, scope, hidden);
1027        }
1028        let t = node.template.as_ref()?;
1029        let base = crate::data::absolute_path(&t.path, scope);
1030        let count = crate::data::get_pointer(self.ctx.data, &base).and_then(Value::as_array).map(Vec::len)?;
1031        let idx = i.checked_sub(node.children.len())?;
1032        if idx >= count {
1033            return None;
1034        }
1035        let tpl = (self.ctx.template)(&t.component)?;
1036        if !self.take_template_item(&t.component, &tpl) {
1037            return None;
1038        }
1039        let item_scope = format!("{base}/{idx}");
1040        let suffix = format!("{}{}", self.enclosing_suffix(node), self.item_suffixes(t, &base).get(idx).cloned().unwrap_or_else(|| format!(".{idx}")));
1041        let item = self.instance(&tpl, &suffix, Some(&t.component));
1042        self.add(&item, Some(parent), layer, &item_scope, hidden)
1043    }
1044
1045    /// A responsive native prop at the active breakpoint (`Drawer.side`).
1046    pub(crate) fn responsive_prop(&mut self, props: &Props, key: &str) -> Option<Value> {
1047        let v = props.get(key)?;
1048        if crate::macros::is_responsive_value(v) {
1049            self.responsive = true;
1050            return crate::macros::responsive_at(v, self.ctx.breakpoint.as_deref()).cloned();
1051        }
1052        Some(v.clone())
1053    }
1054
1055    /// Is the overlay `id` open (local state over the prop)?
1056    pub(crate) fn is_open(&self, id: &str, props: &Props, default: bool) -> bool {
1057        self.ctx.local.open.get(id).copied().unwrap_or_else(|| props.get("open").and_then(Value::as_bool).unwrap_or(default))
1058    }
1059
1060    /// Start a new layer: its root container (a synthetic part of `owner`).
1061    pub(crate) fn layer_root(&mut self, owner: &LNode, part: &str, style: Value) -> (u32, u32) {
1062        let layer = self.next_layer;
1063        self.next_layer += 1;
1064        let mut root = self.blank(&format!("{}.{part}", owner.id), "Box", None, layer, NodeKind::Container, &owner.scope);
1065        root.part = Some(part.to_string());
1066        root.owner = Some(owner.id.clone());
1067        root.owner_component = Some(owner.component.clone());
1068        root.form = owner.form.clone();
1069        root.base_style = obj(style);
1070        root.part_query = Some(RecipeQuery::new(owner.component.clone(), part, self.ctx.recipes.native_recipe_props(&owner.component, &owner.props), vec!["open".into()]));
1071        let index = self.push(root);
1072        (layer, index)
1073    }
1074
1075    #[allow(clippy::too_many_arguments)]
1076    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>) {
1077        let class = if matches!(placement, LayerPlacement::Toast { .. }) { LayerClass::Toast } else { LayerClass::Overlay };
1078        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 });
1079    }
1080}
1081
1082/// `/$row/<table>/<i>[/…]` → `/$row/<table>/<i>` (a literal Table row's
1083/// scope root).
1084pub fn row_scope_root(scope: &str) -> Option<&str> {
1085    let rest = scope.strip_prefix("/$row/")?;
1086    let mut end = "/$row/".len();
1087    for (k, part) in rest.splitn(3, '/').enumerate().take(2) {
1088        end += part.len() + usize::from(k == 0);
1089    }
1090    Some(&scope[..end])
1091}
1092
1093/// The builtin glyph of a part (`core.catalog.json` `builtinIcons`).
1094pub fn builtin_icon(slot: &str) -> Option<&'static str> {
1095    let g = crate::generated::catalog::BUILTIN_ICON_SLOTS.iter().position(|s| *s == slot)?;
1096    crate::generated::catalog::BUILTIN_ICON_NAMES.get(g).copied()
1097}
1098
1099/// Build the layout tree for a normalized root. `Unknown` nodes become
1100/// leaves the painter renders as the placeholder.
1101pub fn build(root: &UiNode, ctx: &mut BuildContext) -> Built {
1102    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() };
1103    if b.add(root, None, 0, "", false).is_none() {
1104        // An invisible root: an empty surface (one hidden Box).
1105        let mut n = b.blank(&root.id, "Box", None, 0, NodeKind::Container, "");
1106        n.hidden = true;
1107        b.push(n);
1108    }
1109    b.flush_toasts();
1110    // Layers in paint order: a parent layer before the layers it opened
1111    // (layer numbers are handed out when a layer's root is created).
1112    b.layers.sort_by_key(|l| (l.class == LayerClass::Toast, l.layer));
1113    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 }
1114}
1115
1116/// Rebuild ONE subtree (a re-windowed List/Table) under an existing parent:
1117/// node 0 of the result is a stub of `parent` (the caller keeps the real
1118/// one), the rest is the subtree in pre-order. `seed` = what the full build
1119/// knew above it (the enclosing Forms' disabled/busy, literal Table rows),
1120/// so the subtree comes out exactly as a full rebuild would build it.
1121pub fn build_subtree(node: &UiNode, parent: &LNode, scope: &str, seed: BuildSeed, ctx: &mut BuildContext) -> Built {
1122    let mut stub = parent.clone();
1123    stub.index = 0;
1124    stub.parent = None;
1125    stub.children.clear();
1126    let layer = stub.layer;
1127    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() };
1128    b.add(node, Some(0), layer, scope, false);
1129    b.flush_toasts();
1130    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 }
1131}
1132
1133/// EXP-1604: a Motion's composition size in px: the dialect's `size`, else
1134/// the inline Lottie's `w` × `h`; `None` for a `src` animation.
1135pub fn motion_size(props: &Props) -> Option<(f64, f64)> {
1136    let pos = |v: Option<&Value>| v.and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0);
1137    let size = props.get("size").and_then(Value::as_array);
1138    let from_size = size.and_then(|a| Some((pos(a.first())?, pos(a.get(1))?)));
1139    from_size.or_else(|| {
1140        let l = props.get("lottie")?;
1141        Some((pos(l.get("w"))?, pos(l.get("h"))?))
1142    })
1143}
1144
1145/// EXP-1586: a ZoomableImage's width / height without a style `height`:
1146/// naturalWidth / naturalHeight (a TALL picture, w/h under `tallAspect`,
1147/// capped at a square so a full-page capture opens as a window onto its
1148/// top), else `mediaAspectRatio` (16:9).
1149pub fn zoomable_aspect_ratio(props: &Props) -> f64 {
1150    let num = |k: &str| props.get(k).and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0);
1151    match (num("naturalWidth"), num("naturalHeight")) {
1152        (Some(w), Some(h)) if crate::zoom::zoom_is_tall(crate::zoom::ZoomSize { width: w, height: h }) => 1.0,
1153        (Some(w), Some(h)) => w / h,
1154        _ => crate::layout::MEDIA_ASPECT_RATIO,
1155    }
1156}
1157
1158#[cfg(test)]
1159mod tests {
1160    use super::*;
1161
1162    #[test]
1163    fn builtin_glyphs_resolve() {
1164        assert_eq!(builtin_icon("CodeBlock.copy"), Some("ui-copy"));
1165        assert_eq!(builtin_icon("Table.sortIcon.asc"), Some("ui-chevron-up"));
1166        assert_eq!(builtin_icon("Nope.x"), None);
1167    }
1168
1169    #[test]
1170    fn a_zoomable_box_follows_its_picture() {
1171        let p = |v: Value| v.as_object().cloned().unwrap_or_default();
1172        assert!((zoomable_aspect_ratio(&p(json!({"naturalWidth": 1440, "naturalHeight": 900}))) - 1.6).abs() < 1e-9);
1173        // A tall picture opens as a square window onto its top.
1174        assert_eq!(zoomable_aspect_ratio(&p(json!({"naturalWidth": 1000, "naturalHeight": 8000}))), 1.0);
1175        assert!((zoomable_aspect_ratio(&p(json!({"naturalWidth": 600, "naturalHeight": 900}))) - 600.0 / 900.0).abs() < 1e-9);
1176        assert_eq!(zoomable_aspect_ratio(&p(json!({}))), crate::layout::MEDIA_ASPECT_RATIO);
1177    }
1178}