Skip to main content

tilo_ui_graph/
lib.rs

1//! Pure, versioned schema and structural editor for Tilo serialized UI graphs.
2
3pub mod component;
4mod edit;
5pub mod keys;
6pub mod layout;
7pub mod rich;
8
9pub use edit::{UiGraphEdit, parse_ui_graph_edits};
10
11use serde::{Deserialize, Serialize};
12use std::collections::HashSet;
13
14pub const UI_GRAPH_VERSION: u32 = 1;
15
16/// What a serialized UI graph node's prop must hold, as the component that
17/// reads it declares in its own `GRAPH_PROPS`. `tilolang doctor` reads that
18/// declaration from the component's code, so the contract cannot be lost with
19/// a comment beside it.
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub enum GraphPropKind {
22    /// Any string.
23    Text,
24    /// A non-empty string naming something the app resolves (a model path).
25    Path,
26}
27const MAX_GRAPH_DEPTH: usize = 64;
28const MAX_GRAPH_NODES: usize = 4096;
29const MAX_ID_LEN: usize = 128;
30const MAX_BINDING_LEN: usize = 512;
31const MAX_COMPONENT_NAME_LEN: usize = 128;
32
33#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
34#[serde(deny_unknown_fields)]
35pub struct UiDocument {
36    pub version: u32,
37    pub root: UiNode,
38}
39
40impl UiDocument {
41    #[must_use]
42    pub fn new(root: UiNode) -> Self {
43        Self {
44            version: UI_GRAPH_VERSION,
45            root,
46        }
47    }
48
49    /// Parse and validate a graph before it can reach the widget tree.
50    pub fn from_json(source: &str) -> Result<Self, UiGraphError> {
51        let document: Self = serde_json::from_str(source)?;
52        document.validate()?;
53        Ok(document)
54    }
55
56    /// Serialize the validated graph in a stable, human-readable form.
57    pub fn to_json_pretty(&self) -> Result<String, UiGraphError> {
58        self.validate()?;
59        Ok(serde_json::to_string_pretty(self)?)
60    }
61
62    /// Check version, size, identity, accessibility, binding and geometry invariants for the
63    /// complete graph.
64    ///
65    /// # Errors
66    ///
67    /// The first violated graph invariant.
68    pub fn validate(&self) -> Result<(), UiGraphError> {
69        if self.version != UI_GRAPH_VERSION {
70            return Err(UiGraphError::UnsupportedVersion {
71                found: self.version,
72                supported: UI_GRAPH_VERSION,
73            });
74        }
75        let mut ids = HashSet::new();
76        let mut count = 0_usize;
77        self.root.validate("root", 0, &mut count, &mut ids)
78    }
79
80    #[must_use]
81    pub fn node(&self, id: &str) -> Option<&UiNode> {
82        self.root.find(id)
83    }
84
85    /// Every source node in depth-first builder order.
86    #[must_use]
87    pub fn nodes(&self) -> Vec<&UiNode> {
88        let mut nodes = Vec::new();
89        self.root.collect(&mut nodes);
90        nodes
91    }
92
93    pub fn node_mut(&mut self, id: &str) -> Option<&mut UiNode> {
94        self.root.find_mut(id)
95    }
96
97    /// Insert `node` into a row or column at `index`. The graph changes only after the complete
98    /// candidate validates.
99    pub fn insert_child(
100        &mut self,
101        parent_id: &str,
102        index: usize,
103        node: UiNode,
104    ) -> Result<(), UiGraphError> {
105        self.transaction(|candidate| {
106            let parent = candidate
107                .node_mut(parent_id)
108                .ok_or_else(|| UiGraphError::UnknownNode(parent_id.to_owned()))?;
109            let children = parent
110                .collection_children_mut()
111                .ok_or_else(|| UiGraphError::CannotHaveChildren(parent_id.to_owned()))?;
112            if index > children.len() {
113                return Err(UiGraphError::ChildIndexOutOfBounds {
114                    parent: parent_id.to_owned(),
115                    index,
116                    len: children.len(),
117                });
118            }
119            children.insert(index, node);
120            Ok(())
121        })
122    }
123
124    /// Remove a non-root node and return its complete subtree.
125    ///
126    /// A container's single required child cannot be removed; replace that
127    /// child or remove the container instead.
128    pub fn remove_node(&mut self, id: &str) -> Result<UiNode, UiGraphError> {
129        if self.root.id() == id {
130            return Err(UiGraphError::CannotRemoveRoot);
131        }
132        let mut candidate = self.clone();
133        let removed = candidate
134            .root
135            .detach_descendant(id)?
136            .ok_or_else(|| UiGraphError::UnknownNode(id.to_owned()))?;
137        candidate.validate()?;
138        *self = candidate;
139        Ok(removed)
140    }
141
142    /// Replace a node in place, including the root, with a validated subtree.
143    ///
144    /// # Errors
145    ///
146    /// An unknown target, or any invariant violated by the replacement. A failure leaves the graph
147    /// unchanged.
148    pub fn replace_node(&mut self, id: &str, replacement: UiNode) -> Result<(), UiGraphError> {
149        self.transaction(|candidate| {
150            if candidate.root.id() == id {
151                candidate.root = replacement;
152                return Ok(());
153            }
154            if candidate.root.replace_descendant(id, replacement) {
155                Ok(())
156            } else {
157                Err(UiGraphError::UnknownNode(id.to_owned()))
158            }
159        })
160    }
161
162    /// Reparent a non-root subtree into a row or column. `index` names the position in the
163    /// destination after the source has been detached.
164    ///
165    /// # Errors
166    ///
167    /// Moving the root, moving into the subtree itself, removing a container's required child, an
168    /// invalid parent or index, or another violated invariant. A failure is atomic.
169    pub fn move_node(
170        &mut self,
171        id: &str,
172        new_parent_id: &str,
173        index: usize,
174    ) -> Result<(), UiGraphError> {
175        if self.root.id() == id {
176            return Err(UiGraphError::CannotMoveRoot);
177        }
178        if self
179            .node(id)
180            .is_some_and(|node| node.find(new_parent_id).is_some())
181        {
182            return Err(UiGraphError::MoveIntoDescendant {
183                node: id.to_owned(),
184                parent: new_parent_id.to_owned(),
185            });
186        }
187        self.transaction(|candidate| {
188            let moved = candidate
189                .root
190                .detach_descendant(id)?
191                .ok_or_else(|| UiGraphError::UnknownNode(id.to_owned()))?;
192            let parent = candidate
193                .node_mut(new_parent_id)
194                .ok_or_else(|| UiGraphError::UnknownNode(new_parent_id.to_owned()))?;
195            let children = parent
196                .collection_children_mut()
197                .ok_or_else(|| UiGraphError::CannotHaveChildren(new_parent_id.to_owned()))?;
198            if index > children.len() {
199                return Err(UiGraphError::ChildIndexOutOfBounds {
200                    parent: new_parent_id.to_owned(),
201                    index,
202                    len: children.len(),
203                });
204            }
205            children.insert(index, moved);
206            Ok(())
207        })
208    }
209
210    fn transaction(
211        &mut self,
212        edit: impl FnOnce(&mut Self) -> Result<(), UiGraphError>,
213    ) -> Result<(), UiGraphError> {
214        let mut candidate = self.clone();
215        edit(&mut candidate)?;
216        candidate.validate()?;
217        *self = candidate;
218        Ok(())
219    }
220}
221
222#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
223#[serde(rename_all = "kebab-case")]
224pub enum UiButtonRole {
225    Primary,
226    #[default]
227    Secondary,
228    Destructive,
229    Plain,
230}
231
232#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
233#[serde(rename_all = "kebab-case")]
234pub enum UiTextRole {
235    Display,
236    LargeTitle,
237    Title,
238    Heading,
239    Subheading,
240    #[default]
241    Body,
242    Label,
243    Caption,
244    Reading,
245    Code,
246}
247
248#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
249#[serde(tag = "source", rename_all = "kebab-case", deny_unknown_fields)]
250pub enum UiTextSource {
251    Static { value: String },
252    Document { path: String },
253}
254
255/// Process-local navigation requested by a button.
256#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
257#[serde(tag = "action", rename_all = "kebab-case", deny_unknown_fields)]
258pub enum UiNavigation {
259    Push { route: String },
260    Replace { route: String },
261    Back,
262    Forward,
263}
264
265#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
266#[serde(tag = "type", rename_all = "kebab-case", deny_unknown_fields)]
267pub enum UiNode {
268    Column {
269        id: String,
270        #[serde(default)]
271        children: Vec<UiNode>,
272        #[serde(default)]
273        gap: Option<f32>,
274        #[serde(default)]
275        no_padding: bool,
276        #[serde(default)]
277        intrinsic_height: bool,
278        #[serde(default)]
279        fill_remaining_height: bool,
280    },
281    Row {
282        id: String,
283        #[serde(default)]
284        children: Vec<UiNode>,
285        #[serde(default)]
286        no_wrap: bool,
287        #[serde(default)]
288        fill_remaining_height: bool,
289    },
290    Container {
291        id: String,
292        child: Box<UiNode>,
293        #[serde(default)]
294        background: bool,
295        #[serde(default)]
296        no_padding: bool,
297        #[serde(default)]
298        fill_height: bool,
299        #[serde(default)]
300        width: Option<f32>,
301        #[serde(default)]
302        height: Option<f32>,
303    },
304    Text {
305        id: String,
306        text: UiTextSource,
307        #[serde(default)]
308        role: UiTextRole,
309    },
310    Button {
311        id: String,
312        #[serde(default)]
313        label: String,
314        #[serde(default)]
315        accessible_name: Option<String>,
316        #[serde(default)]
317        tooltip: Option<String>,
318        /// Where a click is reported to the app: the app takes it from the
319        /// graph's `UiValues` by this path and acts on it. The button never
320        /// writes the document.
321        #[serde(default)]
322        on_click_path: Option<String>,
323        /// What a click reports at `on_click_path`; `"true"` when absent.
324        #[serde(default)]
325        click_value: Option<String>,
326        #[serde(default)]
327        navigate: Option<UiNavigation>,
328        #[serde(default = "default_true")]
329        enabled: bool,
330        #[serde(default)]
331        role: UiButtonRole,
332    },
333    TextInput {
334        id: String,
335        /// Optional visible Fluent label. When present it is also the
336        /// control's accessible name, so serialized forms have one source of
337        /// truth for both presentations.
338        #[serde(default, skip_serializing_if = "Option::is_none")]
339        label: Option<String>,
340        #[serde(default, skip_serializing_if = "String::is_empty")]
341        accessible_name: String,
342        #[serde(default)]
343        placeholder: String,
344        #[serde(default)]
345        value_path: Option<String>,
346        #[serde(default)]
347        initial_value: String,
348        #[serde(default)]
349        multiline: bool,
350        #[serde(default)]
351        disabled: bool,
352    },
353    Checkbox {
354        id: String,
355        #[serde(default, skip_serializing_if = "Option::is_none")]
356        label: Option<String>,
357        #[serde(default, skip_serializing_if = "String::is_empty")]
358        accessible_name: String,
359        value_path: String,
360        #[serde(default = "default_true")]
361        enabled: bool,
362    },
363    Toggle {
364        id: String,
365        #[serde(default, skip_serializing_if = "Option::is_none")]
366        label: Option<String>,
367        #[serde(default, skip_serializing_if = "String::is_empty")]
368        accessible_name: String,
369        value_path: String,
370        #[serde(default = "default_true")]
371        enabled: bool,
372    },
373    /// App-owned retained widget built by a process-local component factory.
374    Component {
375        id: String,
376        /// Stable kebab-case factory name registered by the app.
377        name: String,
378        /// Serializable app-defined input passed unchanged to the factory.
379        #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
380        props: serde_json::Map<String, serde_json::Value>,
381    },
382    Spacer {
383        id: String,
384    },
385}
386
387const fn default_true() -> bool {
388    true
389}
390
391impl UiNode {
392    #[must_use]
393    pub fn id(&self) -> &str {
394        match self {
395            Self::Column { id, .. }
396            | Self::Row { id, .. }
397            | Self::Container { id, .. }
398            | Self::Text { id, .. }
399            | Self::Button { id, .. }
400            | Self::TextInput { id, .. }
401            | Self::Checkbox { id, .. }
402            | Self::Toggle { id, .. }
403            | Self::Component { id, .. }
404            | Self::Spacer { id } => id,
405        }
406    }
407
408    pub fn children(&self) -> Vec<&UiNode> {
409        match self {
410            Self::Column { children, .. } | Self::Row { children, .. } => children.iter().collect(),
411            Self::Container { child, .. } => vec![child],
412            _ => Vec::new(),
413        }
414    }
415
416    fn children_mut(&mut self) -> Vec<&mut UiNode> {
417        match self {
418            Self::Column { children, .. } | Self::Row { children, .. } => {
419                children.iter_mut().collect()
420            }
421            Self::Container { child, .. } => vec![child],
422            _ => Vec::new(),
423        }
424    }
425
426    fn collection_children_mut(&mut self) -> Option<&mut Vec<UiNode>> {
427        match self {
428            Self::Column { children, .. } | Self::Row { children, .. } => Some(children),
429            _ => None,
430        }
431    }
432
433    fn detach_descendant(&mut self, id: &str) -> Result<Option<Self>, UiGraphError> {
434        match self {
435            Self::Column { children, .. } | Self::Row { children, .. } => {
436                if let Some(index) = children.iter().position(|child| child.id() == id) {
437                    return Ok(Some(children.remove(index)));
438                }
439                for child in children {
440                    if let Some(removed) = child.detach_descendant(id)? {
441                        return Ok(Some(removed));
442                    }
443                }
444                Ok(None)
445            }
446            Self::Container {
447                id: parent, child, ..
448            } => {
449                if child.id() == id {
450                    Err(UiGraphError::RequiredContainerChild {
451                        parent: parent.clone(),
452                        child: id.to_owned(),
453                    })
454                } else {
455                    child.detach_descendant(id)
456                }
457            }
458            _ => Ok(None),
459        }
460    }
461
462    fn replace_descendant(&mut self, id: &str, replacement: Self) -> bool {
463        match self {
464            Self::Column { children, .. } | Self::Row { children, .. } => {
465                if let Some(child) = children.iter_mut().find(|child| child.id() == id) {
466                    *child = replacement;
467                    return true;
468                }
469                for child in children {
470                    if child.replace_descendant(id, replacement.clone()) {
471                        return true;
472                    }
473                }
474                false
475            }
476            Self::Container { child, .. } => {
477                if child.id() == id {
478                    **child = replacement;
479                    true
480                } else {
481                    child.replace_descendant(id, replacement)
482                }
483            }
484            _ => false,
485        }
486    }
487
488    fn find(&self, id: &str) -> Option<&Self> {
489        if self.id() == id {
490            return Some(self);
491        }
492        self.children().into_iter().find_map(|child| child.find(id))
493    }
494
495    fn find_mut(&mut self, id: &str) -> Option<&mut Self> {
496        if self.id() == id {
497            return Some(self);
498        }
499        self.children_mut()
500            .into_iter()
501            .find_map(|child| child.find_mut(id))
502    }
503
504    fn collect<'a>(&'a self, nodes: &mut Vec<&'a Self>) {
505        nodes.push(self);
506        for child in self.children() {
507            child.collect(nodes);
508        }
509    }
510
511    fn validate(
512        &self,
513        path: &str,
514        depth: usize,
515        count: &mut usize,
516        ids: &mut HashSet<String>,
517    ) -> Result<(), UiGraphError> {
518        if depth > MAX_GRAPH_DEPTH {
519            return Err(UiGraphError::TooDeep {
520                max: MAX_GRAPH_DEPTH,
521            });
522        }
523        *count = count.saturating_add(1);
524        if *count > MAX_GRAPH_NODES {
525            return Err(UiGraphError::TooManyNodes {
526                max: MAX_GRAPH_NODES,
527            });
528        }
529        let id = self.id();
530        if id.trim().is_empty() || id.len() > MAX_ID_LEN {
531            return Err(UiGraphError::InvalidId {
532                path: path.to_owned(),
533                id: id.to_owned(),
534            });
535        }
536        if !ids.insert(id.to_owned()) {
537            return Err(UiGraphError::DuplicateId(id.to_owned()));
538        }
539        match self {
540            Self::Column { gap, .. } => validate_non_negative(*gap, id, "gap")?,
541            Self::Container { width, height, .. } => {
542                validate_positive(*width, id, "width")?;
543                validate_positive(*height, id, "height")?;
544            }
545            Self::Text { text, .. } => {
546                if let UiTextSource::Document { path } = text {
547                    validate_binding(path, id)?;
548                }
549            }
550            Self::Button {
551                label,
552                accessible_name,
553                on_click_path,
554                navigate,
555                ..
556            } => {
557                if label.trim().is_empty()
558                    && accessible_name
559                        .as_deref()
560                        .is_none_or(|name| name.trim().is_empty())
561                {
562                    return Err(UiGraphError::MissingAccessibleName(id.to_owned()));
563                }
564                if let Some(binding) = on_click_path {
565                    validate_binding(binding, id)?;
566                }
567                if let Some(UiNavigation::Push { route } | UiNavigation::Replace { route }) =
568                    navigate
569                {
570                    validate_binding(route, id)?;
571                }
572            }
573            Self::TextInput {
574                label,
575                accessible_name,
576                value_path,
577                ..
578            } => {
579                validate_form_label(label.as_deref(), accessible_name, id)?;
580                if let Some(binding) = value_path {
581                    validate_binding(binding, id)?;
582                }
583            }
584            Self::Checkbox {
585                label,
586                accessible_name,
587                value_path,
588                ..
589            }
590            | Self::Toggle {
591                label,
592                accessible_name,
593                value_path,
594                ..
595            } => {
596                validate_form_label(label.as_deref(), accessible_name, id)?;
597                validate_binding(value_path, id)?;
598            }
599            Self::Component { name, .. } => validate_component_name(name, id)?,
600            Self::Row { .. } | Self::Spacer { .. } => {}
601        }
602        for (index, child) in self.children().into_iter().enumerate() {
603            child.validate(
604                &format!("{path}/{}[{index}]", child.id()),
605                depth.saturating_add(1),
606                count,
607                ids,
608            )?;
609        }
610        Ok(())
611    }
612}
613
614fn validate_component_name(name: &str, id: &str) -> Result<(), UiGraphError> {
615    let bytes = name.as_bytes();
616    let valid = !bytes.is_empty()
617        && bytes.len() <= MAX_COMPONENT_NAME_LEN
618        && bytes.first().is_some_and(u8::is_ascii_lowercase)
619        && bytes.last().is_some_and(u8::is_ascii_alphanumeric)
620        && bytes
621            .iter()
622            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
623        && !bytes.windows(2).any(|pair| pair == b"--");
624    if valid {
625        Ok(())
626    } else {
627        Err(UiGraphError::InvalidComponentName {
628            id: id.to_owned(),
629            name: name.to_owned(),
630        })
631    }
632}
633
634fn validate_accessible_name(name: &str, id: &str) -> Result<(), UiGraphError> {
635    if name.trim().is_empty() {
636        Err(UiGraphError::MissingAccessibleName(id.to_owned()))
637    } else {
638        Ok(())
639    }
640}
641
642fn validate_form_label(
643    label: Option<&str>,
644    accessible_name: &str,
645    id: &str,
646) -> Result<(), UiGraphError> {
647    validate_accessible_name(label.unwrap_or(accessible_name), id)?;
648    if label.is_some() && !accessible_name.trim().is_empty() {
649        Err(UiGraphError::ConflictingLabels(id.to_owned()))
650    } else {
651        Ok(())
652    }
653}
654
655fn validate_binding(binding: &str, id: &str) -> Result<(), UiGraphError> {
656    if binding.trim().is_empty() || binding.len() > MAX_BINDING_LEN {
657        Err(UiGraphError::InvalidBinding {
658            id: id.to_owned(),
659            binding: binding.to_owned(),
660        })
661    } else {
662        Ok(())
663    }
664}
665
666fn validate_positive(value: Option<f32>, id: &str, property: &str) -> Result<(), UiGraphError> {
667    if value.is_some_and(|value| !value.is_finite() || value <= 0.0) {
668        Err(UiGraphError::InvalidDimension {
669            id: id.to_owned(),
670            property: property.to_owned(),
671        })
672    } else {
673        Ok(())
674    }
675}
676
677fn validate_non_negative(value: Option<f32>, id: &str, property: &str) -> Result<(), UiGraphError> {
678    if value.is_some_and(|value| !value.is_finite() || value < 0.0) {
679        Err(UiGraphError::InvalidDimension {
680            id: id.to_owned(),
681            property: property.to_owned(),
682        })
683    } else {
684        Ok(())
685    }
686}
687
688#[derive(Debug, thiserror::Error)]
689pub enum UiGraphError {
690    #[error("UI graph revision space is exhausted; refusing to reuse a prior live state")]
691    RevisionExhausted,
692    #[error("invalid UI graph JSON: {0}")]
693    Json(#[from] serde_json::Error),
694    #[error("UI graph version {found} is unsupported; this toolkit supports {supported}")]
695    UnsupportedVersion { found: u32, supported: u32 },
696    #[error("invalid UI node id {id:?} at {path}")]
697    InvalidId { path: String, id: String },
698    #[error("duplicate UI node id {0:?}")]
699    DuplicateId(String),
700    #[error("UI graph exceeds the maximum nesting depth of {max}")]
701    TooDeep { max: usize },
702    #[error("UI graph exceeds the maximum node count of {max}")]
703    TooManyNodes { max: usize },
704    #[error("UI node {0:?} needs a visible label or accessible name")]
705    MissingAccessibleName(String),
706    #[error("UI node {0:?} must use either label or accessible_name, not both")]
707    ConflictingLabels(String),
708    #[error("UI node {id:?} has invalid model binding {binding:?}")]
709    InvalidBinding { id: String, binding: String },
710    #[error("UI node {id:?} has invalid {property}")]
711    InvalidDimension { id: String, property: String },
712    #[error("UI component node {id:?} has invalid component name {name:?}")]
713    InvalidComponentName { id: String, name: String },
714    #[error("UI component node {id:?} references unregistered component {name:?}")]
715    UnknownComponent { id: String, name: String },
716    #[error("UI component {name:?} at node {id:?} could not be built: {message}")]
717    ComponentBuild {
718        id: String,
719        name: String,
720        message: String,
721    },
722    #[error("UI node {0:?} does not exist")]
723    UnknownNode(String),
724    #[error("UI node {0:?} is not a row or column and cannot accept children")]
725    CannotHaveChildren(String),
726    #[error("child index {index} is outside {parent:?}, which has {len} children")]
727    ChildIndexOutOfBounds {
728        parent: String,
729        index: usize,
730        len: usize,
731    },
732    #[error("the UI graph root cannot be removed")]
733    CannotRemoveRoot,
734    #[error("the UI graph root cannot be moved; replace it instead")]
735    CannotMoveRoot,
736    #[error("cannot remove {child:?}; it is the required child of container {parent:?}")]
737    RequiredContainerChild { parent: String, child: String },
738    #[error("cannot move {node:?} into its own descendant {parent:?}")]
739    MoveIntoDescendant { node: String, parent: String },
740    #[error("UI graph lock was poisoned")]
741    Poisoned,
742    #[error("the UI graph changed while this edit was being prepared; retry against the new graph")]
743    ConcurrentEdit,
744    #[error("UI graph I/O error: {0}")]
745    Io(String),
746    #[error("UI graph edit batch must contain at least one edit")]
747    EmptyEditBatch,
748    #[error("UI graph edit {index} failed: {message}")]
749    EditFailed { index: usize, message: String },
750    #[error("UI node {id:?} has invalid property path {property:?}")]
751    InvalidPropertyPath { id: String, property: String },
752    #[error("UI node {id:?} has no property {property:?}")]
753    UnknownProperty { id: String, property: String },
754    #[error("property {property:?} is not valid for UI node {id:?}: {message}")]
755    InvalidPropertyValue {
756        id: String,
757        property: String,
758        message: String,
759    },
760}
761
762#[cfg(test)]
763mod tests {
764    use super::*;
765
766    fn sample() -> UiDocument {
767        UiDocument::new(UiNode::Column {
768            id: "root".into(),
769            children: vec![
770                UiNode::Text {
771                    id: "title".into(),
772                    text: UiTextSource::Static {
773                        value: "Projects".into(),
774                    },
775                    role: UiTextRole::Title,
776                },
777                UiNode::Row {
778                    id: "actions".into(),
779                    children: Vec::new(),
780                    no_wrap: true,
781                    fill_remaining_height: false,
782                },
783            ],
784            gap: Some(8.0),
785            no_padding: false,
786            intrinsic_height: false,
787            fill_remaining_height: false,
788        })
789    }
790
791    #[test]
792    fn structural_edits_and_components_round_trip_or_leave_the_document_intact() {
793        {
794            let mut document = sample();
795            document
796                .insert_child(
797                    "actions",
798                    0,
799                    UiNode::Button {
800                        id: "create".into(),
801                        label: "Create".into(),
802                        accessible_name: None,
803                        tooltip: None,
804                        on_click_path: Some("create-requested".into()),
805                        click_value: None,
806                        navigate: None,
807                        enabled: true,
808                        role: UiButtonRole::Primary,
809                    },
810                )
811                .unwrap();
812            document.move_node("create", "root", 1).unwrap();
813            let json = document.to_json_pretty().unwrap();
814            let reopened = UiDocument::from_json(&json).unwrap();
815            assert_eq!(reopened, document);
816            assert_eq!(
817                reopened
818                    .nodes()
819                    .iter()
820                    .map(|node| node.id())
821                    .collect::<Vec<_>>(),
822                ["root", "title", "create", "actions"]
823            );
824        }
825        {
826            let document = UiDocument::from_json(
827                r#"{"version":1,"root":{"type":"component","id":"profile","name":"profile-card","props":{"account_id":42,"compact":true}}}"#,
828            )
829            .expect("valid app component");
830            assert!(matches!(
831                document.node("profile"),
832                Some(UiNode::Component { name, props, .. })
833                    if name == "profile-card"
834                        && props.get("account_id") == Some(&serde_json::json!(42))
835                        && props.get("compact") == Some(&serde_json::json!(true))
836            ));
837            assert_eq!(
838                UiDocument::from_json(&document.to_json_pretty().unwrap()).unwrap(),
839                document
840            );
841
842            for name in [
843                "",
844                "ProfileCard",
845                "profile_card",
846                "-profile",
847                "profile--card",
848            ] {
849                let source = format!(
850                    r#"{{"version":1,"root":{{"type":"component","id":"profile","name":{name:?}}}}}"#
851                );
852                assert!(matches!(
853                    UiDocument::from_json(&source),
854                    Err(UiGraphError::InvalidComponentName { .. })
855                ));
856            }
857        }
858        {
859            let mut document = sample();
860            let original = document.clone();
861            assert!(
862                document
863                    .insert_child("root", 0, UiNode::Spacer { id: "title".into() })
864                    .is_err()
865            );
866            assert_eq!(document, original);
867            assert!(document.move_node("root", "actions", 0).is_err());
868            assert_eq!(document, original);
869            assert!(document.remove_node("root").is_err());
870            assert_eq!(document, original);
871        }
872    }
873
874    #[test]
875    fn navigation_and_form_labels_validate_their_targets_and_sources() {
876        {
877            let mut document = sample();
878            document
879                .insert_child(
880                    "actions",
881                    0,
882                    UiNode::Button {
883                        id: "settings".into(),
884                        label: "Settings".into(),
885                        accessible_name: None,
886                        tooltip: None,
887                        on_click_path: None,
888                        click_value: None,
889                        navigate: Some(UiNavigation::Push {
890                            route: "settings".into(),
891                        }),
892                        enabled: true,
893                        role: UiButtonRole::Secondary,
894                    },
895                )
896                .unwrap();
897            let reopened = UiDocument::from_json(&document.to_json_pretty().unwrap()).unwrap();
898            assert_eq!(reopened, document);
899
900            if let Some(UiNode::Button { navigate, .. }) = document.node_mut("settings") {
901                *navigate = Some(UiNavigation::Replace { route: "  ".into() });
902            }
903            assert!(matches!(
904                document.validate(),
905                Err(UiGraphError::InvalidBinding { .. })
906            ));
907        }
908        {
909            let mut document = sample();
910            document
911                .insert_child(
912                    "root",
913                    1,
914                    UiNode::TextInput {
915                        id: "name".into(),
916                        label: Some("profile-name-label".into()),
917                        accessible_name: String::new(),
918                        placeholder: String::new(),
919                        value_path: None,
920                        initial_value: String::new(),
921                        multiline: false,
922                        disabled: false,
923                    },
924                )
925                .unwrap();
926            document
927                .insert_child(
928                    "root",
929                    2,
930                    UiNode::Checkbox {
931                        id: "remember".into(),
932                        label: Some("profile-remember-label".into()),
933                        accessible_name: String::new(),
934                        value_path: "remember".into(),
935                        enabled: true,
936                    },
937                )
938                .unwrap();
939
940            let json = document.to_json_pretty().unwrap();
941            assert!(json.contains(r#""label": "profile-name-label""#));
942            assert!(json.contains(r#""label": "profile-remember-label""#));
943            assert!(!json.contains("accessible_name"));
944            assert_eq!(UiDocument::from_json(&json).unwrap(), document);
945
946            if let Some(UiNode::TextInput {
947                accessible_name, ..
948            }) = document.node_mut("name")
949            {
950                *accessible_name = "duplicate-name".into();
951            }
952            assert!(matches!(
953                document.validate(),
954                Err(UiGraphError::ConflictingLabels(id)) if id == "name"
955            ));
956
957            if let Some(UiNode::TextInput {
958                accessible_name, ..
959            }) = document.node_mut("name")
960            {
961                accessible_name.clear();
962            }
963            if let Some(UiNode::Checkbox {
964                accessible_name, ..
965            }) = document.node_mut("remember")
966            {
967                *accessible_name = "duplicate-check-name".into();
968            }
969            assert!(matches!(
970                document.validate(),
971                Err(UiGraphError::ConflictingLabels(id)) if id == "remember"
972            ));
973        }
974    }
975}