mod containers;
pub mod fields;
mod misc;
mod overlays;
pub use overlays::is_context_menu;
pub mod search;
mod table;
use std::collections::HashMap;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use crate::catalog::CatalogView;
use crate::data::{resolve_value, ResolveContext};
use crate::list::{ListWindow, VisibleRange};
use crate::overlay::{OverlayAlign, OverlaySide};
use crate::recipes::RecipeIndex;
use crate::strings::StringTable;
use crate::theme::RecipeQuery;
use crate::types::{Props, UiNode};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NodeKind {
Container,
Leaf,
}
#[derive(Debug, Clone, PartialEq)]
pub struct LNode {
pub index: u32,
pub id: String,
pub component: String,
pub part: Option<String>,
pub owner: Option<String>,
pub owner_component: Option<String>,
pub catalog_id: Option<String>,
pub extension_kind: Option<String>,
pub depth: u32,
pub parent: Option<u32>,
pub children: Vec<u32>,
pub layer: u32,
pub kind: NodeKind,
pub props: Props,
pub base_style: Props,
pub default_keys: Vec<String>,
pub own_query: Option<RecipeQuery>,
pub part_query: Option<RecipeQuery>,
pub authored_keys: Vec<String>,
pub hidden: bool,
pub lines: Option<u32>,
pub pressable: bool,
pub scope: String,
pub source: Option<SourceRef>,
pub on: Option<IndexMap<String, Value>>,
pub accessibility: Option<Value>,
pub trigger_for: Option<String>,
pub form: Option<String>,
pub form_disabled: bool,
pub live: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceRef {
pub id: String,
pub template: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum LayerPlacement {
Centered,
Edge(OverlaySide),
Anchored { anchor: u32, side: OverlaySide, align: OverlayAlign },
AtPoint { x: f32, y: f32 },
Toast { order: u32 },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LayerClass {
Overlay,
Toast,
}
#[derive(Debug, Clone, PartialEq)]
pub struct LayerSpec {
pub layer: u32,
pub root: u32,
pub kind: String,
pub owner: String,
pub placement: LayerPlacement,
pub class: LayerClass,
pub modal: bool,
pub dismissible: bool,
pub match_anchor_width: bool,
pub scroll_body: Option<u32>,
pub mirror: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ListSpec {
pub node: u32,
pub id: String,
pub keys: std::sync::Arc<Vec<String>>,
pub range: VisibleRange,
pub offsets: std::sync::Arc<Vec<f32>>,
pub content_height: f32,
pub windowed: bool,
pub horizontal: bool,
pub gap: f32,
pub data_index: Option<std::sync::Arc<Vec<Option<usize>>>>,
pub headers: std::sync::Arc<Vec<usize>>,
pub sticky: bool,
pub static_count: usize,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ListViewSource {
Own,
Ancestor { id: String, rel: f32 },
Host { rel: f32 },
}
#[derive(Debug, Clone, PartialEq)]
pub struct ListView {
pub source: ListViewSource,
pub viewport: f32,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct FieldErrors {
pub name: String,
pub messages: Vec<String>,
}
#[derive(Debug, Clone, Default)]
pub struct LocalState {
pub tabs: HashMap<String, String>,
pub accordion: HashMap<String, Vec<String>>,
pub carousel: HashMap<String, i64>,
pub open: HashMap<String, bool>,
pub pressed_toggles: HashMap<String, bool>,
pub holds: HashMap<String, crate::hold::HoldTracker>,
pub lists: HashMap<String, ListWindow>,
pub scroll: HashMap<String, (f32, f32)>,
pub query: HashMap<String, String>,
pub month: HashMap<String, (i32, u32)>,
pub range_anchor: HashMap<String, String>,
pub submenu: HashMap<String, usize>,
pub active: HashMap<String, usize>,
pub context_point: HashMap<String, (f32, f32)>,
pub field_values: HashMap<String, Value>,
pub errors: HashMap<String, FieldErrors>,
pub sort: HashMap<String, (String, String)>,
pub selected: HashMap<String, Vec<String>>,
pub chips: HashMap<String, Vec<String>>,
pub files: HashMap<String, Vec<Value>>,
pub copied: HashMap<String, bool>,
pub static_keys: HashMap<String, std::sync::Arc<Vec<String>>>,
pub list_views: HashMap<String, ListView>,
pub surface_scroll: Option<(f32, f32)>,
pub sizes: HashMap<String, Vec<f64>>,
pub drags: HashMap<String, Vec<f64>>,
pub sticky_any: bool,
pub key_cache: HashMap<String, (u64, std::sync::Arc<Vec<String>>)>,
}
pub struct BuildContext<'a> {
pub view: &'a CatalogView,
pub recipes: &'a RecipeIndex,
pub data: &'a Value,
pub local: &'a mut LocalState,
pub template: &'a dyn Fn(&str) -> Option<UiNode>,
pub viewport_height: f32,
pub viewport_width: f32,
pub hairline: f32,
pub row_extent: f32,
pub menu_row: f32,
pub tab_bar: f32,
pub checkbox: f32,
pub gap_px: &'a dyn Fn(&str) -> f32,
pub expand_controls: bool,
pub strings: &'a StringTable,
pub breakpoint: Option<String>,
pub locale: &'a str,
pub wide: bool,
pub today: Option<String>,
pub formatter: &'a dyn crate::format::Formatter,
pub now: f64,
pub data_version: u64,
}
pub struct Built {
pub nodes: Vec<LNode>,
pub layers: Vec<LayerSpec>,
pub lists: Vec<ListSpec>,
pub responsive: bool,
pub toasts: Vec<ToastSpec>,
pub row_scopes: HashMap<String, Value>,
pub forms: HashMap<String, (bool, bool)>,
pub issues: Vec<crate::types::ReduceIssue>,
}
#[derive(Debug, Clone, Default)]
pub struct BuildSeed {
pub row_scopes: HashMap<String, Value>,
pub forms: HashMap<String, (bool, bool)>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToastSpec {
pub id: String,
pub duration_ms: f64,
#[serde(rename = "type")]
pub kind: String,
}
pub(crate) struct Builder<'a, 'b> {
pub(crate) ctx: &'b mut BuildContext<'a>,
pub(crate) nodes: Vec<LNode>,
pub(crate) layers: Vec<LayerSpec>,
pub(crate) lists: Vec<ListSpec>,
pub(crate) responsive: bool,
pub(crate) toasts: Vec<ToastSpec>,
pub(crate) pending_toasts: Vec<(u32, UiNode)>,
pub(crate) next_layer: u32,
pub(crate) row_scopes: HashMap<String, Value>,
pub(crate) forms: HashMap<String, (bool, bool)>,
pub(crate) sources: HashMap<String, SourceRef>,
pub(crate) suffixes: HashMap<String, std::sync::Arc<Vec<String>>>,
pub(crate) flex_gaps: HashMap<u32, f32>,
pub(crate) template_items: usize,
pub(crate) template_nodes: usize,
pub(crate) template_refused: bool,
pub(crate) issues: Vec<crate::types::ReduceIssue>,
}
pub(crate) fn subtree_nodes(root: &UiNode) -> usize {
let mut count = 0;
let mut stack = vec![root];
while let Some(n) = stack.pop() {
count += 1;
stack.extend(n.children.iter());
stack.extend(n.slots.iter().flat_map(|s| s.values()));
}
count
}
pub(crate) fn obj(v: Value) -> Props {
match v {
Value::Object(m) => m,
_ => Map::new(),
}
}
fn with_suffix(node: &UiNode, suffix: &str, template: Option<&str>, sources: &mut HashMap<String, SourceRef>) -> UiNode {
let mut out = node.clone();
out.id = format!("{}{suffix}", node.id);
let source = sources.get(&node.id).cloned().unwrap_or_else(|| SourceRef { id: node.id.clone(), template: template.map(str::to_string) });
sources.insert(out.id.clone(), source);
out.children = node.children.iter().map(|c| with_suffix(c, suffix, template, sources)).collect();
if let Some(slots) = &node.slots {
out.slots = Some(slots.iter().map(|(k, v)| (k.clone(), with_suffix(v, suffix, template, sources))).collect());
}
out
}
pub const OVERLAYS: &[&str] = &["Dialog", "Drawer", "Popover", "Tooltip", "Menu"];
pub const FORM_FIELDS: &[&str] =
&["Input", "Textarea", "NumberField", "Checkbox", "Radio", "ChoiceTiles", "Switch", "Select", "ChipInput", "DatePicker", "DateRangePicker", "TimePicker", "FileUpload", "Slider"];
pub(crate) fn display_text_props(def: &crate::types::ComponentDef, props: &mut Props) {
for (k, v) in props.iter_mut() {
if matches!(v, Value::Number(_) | Value::Bool(_)) && def.props.get(k).is_some_and(|s| s.type_ == "string" || s.type_ == "markdown") {
*v = Value::String(crate::format::display_string(v));
}
}
}
pub(crate) fn str_prop<'p>(props: &'p Props, key: &str) -> Option<&'p str> {
props.get(key).and_then(Value::as_str)
}
pub(crate) fn recipe_props(props: &Props, form_disabled: bool) -> std::borrow::Cow<'_, Props> {
if !form_disabled {
return std::borrow::Cow::Borrowed(props);
}
let mut own = props.clone();
own.remove("disabled");
std::borrow::Cow::Owned(own)
}
pub(crate) fn bool_prop(props: &Props, key: &str) -> bool {
props.get(key).and_then(Value::as_bool).unwrap_or(false)
}
pub(crate) fn js(v: &Value) -> String {
crate::json::to_js_string(v)
}
impl<'a, 'b> Builder<'a, 'b> {
pub(crate) fn resolve_ctx<'s>(&'s self, scope: &'s str) -> ResolveContext<'s> {
let ctx = ResolveContext::new(self.ctx.data, scope).with_strings(self.ctx.strings).with_formatter(self.ctx.formatter).with_now(self.ctx.now);
match row_scope_root(scope).and_then(|root| self.row_scopes.get_key_value(root)) {
Some((root, row)) => ctx.with_overlay(root, row),
None => ctx,
}
}
pub(crate) fn resolve(&self, value: &Value, scope: &str) -> Option<Value> {
resolve_value(value, &self.resolve_ctx(scope))
}
pub(crate) fn resolve_map(&self, map: &Props, scope: &str) -> Props {
obj(resolve_value(&Value::Object(map.clone()), &self.resolve_ctx(scope)).unwrap_or(Value::Null))
}
pub(crate) fn string(&self, id: &str) -> String {
self.ctx.strings.get(id).cloned().unwrap_or_else(|| id.to_string())
}
pub(crate) fn string_with(&self, id: &str, params: &[(&str, &str)]) -> String {
let params: Map<String, Value> = params.iter().map(|(k, v)| (k.to_string(), Value::String(v.to_string()))).collect();
crate::strings::format_string(&self.string(id), ¶ms)
}
pub(crate) fn instance(&mut self, node: &UiNode, suffix: &str, template: Option<&str>) -> UiNode {
with_suffix(node, suffix, template, &mut self.sources)
}
pub(crate) fn push(&mut self, mut node: LNode) -> u32 {
let index = self.nodes.len() as u32;
node.index = index;
if let Some(p) = node.parent {
self.nodes[p as usize].children.push(index);
}
self.nodes.push(node);
index
}
pub(crate) fn blank(&self, id: &str, component: &str, parent: Option<u32>, layer: u32, kind: NodeKind, scope: &str) -> LNode {
let (depth, hidden, form) = parent
.map(|p| {
let pn = &self.nodes[p as usize];
(pn.depth + 1, pn.hidden, pn.form.clone())
})
.unwrap_or((0, false, None));
LNode {
index: 0,
id: id.to_string(),
component: component.to_string(),
part: None,
owner: None,
owner_component: None,
catalog_id: None,
extension_kind: None,
depth,
parent,
children: Vec::new(),
layer,
kind,
props: Map::new(),
base_style: Map::new(),
default_keys: Vec::new(),
own_query: None,
part_query: None,
authored_keys: Vec::new(),
hidden,
lines: None,
pressable: false,
scope: scope.to_string(),
source: None,
on: None,
accessibility: None,
trigger_for: None,
form,
form_disabled: false,
live: None,
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn part_in(&mut self, parent: u32, owner: &LNode, part: &str, component: &str, kind: NodeKind, style: Value, props: Value, suffix: &str) -> u32 {
let id = format!("{}.{part}{suffix}", owner.id);
let layer = self.nodes[parent as usize].layer;
let mut n = self.blank(&id, component, Some(parent), layer, kind, &owner.scope);
n.part = Some(part.to_string());
n.owner = Some(owner.id.clone());
n.owner_component = Some(owner.component.clone());
n.base_style = obj(style);
n.props = obj(props);
let query_props = self.ctx.recipes.native_recipe_props(&owner.component, &recipe_props(&owner.props, owner.form_disabled));
n.part_query = Some(RecipeQuery::new(owner.component.clone(), part, query_props, Vec::new()));
if let Some(l) = n.props.get("lines").and_then(Value::as_u64) {
n.lines = Some(l as u32);
}
self.push(n)
}
pub(crate) fn part(&mut self, owner: &LNode, part: &str, component: &str, kind: NodeKind, style: Value, props: Value) -> u32 {
self.part_in(owner.index, owner, part, component, kind, style, props, "")
}
pub(crate) fn text_part(&mut self, parent: u32, owner: &LNode, part: &str, text: &str, variant: &str, suffix: &str) -> u32 {
self.part_in(parent, owner, part, "Text", NodeKind::Leaf, json!({}), json!({"text": text, "variant": variant}), suffix)
}
pub(crate) fn icon_part(&mut self, parent: u32, owner: &LNode, part: &str, glyph_slot: &str, suffix: &str) -> u32 {
let name = builtin_icon(glyph_slot).unwrap_or("ui-icon-placeholder");
self.part_in(parent, owner, part, "Icon", NodeKind::Leaf, json!({"flexShrink": 0}), json!({"name": name, "size": "sm"}), suffix)
}
pub(crate) fn default_a11y(&mut self, index: u32, key: &str, value: Value) {
let a = self.nodes[index as usize].accessibility.get_or_insert_with(|| json!({}));
if let Some(m) = a.as_object_mut() {
m.entry(key.to_string()).or_insert(value);
}
}
pub(crate) fn add_state(&mut self, index: u32, state: &str) {
if let Some(q) = &mut self.nodes[index as usize].part_query {
if !q.states.iter().any(|s| s == state) {
q.states.push(state.to_string());
}
}
}
pub(crate) fn query_prop(&mut self, index: u32, key: &str, value: Value) {
if let Some(q) = &mut self.nodes[index as usize].part_query {
q.props.insert(key.to_string(), value);
}
}
pub(crate) fn style_default(&mut self, index: u32, entries: &[(&str, Value)]) {
let n = &mut self.nodes[index as usize];
for (k, v) in entries {
if !n.base_style.contains_key(*k) {
n.base_style.insert(k.to_string(), v.clone());
n.default_keys.push(k.to_string());
}
}
}
fn media_ratio(&mut self, index: u32) {
let n = &self.nodes[index as usize];
let given = n.props.get("aspectRatio").and_then(Value::as_f64).filter(|r| r.is_finite() && *r > 0.0);
let has_height = n.props.get("height").is_some_and(|v| !v.is_null()) || n.base_style.contains_key("height");
let ratio = given.or_else(|| (n.component == "Video" || !has_height).then_some(crate::layout::MEDIA_ASPECT_RATIO));
if let Some(r) = ratio {
self.style_default(index, &[("aspectRatio", json!(r))]);
}
}
fn zoomable_box(&mut self, index: u32) {
let n = &self.nodes[index as usize];
let has_height = n.base_style.contains_key("height");
let ratio = zoomable_aspect_ratio(&n.props);
self.style_default(index, &[("width", json!("100%"))]);
if !has_height {
self.style_default(index, &[("aspectRatio", json!(ratio))]);
}
}
fn motion_box(&mut self, index: u32) {
let n = &self.nodes[index as usize];
let Some((w, h)) = motion_size(&n.props) else { return };
let (has_w, has_h) = (n.base_style.contains_key("width"), n.base_style.contains_key("height"));
if !has_w && !has_h {
self.style_default(index, &[("width", json!(w)), ("maxWidth", json!("100%"))]);
}
if !(has_w && has_h) {
self.style_default(index, &[("aspectRatio", json!(w / h))]);
}
}
pub(crate) fn is_overlay(component: &str) -> bool {
OVERLAYS.contains(&component)
}
fn visible(&self, node: &UiNode, scope: &str) -> bool {
crate::data::is_visible(node.visible.as_ref(), &self.resolve_ctx(scope))
}
pub(crate) fn add(&mut self, node: &UiNode, parent: Option<u32>, layer: u32, scope: &str, force_hidden: bool) -> Option<u32> {
crate::deep(|| self.add_node(node, parent, layer, scope, force_hidden))
}
fn add_node(&mut self, node: &UiNode, parent: Option<u32>, layer: u32, scope: &str, force_hidden: bool) -> Option<u32> {
if !self.visible(node, scope) {
return None;
}
let view = self.ctx.view;
let def = view.component(&node.component);
let mut props = crate::data::resolve_node_props(def, &node.props, &self.resolve_ctx(scope), &view.defs);
if let Some(def) = def {
display_text_props(def, &mut props);
}
self.local_overrides(&node.id, &node.component, &mut props);
let form = parent.and_then(|p| self.nodes[p as usize].form.clone());
let mut form_disabled = false;
if let Some((disabled, busy)) = form.as_ref().and_then(|f| self.forms.get(f)).copied() {
if disabled && (FORM_FIELDS.contains(&node.component.as_str()) || node.component == "Button") {
form_disabled = !bool_prop(&props, "disabled");
props.insert("disabled".into(), Value::Bool(true));
}
if busy && node.component == "Button" && bool_prop(&props, "submit") {
props.insert("loading".into(), Value::Bool(true));
}
}
let ext = view.extension_of(&node.component).map(str::to_string);
let children_rule = def.map(|d| d.children.as_str()).unwrap_or("none");
let has_children = !node.children.is_empty() || node.template.is_some();
let component = if ext.is_some() { "Extension".to_string() } else { node.component.clone() };
let kind = if ext.is_some() {
if has_children {
NodeKind::Container
} else {
NodeKind::Leaf
}
} else {
match (node.component.as_str(), children_rule) {
("Box", _) => NodeKind::Container,
(_, "none") => NodeKind::Leaf,
("Button", "one") => {
if has_children {
NodeKind::Container
} else {
NodeKind::Leaf
}
}
_ => NodeKind::Container,
}
};
let mut n = self.blank(&node.id, &component, parent, layer, kind, scope);
n.hidden |= force_hidden;
if let Some(e) = ext {
n.catalog_id = Some(e);
n.extension_kind = Some(node.component.clone());
}
let mut base: Props = props.get("style").and_then(Value::as_object).cloned().unwrap_or_default();
if let Some(s) = &node.style {
for (k, v) in self.resolve_map(s, scope) {
base.insert(k, v);
}
}
n.base_style = base;
n.lines = props.get("lines").and_then(Value::as_u64).map(|l| l as u32);
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");
n.on = node.on.clone();
n.source = self.sources.get(&node.id).cloned();
n.accessibility = node.accessibility.as_ref().and_then(|a| self.resolve(a, scope));
n.live = str_prop(&props, "live").filter(|l| *l != "off").map(str::to_string);
n.form_disabled = form_disabled;
n.own_query = Some(RecipeQuery::new(node.component.clone(), "root", self.ctx.recipes.native_recipe_props(&node.component, &recipe_props(&props, form_disabled)), Vec::new()));
if let Some(r) = &node.recipe {
n.part_query = Some(RecipeQuery::new(r.macro_.clone(), r.part.clone(), self.resolve_map(&r.props, scope), Vec::new()));
n.authored_keys = r.authored.clone();
}
if node.component == "Form" {
n.form = Some(node.id.clone());
}
n.props = props;
let index = self.push(n);
if node.component == "Button" && self.ctx.local.holds.get(&node.id).is_some_and(crate::hold::HoldTracker::active) {
self.add_state_own(index, "pressed");
}
if let Some(errors) = self.ctx.local.errors.get(&node.id) {
if !errors.messages.is_empty() {
let _ = errors;
self.add_state_own(index, "invalid");
}
}
let expand = self.ctx.expand_controls;
match node.component.as_str() {
"Image" | "Video" => self.media_ratio(index),
"ZoomableImage" => self.zoomable_box(index),
"Motion" => self.motion_box(index),
"Segmented" if crate::segmented::is_rail(&self.nodes[index as usize].props) => {
let tall = crate::segmented::rail_height(&self.nodes[index as usize].props, self.ctx.tab_bar);
self.style_default(index, &[("alignSelf", json!("flex-start")), ("flexShrink", json!(0)), ("height", json!(tall))])
}
"Segmented" if str_prop(&self.nodes[index as usize].props, "variant") == Some("bar") => {
self.style_default(index, &[("width", json!("100%"))])
}
"Segmented" if !bool_prop(&self.nodes[index as usize].props, "fill") && str_prop(&self.nodes[index as usize].props, "variant") != Some("bar") => {
self.style_default(index, &[("alignSelf", json!("flex-start"))])
}
"Button" if self.nodes[index as usize].kind == NodeKind::Container => {
self.style_default(index, &[("display", json!("flex")), ("flexDirection", json!("row")), ("alignItems", json!("center")), ("justifyContent", json!("center"))])
}
"VoiceWave" => self.style_default(index, &[("display", json!("flex")), ("alignItems", json!("center")), ("justifyContent", json!("center"))]),
"TreeGuides" => {
let depth = self.nodes[index as usize].props.get("depth").and_then(Value::as_f64).unwrap_or(0.0).max(0.0);
self.style_default(index, &[("alignSelf", json!("stretch")), ("width", json!(depth * crate::layout::TREE_GUIDE_COLUMN)), ("flexShrink", json!(0))]);
}
_ => {}
}
match node.component.as_str() {
"Tabs" => self.tabs(index, node, scope),
"Accordion" => self.accordion(index, node, scope),
"Carousel" => self.carousel(index, node, scope),
"List" => self.list(index, node, scope),
"Resizable" => self.resizable(index, node, scope),
"Table" => self.table(index, node, scope),
"Toast" => self.toast(index, node),
c if Self::is_overlay(c) => self.overlay(index, node, scope),
"Form" => self.form(index, node, scope),
"Input" | "Textarea" if expand => self.field(index),
"Select" if expand => self.select(index),
"DatePicker" | "DateRangePicker" if expand => self.date_picker(index),
"TimePicker" if expand => self.time_picker(index),
"NumberField" if expand => self.number_field(index),
"ChipInput" if expand => self.chip_input(index),
"FileUpload" if expand => self.file_upload(index),
"CodeBlock" if expand => self.code_block(index),
"Checkbox" | "Switch" if expand => self.check(index),
"Radio" if expand => self.radio(index),
"ChoiceTiles" if expand => self.choice_tiles(index),
"Slider" if expand => self.slider(index),
"SearchList" if expand => self.search_list(index),
"Skeleton" => self.skeleton_rows(index),
"Chart" => self.chart(index),
_ => {
if let Some(slots) = &node.slots {
for slot in slots.values() {
self.add(slot, Some(index), layer, scope, false);
}
}
self.children_of(index, node, scope, false);
}
}
Some(index)
}
fn add_state_own(&mut self, index: u32, state: &str) {
if let Some(q) = &mut self.nodes[index as usize].own_query {
if !q.states.iter().any(|s| s == state) {
q.states.push(state.to_string());
}
}
}
fn local_overrides(&self, id: &str, component: &str, props: &mut Props) {
let local = &self.ctx.local;
if let Some(v) = local.field_values.get(id) {
match component {
"DateRangePicker" => {
for k in ["start", "end"] {
if let Some(x) = v.get(k) {
props.insert(k.into(), x.clone());
}
}
}
_ => {
let key = match component {
"Checkbox" | "Switch" => "checked",
"ChipInput" => "values",
"FileUpload" => "files",
_ => "value",
};
props.insert(key.into(), v.clone());
}
}
}
if component == "Button" && local.holds.get(id).is_some_and(crate::hold::HoldTracker::active) {
if let Some(label) = props.get("holdingLabel").and_then(Value::as_str).filter(|l| !l.is_empty()).map(str::to_string) {
props.insert("label".into(), Value::String(label));
}
}
if component == "Toggle" {
if let Some(pressed) = local.pressed_toggles.get(id) {
props.insert("pressed".into(), Value::Bool(*pressed));
}
}
if component == "ChipInput" {
if let Some(chips) = local.chips.get(id) {
props.insert("values".into(), Value::Array(chips.iter().cloned().map(Value::String).collect()));
}
}
if component == "FileUpload" {
if let Some(files) = local.files.get(id) {
props.insert("files".into(), Value::Array(files.clone()));
}
}
if component == "Table" {
if let Some((key, dir)) = local.sort.get(id) {
props.insert("sort".into(), json!({"key": key, "direction": dir}));
}
if let Some(sel) = local.selected.get(id) {
props.insert("selected".into(), Value::Array(sel.iter().cloned().map(Value::String).collect()));
}
}
}
fn item_suffixes(&mut self, t: &crate::types::Template, base: &str) -> std::sync::Arc<Vec<String>> {
let cache_key = format!("{base}\u{0}{}", t.key.as_deref().unwrap_or(""));
if let Some(s) = self.suffixes.get(&cache_key) {
return s.clone();
}
let version = self.ctx.data_version;
if let Some((v, keys)) = self.ctx.local.key_cache.get(&format!("s\u{0}{cache_key}")) {
if *v == version {
let keys = keys.clone();
self.suffixes.insert(cache_key, keys.clone());
return keys;
}
}
let items = crate::data::get_pointer(self.ctx.data, base).and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]);
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();
let out = std::sync::Arc::new(out);
self.ctx.local.key_cache.insert(format!("s\u{0}{cache_key}"), (version, out.clone()));
self.suffixes.insert(cache_key, out.clone());
out
}
pub(crate) fn enclosing_suffix(&self, node: &UiNode) -> String {
match self.sources.get(&node.id) {
Some(src) if node.id.len() > src.id.len() && node.id.starts_with(src.id.as_str()) => node.id[src.id.len()..].to_string(),
_ => String::new(),
}
}
pub(crate) fn children_of(&mut self, parent: u32, node: &UiNode, scope: &str, hidden: bool) -> Vec<u32> {
let mut out = Vec::new();
let layer = self.nodes[parent as usize].layer;
for child in &node.children {
out.extend(self.add(child, Some(parent), layer, scope, hidden));
}
if let Some(t) = &node.template {
let base = crate::data::absolute_path(&t.path, scope);
let count = crate::data::get_pointer(self.ctx.data, &base).and_then(Value::as_array).map(Vec::len).unwrap_or(0);
if let Some(tpl) = (self.ctx.template)(&t.component) {
let suffixes = self.item_suffixes(t, &base);
let enclosing = self.enclosing_suffix(node);
for i in 0..count {
if !self.take_template_item(&t.component, &tpl) {
break;
}
let item_scope = format!("{base}/{i}");
let suffix = format!("{enclosing}{}", suffixes[i]);
let item = self.instance(&tpl, &suffix, Some(&t.component));
out.extend(self.add(&item, Some(parent), layer, &item_scope, hidden));
}
}
}
out
}
fn take_template_item(&mut self, template: &str, tpl: &UiNode) -> bool {
if self.template_refused {
return false;
}
let nodes = subtree_nodes(tpl);
let message = if self.template_items >= crate::limits::MAX_TEMPLATE_ITEMS {
crate::limits::template_items_issue()
} else if self.template_nodes + nodes > crate::limits::MAX_COMPONENTS {
crate::limits::components_issue()
} else {
self.template_items += 1;
self.template_nodes += nodes;
return true;
};
self.template_refused = true;
self.issues.push(crate::types::ReduceIssue { id: template.to_string(), message });
false
}
pub(crate) fn child_keys(&mut self, node: &UiNode, scope: &str) -> std::sync::Arc<Vec<String>> {
if node.template.is_none() {
if let Some(k) = self.ctx.local.static_keys.get(&node.id) {
if k.len() == node.children.len() {
return k.clone();
}
}
let keys = std::sync::Arc::new(node.children.iter().map(|c| c.id.clone()).collect::<Vec<_>>());
self.ctx.local.static_keys.insert(node.id.clone(), keys.clone());
return keys;
}
let enclosing = self.enclosing_suffix(node);
let cache_key = format!("c\u{0}{}\u{0}{scope}", node.id);
if let Some((v, keys)) = self.ctx.local.key_cache.get(&cache_key) {
if *v == self.ctx.data_version && keys.len() >= node.children.len() {
return keys.clone();
}
}
let mut keys: Vec<String> = node.children.iter().map(|c| c.id.clone()).collect();
if let Some(t) = &node.template {
let base = crate::data::absolute_path(&t.path, scope);
for suffix in self.item_suffixes(t, &base).iter() {
keys.push(format!("{}{enclosing}{suffix}", t.component));
}
}
let keys = std::sync::Arc::new(keys);
self.ctx.local.key_cache.insert(cache_key, (self.ctx.data_version, keys.clone()));
keys
}
pub(crate) fn one_child(&mut self, parent: u32, node: &UiNode, i: usize, scope: &str, hidden: bool) -> Option<u32> {
let layer = self.nodes[parent as usize].layer;
if let Some(child) = node.children.get(i) {
return self.add(child, Some(parent), layer, scope, hidden);
}
let t = node.template.as_ref()?;
let base = crate::data::absolute_path(&t.path, scope);
let count = crate::data::get_pointer(self.ctx.data, &base).and_then(Value::as_array).map(Vec::len)?;
let idx = i.checked_sub(node.children.len())?;
if idx >= count {
return None;
}
let tpl = (self.ctx.template)(&t.component)?;
if !self.take_template_item(&t.component, &tpl) {
return None;
}
let item_scope = format!("{base}/{idx}");
let suffix = format!("{}{}", self.enclosing_suffix(node), self.item_suffixes(t, &base).get(idx).cloned().unwrap_or_else(|| format!(".{idx}")));
let item = self.instance(&tpl, &suffix, Some(&t.component));
self.add(&item, Some(parent), layer, &item_scope, hidden)
}
pub(crate) fn responsive_prop(&mut self, props: &Props, key: &str) -> Option<Value> {
let v = props.get(key)?;
if crate::macros::is_responsive_value(v) {
self.responsive = true;
return crate::macros::responsive_at(v, self.ctx.breakpoint.as_deref()).cloned();
}
Some(v.clone())
}
pub(crate) fn is_open(&self, id: &str, props: &Props, default: bool) -> bool {
self.ctx.local.open.get(id).copied().unwrap_or_else(|| props.get("open").and_then(Value::as_bool).unwrap_or(default))
}
pub(crate) fn layer_root(&mut self, owner: &LNode, part: &str, style: Value) -> (u32, u32) {
let layer = self.next_layer;
self.next_layer += 1;
let mut root = self.blank(&format!("{}.{part}", owner.id), "Box", None, layer, NodeKind::Container, &owner.scope);
root.part = Some(part.to_string());
root.owner = Some(owner.id.clone());
root.owner_component = Some(owner.component.clone());
root.form = owner.form.clone();
root.base_style = obj(style);
root.part_query = Some(RecipeQuery::new(owner.component.clone(), part, self.ctx.recipes.native_recipe_props(&owner.component, &recipe_props(&owner.props, owner.form_disabled)), vec!["open".into()]));
let index = self.push(root);
(layer, index)
}
#[allow(clippy::too_many_arguments)]
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>) {
let class = if matches!(placement, LayerPlacement::Toast { .. }) { LayerClass::Toast } else { LayerClass::Overlay };
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 });
}
}
pub fn row_scope_root(scope: &str) -> Option<&str> {
let rest = scope.strip_prefix("/$row/")?;
let mut end = "/$row/".len();
for (k, part) in rest.splitn(3, '/').enumerate().take(2) {
end += part.len() + usize::from(k == 0);
}
Some(&scope[..end])
}
pub fn builtin_icon(slot: &str) -> Option<&'static str> {
let g = crate::generated::catalog::BUILTIN_ICON_SLOTS.iter().position(|s| *s == slot)?;
crate::generated::catalog::BUILTIN_ICON_NAMES.get(g).copied()
}
pub fn build(root: &UiNode, ctx: &mut BuildContext) -> Built {
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() };
if b.add(root, None, 0, "", false).is_none() {
let mut n = b.blank(&root.id, "Box", None, 0, NodeKind::Container, "");
n.hidden = true;
b.push(n);
}
b.flush_toasts();
b.layers.sort_by_key(|l| (l.class == LayerClass::Toast, l.layer));
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 }
}
pub fn build_subtree(node: &UiNode, parent: &LNode, scope: &str, seed: BuildSeed, ctx: &mut BuildContext) -> Built {
let mut stub = parent.clone();
stub.index = 0;
stub.parent = None;
stub.children.clear();
let layer = stub.layer;
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() };
b.add(node, Some(0), layer, scope, false);
b.flush_toasts();
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 }
}
pub fn motion_size(props: &Props) -> Option<(f64, f64)> {
let pos = |v: Option<&Value>| v.and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0);
let size = props.get("size").and_then(Value::as_array);
let from_size = size.and_then(|a| Some((pos(a.first())?, pos(a.get(1))?)));
from_size.or_else(|| {
let l = props.get("lottie")?;
Some((pos(l.get("w"))?, pos(l.get("h"))?))
})
}
pub fn zoomable_aspect_ratio(props: &Props) -> f64 {
let num = |k: &str| props.get(k).and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0);
match (num("naturalWidth"), num("naturalHeight")) {
(Some(w), Some(h)) if crate::zoom::zoom_is_tall(crate::zoom::ZoomSize { width: w, height: h }) => 1.0,
(Some(w), Some(h)) => w / h,
_ => crate::layout::MEDIA_ASPECT_RATIO,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builtin_glyphs_resolve() {
assert_eq!(builtin_icon("CodeBlock.copy"), Some("ui-copy"));
assert_eq!(builtin_icon("Table.sortIcon.asc"), Some("ui-chevron-up"));
assert_eq!(builtin_icon("Nope.x"), None);
}
#[test]
fn a_zoomable_box_follows_its_picture() {
let p = |v: Value| v.as_object().cloned().unwrap_or_default();
assert!((zoomable_aspect_ratio(&p(json!({"naturalWidth": 1440, "naturalHeight": 900}))) - 1.6).abs() < 1e-9);
assert_eq!(zoomable_aspect_ratio(&p(json!({"naturalWidth": 1000, "naturalHeight": 8000}))), 1.0);
assert!((zoomable_aspect_ratio(&p(json!({"naturalWidth": 600, "naturalHeight": 900}))) - 600.0 / 900.0).abs() < 1e-9);
assert_eq!(zoomable_aspect_ratio(&p(json!({}))), crate::layout::MEDIA_ASPECT_RATIO);
}
}