Skip to main content

native_gui_core/
properties.rs

1//! PropertyGrid typed property model — capability groups
2//! P1, P2, P4, and P5.
3//!
4//! A backend-agnostic, Rust-owned model for hierarchical typed properties:
5//! stable [`PropertyId`]s, the portable value/editor vocabulary, categories
6//! and nested children, expansion state, and categorized / category-free
7//! projections, plus the mutation/lookup surface, the staged
8//! [`PropertyEvent::Changing`] veto protocol with default-deny answers, the
9//! ordered [`PropertyEvent`] log, and per-node dirty/validation state.
10//! No widget, no backend method, and no editor rendering lives
11//! here — the future `property-grid` facade (advanced-control RFC) wraps this
12//! model. See `docs/widget-expansion-roadmap.md` ("PropertyGrid typed
13//! property model" and its paragraphs) for the design
14//! and evidence rules.
15//!
16//! # Edit paths
17//!
18//! [`PropertyModel::set_value`] is the programmatic path: it applies
19//! immediately, is blocked only by `read_only`, emits exactly one
20//! [`PropertyEvent::Changed`] per real value change, and emits nothing (and
21//! marks nothing dirty) for a no-op set. The user-edit path is two-phase:
22//! [`PropertyModel::request_change`] stages a [`PendingChange`] and emits
23//! [`PropertyEvent::Changing`]; exactly one of [`PropertyModel::commit_change`]
24//! (applies, emits `Changed`) or a denial
25//! ([`PropertyModel::deny_change`], [`PropertyModel::timeout_change`],
26//! [`PropertyModel::resolve_change`], supersede, or withdrawal) follows, and
27//! a denied proposal never touches the stored value.
28
29use std::collections::{BTreeSet, HashSet};
30use std::fmt;
31
32use crate::widgets::Color;
33
34/// Stable identifier for one node in a [`PropertyModel`].
35///
36/// Ids are minted by the model, never reused, and stay valid across
37/// expansion changes, projection modes, sibling removals, and serde round
38/// trips.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
40#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
41pub struct PropertyId(pub u64);
42
43impl fmt::Display for PropertyId {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        write!(f, "{}", self.0)
46    }
47}
48
49/// The portable property value set (capability group P1).
50#[derive(Debug, Clone, PartialEq)]
51#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
52pub enum PropertyValue {
53    /// Free-form single-line text.
54    Text(String),
55    /// Boolean state.
56    Bool(bool),
57    /// Signed integer.
58    Int(i64),
59    /// Unsigned integer.
60    Uint(u64),
61    /// Floating-point number (must be finite).
62    Float(f64),
63    /// One of a fixed option list; `selected` indexes `options`.
64    Enum {
65        /// Index of the selected option.
66        selected: usize,
67        /// Option labels, in display order.
68        options: Vec<String>,
69    },
70    /// Any number of a fixed option list; `selected` holds sorted, unique
71    /// indices into `options`.
72    Flags {
73        /// Sorted, unique indices of the selected options.
74        selected: Vec<usize>,
75        /// Option labels, in display order.
76        options: Vec<String>,
77    },
78    /// RGB color (the shared [`Color`] type).
79    Color(Color),
80    /// ISO-8601 date text (`YYYY-MM-DD`).
81    Date(String),
82    /// Filesystem path text.
83    Path(String),
84    /// Editor-defined composite value, for example a range (`[Int, Int]`),
85    /// a point (`[Float, Float]`), or a rectangle.
86    Aggregate(Vec<PropertyValue>),
87}
88
89impl PropertyValue {
90    /// Stable lowercase kind identifier used by diagnostics and errors.
91    pub const fn kind_name(&self) -> &'static str {
92        match self {
93            Self::Text(_) => "text",
94            Self::Bool(_) => "bool",
95            Self::Int(_) => "int",
96            Self::Uint(_) => "uint",
97            Self::Float(_) => "float",
98            Self::Enum { .. } => "enum",
99            Self::Flags { .. } => "flags",
100            Self::Color(_) => "color",
101            Self::Date(_) => "date",
102            Self::Path(_) => "path",
103            Self::Aggregate(_) => "aggregate",
104        }
105    }
106
107    /// Whether this value can be edited by `editor`.
108    ///
109    /// Incompatible pairs are rejected at insertion and mutation time; a
110    /// model never accepts a value its editor cannot represent.
111    pub fn is_compatible(&self, editor: PropertyEditor) -> bool {
112        matches!(
113            (self, editor),
114            (Self::Text(_), PropertyEditor::Text)
115                | (Self::Bool(_), PropertyEditor::Checkbox)
116                | (
117                    Self::Int(_) | Self::Uint(_) | Self::Float(_),
118                    PropertyEditor::Numeric
119                )
120                | (
121                    Self::Int(_) | Self::Uint(_) | Self::Float(_),
122                    PropertyEditor::Slider
123                )
124                | (
125                    Self::Enum { .. } | Self::Flags { .. },
126                    PropertyEditor::Choice
127                )
128                | (Self::Color(_), PropertyEditor::Color)
129                | (Self::Date(_), PropertyEditor::Date)
130                | (Self::Path(_), PropertyEditor::Path)
131                | (Self::Aggregate(_), PropertyEditor::Composite)
132        )
133    }
134
135    /// Checks the value's own invariants (indices, sorting, emptiness,
136    /// finiteness). Runs on every insertion/mutation and from
137    /// [`PropertyModel::validate`].
138    pub fn validate(&self) -> PropertyResult<()> {
139        match self {
140            Self::Text(_) | Self::Bool(_) | Self::Int(_) | Self::Uint(_) | Self::Color(_) => Ok(()),
141            Self::Float(value) => {
142                if value.is_finite() {
143                    Ok(())
144                } else {
145                    Err(PropertyError::InvalidValue {
146                        kind: "float",
147                        reason: "value must be finite",
148                    })
149                }
150            }
151            Self::Enum { selected, options } => {
152                if options.is_empty() || *selected >= options.len() {
153                    Err(PropertyError::InvalidValue {
154                        kind: "enum",
155                        reason: "selected index must be within the option list",
156                    })
157                } else {
158                    Ok(())
159                }
160            }
161            Self::Flags { selected, options } => {
162                if options.is_empty() {
163                    return Err(PropertyError::InvalidValue {
164                        kind: "flags",
165                        reason: "option list must not be empty",
166                    });
167                }
168                if selected.windows(2).any(|pair| pair[0] >= pair[1]) {
169                    return Err(PropertyError::InvalidValue {
170                        kind: "flags",
171                        reason: "selected indices must be sorted and unique",
172                    });
173                }
174                if selected.iter().any(|index| *index >= options.len()) {
175                    return Err(PropertyError::InvalidValue {
176                        kind: "flags",
177                        reason: "selected index must be within the option list",
178                    });
179                }
180                Ok(())
181            }
182            Self::Date(text) => {
183                if text.is_empty() {
184                    Err(PropertyError::InvalidValue {
185                        kind: "date",
186                        reason: "date text must not be empty",
187                    })
188                } else {
189                    Ok(())
190                }
191            }
192            Self::Path(text) => {
193                if text.is_empty() {
194                    Err(PropertyError::InvalidValue {
195                        kind: "path",
196                        reason: "path text must not be empty",
197                    })
198                } else {
199                    Ok(())
200                }
201            }
202            Self::Aggregate(values) => {
203                if values.is_empty() {
204                    Err(PropertyError::InvalidValue {
205                        kind: "aggregate",
206                        reason: "aggregate must hold at least one value",
207                    })
208                } else {
209                    values.iter().try_for_each(Self::validate)
210                }
211            }
212        }
213    }
214}
215
216/// Editor family compatible with a [`PropertyValue`] (capability groups P1/P3).
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
218#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
219pub enum PropertyEditor {
220    /// Single-line text editor.
221    Text,
222    /// Checkbox.
223    Checkbox,
224    /// Single-choice dropdown or radio list (`Enum`/`Flags` values).
225    Choice,
226    /// Numeric spinner/entry.
227    Numeric,
228    /// Slider.
229    Slider,
230    /// Color picker.
231    Color,
232    /// Date picker.
233    Date,
234    /// File/directory chooser.
235    Path,
236    /// Composite editor for `Aggregate` values.
237    Composite,
238}
239
240impl PropertyEditor {
241    /// Stable lowercase identifier used by diagnostics and errors.
242    pub const fn as_str(self) -> &'static str {
243        match self {
244            Self::Text => "text",
245            Self::Checkbox => "checkbox",
246            Self::Choice => "choice",
247            Self::Numeric => "numeric",
248            Self::Slider => "slider",
249            Self::Color => "color",
250            Self::Date => "date",
251            Self::Path => "path",
252            Self::Composite => "composite",
253        }
254    }
255}
256
257/// What a node represents: a group row or an editable property.
258#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
259#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
260pub enum PropertyNodeKind {
261    /// Collapsible group row; carries no value.
262    Category,
263    /// Editable property with a value and an editor family.
264    Property,
265}
266
267/// One node in a [`PropertyModel`].
268#[derive(Debug, Clone, PartialEq)]
269#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
270pub struct PropertyNode {
271    /// Stable identifier.
272    pub id: PropertyId,
273    /// Display label.
274    pub label: String,
275    /// Group row or editable property.
276    pub kind: PropertyNodeKind,
277    /// The value (properties only).
278    pub value: Option<PropertyValue>,
279    /// The editor family (properties only).
280    pub editor: Option<PropertyEditor>,
281    /// Parent node, `None` for roots.
282    pub parent: Option<PropertyId>,
283    /// Children in display order.
284    pub children: Vec<PropertyId>,
285    /// Whether the node accepts user edits (default true). The programmatic
286    /// [`PropertyModel::set_value`] path still applies to disabled nodes.
287    #[cfg_attr(feature = "serde", serde(default = "default_enabled"))]
288    pub enabled: bool,
289    /// Whether the node and its subtree are omitted from projections
290    /// (default false).
291    #[cfg_attr(feature = "serde", serde(default))]
292    pub hidden: bool,
293    /// Whether both edit paths reject value changes (default false).
294    #[cfg_attr(feature = "serde", serde(default))]
295    pub read_only: bool,
296    /// Dirty marker set by a real value change; cleared by the application
297    /// through [`PropertyModel::clear_modified`].
298    #[cfg_attr(feature = "serde", serde(default))]
299    pub modified: bool,
300    /// Application-facing validation message (`None` when the value is
301    /// considered valid).
302    #[cfg_attr(feature = "serde", serde(default))]
303    pub validation: Option<String>,
304}
305
306/// Serde default for [`PropertyNode::enabled`].
307#[cfg_attr(not(feature = "serde"), allow(dead_code))]
308const fn default_enabled() -> bool {
309    true
310}
311
312/// How [`PropertyModel::rows`] projects the tree.
313#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
314#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
315pub enum ProjectionMode {
316    /// Emit category group rows (the grouped inspector view).
317    #[default]
318    Categorized,
319    /// Omit category rows; their children surface at the category's depth.
320    CategoryFree,
321}
322
323/// One projected row produced by [`PropertyModel::rows`].
324#[derive(Debug, Clone, PartialEq)]
325pub struct PropertyRow<'a> {
326    /// Stable node id.
327    pub id: PropertyId,
328    /// Depth among the emitted rows (zero for top-level rows).
329    pub depth: usize,
330    /// Whether this row is a category group row.
331    pub category: bool,
332    /// Display label.
333    pub label: &'a str,
334    /// Value (properties only).
335    pub value: Option<&'a PropertyValue>,
336    /// Editor family (properties only).
337    pub editor: Option<PropertyEditor>,
338    /// Whether the node's children are currently shown.
339    pub expanded: bool,
340    /// Whether the node has children.
341    pub has_children: bool,
342    /// Whether the row accepts user edits (disabled rows stay visible).
343    pub enabled: bool,
344    /// Whether both edit paths reject value changes for this row.
345    pub read_only: bool,
346    /// Whether the row carries unsaved changes.
347    pub modified: bool,
348    /// Whether this row is the model's current selection.
349    pub selected: bool,
350    /// Application-facing validation message, when set.
351    pub validation: Option<&'a str>,
352}
353
354/// One-shot handle for a staged [`PropertyModel::request_change`] decision
355/// (P5).
356///
357/// The model mints the token, the application answers it exactly once, and an
358/// unanswered, superseded, or withdrawn token can never apply the change —
359/// the same default-deny shape as the advanced-control
360/// [`DecisionToken`](crate::advanced::DecisionToken) vocabulary.
361#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
362pub struct ChangeToken(pub u64);
363
364impl fmt::Display for ChangeToken {
365    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
366        write!(f, "{}", self.0)
367    }
368}
369
370/// Why a staged change was discarded (P5).
371#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
372pub enum DenialReason {
373    /// The application vetoed the edit ([`PropertyModel::deny_change`]).
374    Vetoed,
375    /// The decision timed out ([`PropertyModel::timeout_change`]).
376    TimedOut,
377    /// No explicit decision was given ([`PropertyModel::resolve_change`]).
378    DefaultDenied,
379    /// A newer [`PropertyModel::request_change`] replaced this one.
380    Superseded,
381    /// The node was removed (or the model cleared) while staged.
382    Withdrawn,
383}
384
385impl DenialReason {
386    /// Stable lowercase identifier used by diagnostics and tests.
387    pub const fn as_str(self) -> &'static str {
388        match self {
389            Self::Vetoed => "vetoed",
390            Self::TimedOut => "timed_out",
391            Self::DefaultDenied => "default_denied",
392            Self::Superseded => "superseded",
393            Self::Withdrawn => "withdrawn",
394        }
395    }
396}
397
398/// A staged user edit awaiting a one-shot decision (P5).
399///
400/// Nothing has been applied while a change is pending: `previous` is still
401/// the stored value, so a denial is a pure rollback that emits no `Changed`
402/// event.
403#[derive(Debug, Clone, PartialEq)]
404pub struct PendingChange {
405    /// One-shot decision handle.
406    pub token: ChangeToken,
407    /// The property being edited.
408    pub id: PropertyId,
409    /// The value still stored (the rollback target).
410    pub previous: PropertyValue,
411    /// The value a commit would install.
412    pub proposed: PropertyValue,
413}
414
415/// One ordered model event (P5).
416///
417/// Events are appended in the exact order transitions happen and are drained
418/// with [`PropertyModel::drain_events`]; rejected operations emit nothing at
419/// all, so a typed error is always the only signal for a rejected edit.
420#[derive(Debug, Clone, PartialEq)]
421pub enum PropertyEvent {
422    /// A node was appended or inserted.
423    Added {
424        /// The new node.
425        id: PropertyId,
426    },
427    /// A subtree was removed: the root first, then descendants in display
428    /// order.
429    Removed {
430        /// Every removed id, root first.
431        ids: Vec<PropertyId>,
432    },
433    /// [`PropertyModel::clear`] dropped every node.
434    Cleared {
435        /// How many nodes were removed.
436        removed: usize,
437    },
438    /// A user edit was staged and awaits a decision; nothing changed yet.
439    Changing {
440        /// One-shot decision handle.
441        token: ChangeToken,
442        /// The property being edited.
443        id: PropertyId,
444        /// The value still stored.
445        previous: PropertyValue,
446        /// The value a commit would install.
447        proposed: PropertyValue,
448    },
449    /// A value change was applied (programmatic path or committed edit).
450    Changed {
451        /// The property that changed.
452        id: PropertyId,
453        /// The value before the change.
454        previous: PropertyValue,
455        /// The value after the change.
456        current: PropertyValue,
457    },
458    /// A staged change was discarded instead of applied.
459    ChangeDenied {
460        /// The token that was answered.
461        token: ChangeToken,
462        /// The property the edit targeted.
463        id: PropertyId,
464        /// Why the edit was discarded.
465        reason: DenialReason,
466    },
467    /// The single selection moved (`current: None` clears it).
468    SelectionChanged {
469        /// The previous selection.
470        previous: Option<PropertyId>,
471        /// The new selection.
472        current: Option<PropertyId>,
473    },
474    /// [`PropertyModel::activate`] fired (programmatic double-click/Enter).
475    Activated {
476        /// The activated node.
477        id: PropertyId,
478    },
479    /// A node expanded or collapsed.
480    ExpansionChanged {
481        /// The node whose expansion state changed.
482        id: PropertyId,
483        /// The new expansion state.
484        expanded: bool,
485    },
486    /// The validation message of a node changed.
487    ValidationChanged {
488        /// The affected node.
489        id: PropertyId,
490        /// The new message (`None` clears the error state).
491        message: Option<String>,
492    },
493}
494
495/// Errors returned by the property model.
496#[derive(Debug, Clone, PartialEq, Eq)]
497pub enum PropertyError {
498    /// The referenced node does not exist.
499    UnknownNode(PropertyId),
500    /// A parent id was given that does not exist in the model.
501    MissingParent(PropertyId),
502    /// The same id appears more than once (only possible through a crafted
503    /// deserialized document; the API mints unique ids).
504    DuplicateId(PropertyId),
505    /// A category was given a value (categories are group rows).
506    CategoryHasNoValue(PropertyId),
507    /// The value and editor cannot be paired.
508    IncompatibleEditor {
509        /// The editor family requested.
510        editor: PropertyEditor,
511        /// The value's kind identifier.
512        value: &'static str,
513    },
514    /// The value violates its own invariants.
515    InvalidValue {
516        /// The value's kind identifier.
517        kind: &'static str,
518        /// Why the value is invalid.
519        reason: &'static str,
520    },
521    /// A read-only node rejected a value change.
522    ReadOnly(PropertyId),
523    /// A disabled node rejected a user edit.
524    Disabled(PropertyId),
525    /// A hidden node rejected an edit, selection, or reveal attempt.
526    Hidden(PropertyId),
527    /// The change token is unknown, already decided, or stale.
528    StaleChange(ChangeToken),
529    /// An insertion index is past the end of the sibling list.
530    InvalidIndex {
531        /// The requested index.
532        index: usize,
533        /// The current sibling count.
534        len: usize,
535    },
536    /// The arena, parent links, and child lists do not agree.
537    InconsistentStructure(&'static str),
538}
539
540impl fmt::Display for PropertyError {
541    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
542        match self {
543            Self::UnknownNode(id) => write!(f, "Property node not found: {id}"),
544            Self::MissingParent(id) => write!(f, "Property parent not found: {id}"),
545            Self::DuplicateId(id) => write!(f, "Duplicate property id: {id}"),
546            Self::CategoryHasNoValue(id) => write!(f, "Property category {id} cannot hold a value"),
547            Self::IncompatibleEditor { editor, value } => {
548                write!(
549                    f,
550                    "Editor {} cannot edit a {} value",
551                    editor.as_str(),
552                    value
553                )
554            }
555            Self::InvalidValue { kind, reason } => {
556                write!(f, "Invalid {kind} value: {reason}")
557            }
558            Self::ReadOnly(id) => write!(f, "Property {id} is read-only"),
559            Self::Disabled(id) => write!(f, "Property {id} is disabled"),
560            Self::Hidden(id) => write!(f, "Property {id} is hidden"),
561            Self::StaleChange(token) => write!(f, "Property change token {token} is stale"),
562            Self::InvalidIndex { index, len } => {
563                write!(
564                    f,
565                    "Insertion index {index} is out of range (siblings: {len})"
566                )
567            }
568            Self::InconsistentStructure(reason) => {
569                write!(f, "Inconsistent property model: {reason}")
570            }
571        }
572    }
573}
574
575impl std::error::Error for PropertyError {}
576
577/// Result type for property model operations.
578pub type PropertyResult<T> = Result<T, PropertyError>;
579
580/// Hierarchical typed property model (capability groups P1, P2, P4, P5).
581///
582/// Construction is additive (`add_category` / `add_property` /
583/// `insert_property`), removal is by subtree, and every mutation validates
584/// value/editor compatibility. Default expansion is expanded; collapse any
585/// node with `set_expanded(id, false)`. Value edits take either the
586/// programmatic path (`set_value`) or the vetoable user path
587/// (`request_change` → `commit_change`/denial); every transition is recorded
588/// in the ordered [`PropertyModel::events`] log.
589///
590/// Equality compares durable state (arena, roots, id counter, collapse set,
591/// selection); the transient event log and any pending change are excluded.
592#[derive(Debug, Clone, Default)]
593#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
594pub struct PropertyModel {
595    nodes: Vec<PropertyNode>,
596    roots: Vec<PropertyId>,
597    next_id: u64,
598    collapsed: BTreeSet<PropertyId>,
599    /// Single stable-id selection (persisted).
600    #[cfg_attr(feature = "serde", serde(default))]
601    selected: Option<PropertyId>,
602    /// Ordered event log; transient and never persisted.
603    #[cfg_attr(feature = "serde", serde(skip))]
604    events: Vec<PropertyEvent>,
605    /// The staged user edit, when one is awaiting a decision.
606    #[cfg_attr(feature = "serde", serde(skip))]
607    pending: Option<PendingChange>,
608    /// Counter for [`ChangeToken`]s; transient and never reused.
609    #[cfg_attr(feature = "serde", serde(skip))]
610    next_change_token: u64,
611}
612
613impl PartialEq for PropertyModel {
614    fn eq(&self, other: &Self) -> bool {
615        self.nodes == other.nodes
616            && self.roots == other.roots
617            && self.next_id == other.next_id
618            && self.collapsed == other.collapsed
619            && self.selected == other.selected
620    }
621}
622
623impl PropertyModel {
624    /// Creates an empty model.
625    pub fn new() -> Self {
626        Self {
627            nodes: Vec::new(),
628            roots: Vec::new(),
629            next_id: 1,
630            collapsed: BTreeSet::new(),
631            selected: None,
632            events: Vec::new(),
633            pending: None,
634            next_change_token: 1,
635        }
636    }
637
638    /// Number of nodes (categories and properties alike).
639    pub fn len(&self) -> usize {
640        self.nodes.len()
641    }
642
643    /// Whether the model holds no nodes.
644    pub fn is_empty(&self) -> bool {
645        self.nodes.is_empty()
646    }
647
648    /// Root ids in insertion order.
649    pub fn roots(&self) -> &[PropertyId] {
650        &self.roots
651    }
652
653    /// Looks a node up by id.
654    pub fn get(&self, id: PropertyId) -> Option<&PropertyNode> {
655        self.nodes.iter().find(|node| node.id == id)
656    }
657
658    /// The value of a property node, when present.
659    pub fn value(&self, id: PropertyId) -> Option<&PropertyValue> {
660        self.get(id).and_then(|node| node.value.as_ref())
661    }
662
663    /// Adds a category group row under `parent` (or at the root).
664    pub fn add_category(
665        &mut self,
666        parent: Option<PropertyId>,
667        label: impl Into<String>,
668    ) -> PropertyResult<PropertyId> {
669        let index = self.sibling_count(parent)?;
670        self.insert(
671            parent,
672            index,
673            label.into(),
674            PropertyNodeKind::Category,
675            None,
676            None,
677        )
678    }
679
680    /// Adds an editable property under `parent` (or at the root).
681    ///
682    /// Rejects incompatible value/editor pairs and invalid values.
683    pub fn add_property(
684        &mut self,
685        parent: Option<PropertyId>,
686        label: impl Into<String>,
687        editor: PropertyEditor,
688        value: PropertyValue,
689    ) -> PropertyResult<PropertyId> {
690        let index = self.sibling_count(parent)?;
691        self.insert_property(parent, index, label, editor, value)
692    }
693
694    /// Inserts an editable property at `index` among the siblings of
695    /// `parent` (or among the roots).
696    ///
697    /// Appends when `index` equals the sibling count; larger indices are the
698    /// typed `InvalidIndex`. Rejects incompatible value/editor pairs and
699    /// invalid values without mutating the model.
700    pub fn insert_property(
701        &mut self,
702        parent: Option<PropertyId>,
703        index: usize,
704        label: impl Into<String>,
705        editor: PropertyEditor,
706        value: PropertyValue,
707    ) -> PropertyResult<PropertyId> {
708        if !value.is_compatible(editor) {
709            return Err(PropertyError::IncompatibleEditor {
710                editor,
711                value: value.kind_name(),
712            });
713        }
714        value.validate()?;
715        self.insert(
716            parent,
717            index,
718            label.into(),
719            PropertyNodeKind::Property,
720            Some(editor),
721            Some(value),
722        )
723    }
724
725    /// Drops every node, resolving dependent state first: a staged change is
726    /// withdrawn, a selection is cleared, and the collapse set resets.
727    ///
728    /// `next_id` never rewinds, so cleared ids are never reused. Returns how
729    /// many nodes were removed; `Cleared` is emitted only for a non-empty
730    /// model.
731    pub fn clear(&mut self) -> usize {
732        let removed = self.nodes.len();
733        self.withdraw_pending_for_subtree(None);
734        self.set_selection_internal(None);
735        self.nodes.clear();
736        self.roots.clear();
737        self.collapsed.clear();
738        if removed > 0 {
739            self.events.push(PropertyEvent::Cleared { removed });
740        }
741        removed
742    }
743
744    /// The model's single selection, when one is set.
745    pub fn selected(&self) -> Option<PropertyId> {
746        self.selected
747    }
748
749    /// Moves the selection; `None` clears it.
750    ///
751    /// Unknown ids are `UnknownNode` and hidden nodes — or nodes under a
752    /// hidden ancestor — are `Hidden`; an unchanged selection emits nothing.
753    pub fn set_selected(&mut self, id: Option<PropertyId>) -> PropertyResult<()> {
754        if let Some(id) = id {
755            if self.get(id).is_none() {
756                return Err(PropertyError::UnknownNode(id));
757            }
758            if let Some(hidden) = self.hidden_hint(id) {
759                return Err(PropertyError::Hidden(hidden));
760            }
761        }
762        self.set_selection_internal(id);
763        Ok(())
764    }
765
766    /// Fires the programmatic activation signal (double-click / Enter on the
767    /// chosen row). Hidden nodes — or nodes under a hidden ancestor — are
768    /// `Hidden`, disabled nodes `Disabled`, unknown ids `UnknownNode`.
769    pub fn activate(&mut self, id: PropertyId) -> PropertyResult<()> {
770        if self.get(id).is_none() {
771            return Err(PropertyError::UnknownNode(id));
772        }
773        if let Some(hidden) = self.hidden_hint(id) {
774            return Err(PropertyError::Hidden(hidden));
775        }
776        if !self.is_enabled(id) {
777            return Err(PropertyError::Disabled(id));
778        }
779        self.events.push(PropertyEvent::Activated { id });
780        Ok(())
781    }
782
783    /// Whether the node accepts user edits (unknown ids read as enabled).
784    pub fn is_enabled(&self, id: PropertyId) -> bool {
785        self.get(id).map(|node| node.enabled).unwrap_or(true)
786    }
787
788    /// Enables or disables user edits on a node. Disabling resolves a
789    /// staged change on that node as `Withdrawn`.
790    pub fn set_enabled(&mut self, id: PropertyId, enabled: bool) -> PropertyResult<()> {
791        if !enabled {
792            self.withdraw_pending_for(id);
793        }
794        self.node_mut(id)?.enabled = enabled;
795        Ok(())
796    }
797
798    /// Whether the node is hidden from projections (unknown ids read as
799    /// visible).
800    pub fn is_hidden(&self, id: PropertyId) -> bool {
801        self.get(id).map(|node| node.hidden).unwrap_or(false)
802    }
803
804    /// Hides or reveals a node and its subtree. Hiding clears a selection
805    /// inside the subtree and resolves a staged change there as `Withdrawn`.
806    pub fn set_hidden(&mut self, id: PropertyId, hidden: bool) -> PropertyResult<()> {
807        if hidden {
808            self.withdraw_pending_for_subtree(Some(id));
809            if let Some(selected) = self.selected {
810                if self.subtree_contains(id, selected) {
811                    self.set_selection_internal(None);
812                }
813            }
814        }
815        self.node_mut(id)?.hidden = hidden;
816        Ok(())
817    }
818
819    /// Whether both edit paths reject value changes (unknown ids read as
820    /// editable).
821    pub fn is_read_only(&self, id: PropertyId) -> bool {
822        self.get(id).map(|node| node.read_only).unwrap_or(false)
823    }
824
825    /// Marks a node read-only (or editable again). Marking read-only
826    /// resolves a staged change on that node as `Withdrawn`. Read-only is
827    /// editability state, so setting the flag itself is never blocked.
828    pub fn set_read_only(&mut self, id: PropertyId, read_only: bool) -> PropertyResult<()> {
829        if read_only {
830            self.withdraw_pending_for(id);
831        }
832        self.node_mut(id)?.read_only = read_only;
833        Ok(())
834    }
835
836    /// Expands every ancestor of `id` (root-most first) so its row can
837    /// appear in a projection.
838    ///
839    /// Emits one `ExpansionChanged` per ancestor that actually expands. A
840    /// node hidden itself — or under a hidden ancestor — is the typed
841    /// `Hidden` error, which names the hidden node.
842    pub fn ensure_visible(&mut self, id: PropertyId) -> PropertyResult<()> {
843        if self.get(id).is_none() {
844            return Err(PropertyError::UnknownNode(id));
845        }
846        if let Some(hidden) = self.hidden_hint(id) {
847            return Err(PropertyError::Hidden(hidden));
848        }
849        let mut ancestors = Vec::new();
850        let mut current = self.get(id).and_then(|node| node.parent);
851        while let Some(parent) = current {
852            ancestors.push(parent);
853            current = self.get(parent).and_then(|node| node.parent);
854        }
855        ancestors.reverse();
856        for ancestor in ancestors {
857            if !self.is_expanded(ancestor) {
858                self.set_expanded(ancestor, true)?;
859            }
860        }
861        Ok(())
862    }
863
864    /// The application-facing validation message for a node, when set.
865    pub fn validation(&self, id: PropertyId) -> Option<&str> {
866        self.get(id).and_then(|node| node.validation.as_deref())
867    }
868
869    /// Sets or clears ([`None`]) the validation message of a node.
870    ///
871    /// Emits `ValidationChanged` only when the message actually changes; an
872    /// unchanged message emits nothing.
873    pub fn set_validation(
874        &mut self,
875        id: PropertyId,
876        message: Option<String>,
877    ) -> PropertyResult<()> {
878        if self.get(id).is_none() {
879            return Err(PropertyError::UnknownNode(id));
880        }
881        if self.validation(id).map(str::to_owned) == message {
882            return Ok(());
883        }
884        self.node_mut(id)?.validation = message.clone();
885        self.events
886            .push(PropertyEvent::ValidationChanged { id, message });
887        Ok(())
888    }
889
890    /// Whether the node carries unsaved changes (unknown ids read as
891    /// unmodified).
892    pub fn is_modified(&self, id: PropertyId) -> bool {
893        self.get(id).map(|node| node.modified).unwrap_or(false)
894    }
895
896    /// How many nodes carry unsaved changes.
897    pub fn modified_count(&self) -> usize {
898        self.nodes.iter().filter(|node| node.modified).count()
899    }
900
901    /// Clears the dirty marker of one node.
902    pub fn clear_modified(&mut self, id: PropertyId) -> PropertyResult<()> {
903        self.node_mut(id)?.modified = false;
904        Ok(())
905    }
906
907    /// Clears every dirty marker and reports how many were set.
908    pub fn clear_all_modified(&mut self) -> usize {
909        let mut cleared = 0;
910        for node in &mut self.nodes {
911            if node.modified {
912                node.modified = false;
913                cleared += 1;
914            }
915        }
916        cleared
917    }
918
919    /// Stages a user edit and returns its one-shot [`ChangeToken`].
920    ///
921    /// Applies the user-path gates (hidden — the node itself or an ancestor,
922    /// then disabled, then read-only), the category guard, and the
923    /// compatibility/value invariants; a rejection mutates nothing and emits
924    /// nothing. On success the proposal is staged, `Changing` is emitted, and
925    /// exactly one decision must follow. A request staged while another is
926    /// pending resolves the first as `Superseded`.
927    pub fn request_change(
928        &mut self,
929        id: PropertyId,
930        proposed: PropertyValue,
931    ) -> PropertyResult<ChangeToken> {
932        if self.get(id).is_none() {
933            return Err(PropertyError::UnknownNode(id));
934        }
935        if let Some(hidden) = self.hidden_hint(id) {
936            return Err(PropertyError::Hidden(hidden));
937        }
938        let (editor, previous) = {
939            let node = self.get(id).ok_or(PropertyError::UnknownNode(id))?;
940            if node.kind == PropertyNodeKind::Category {
941                return Err(PropertyError::CategoryHasNoValue(id));
942            }
943            if !node.enabled {
944                return Err(PropertyError::Disabled(id));
945            }
946            if node.read_only {
947                return Err(PropertyError::ReadOnly(id));
948            }
949            let editor = node.editor.ok_or(PropertyError::InconsistentStructure(
950                "property is missing its editor",
951            ))?;
952            let previous = node
953                .value
954                .clone()
955                .ok_or(PropertyError::InconsistentStructure(
956                    "property is missing its value",
957                ))?;
958            (editor, previous)
959        };
960        if !proposed.is_compatible(editor) {
961            return Err(PropertyError::IncompatibleEditor {
962                editor,
963                value: proposed.kind_name(),
964            });
965        }
966        proposed.validate()?;
967        if let Some(pending) = self.pending.take() {
968            self.events.push(PropertyEvent::ChangeDenied {
969                token: pending.token,
970                id: pending.id,
971                reason: DenialReason::Superseded,
972            });
973        }
974        let token = ChangeToken(self.next_change_token);
975        self.next_change_token = self.next_change_token.saturating_add(1);
976        self.pending = Some(PendingChange {
977            token,
978            id,
979            previous: previous.clone(),
980            proposed: proposed.clone(),
981        });
982        self.events.push(PropertyEvent::Changing {
983            token,
984            id,
985            previous,
986            proposed,
987        });
988        Ok(token)
989    }
990
991    /// The staged change, when one awaits a decision.
992    pub fn pending_change(&self) -> Option<&PendingChange> {
993        self.pending.as_ref()
994    }
995
996    /// Applies a staged change (the `Changing` → `Changed` path).
997    ///
998    /// A commit whose value already equals the stored value emits nothing;
999    /// replaying a decided or unknown token is `StaleChange`.
1000    pub fn commit_change(&mut self, token: ChangeToken) -> PropertyResult<()> {
1001        let pending = self.take_pending(token)?;
1002        let changed = {
1003            let node = self
1004                .nodes
1005                .iter_mut()
1006                .find(|node| node.id == pending.id)
1007                .ok_or(PropertyError::UnknownNode(pending.id))?;
1008            if node.value.as_ref() == Some(&pending.proposed) {
1009                false
1010            } else {
1011                node.value = Some(pending.proposed.clone());
1012                node.modified = true;
1013                true
1014            }
1015        };
1016        if changed {
1017            self.events.push(PropertyEvent::Changed {
1018                id: pending.id,
1019                previous: pending.previous,
1020                current: pending.proposed,
1021            });
1022        }
1023        Ok(())
1024    }
1025
1026    /// Vetoes a staged change; the stored value is untouched.
1027    pub fn deny_change(&mut self, token: ChangeToken) -> PropertyResult<()> {
1028        self.deny_pending(token, DenialReason::Vetoed)
1029    }
1030
1031    /// Resolves a staged change as timed out (default deny).
1032    pub fn timeout_change(&mut self, token: ChangeToken) -> PropertyResult<()> {
1033        self.deny_pending(token, DenialReason::TimedOut)
1034    }
1035
1036    /// Resolves a staged change with no explicit answer (default deny).
1037    pub fn resolve_change(&mut self, token: ChangeToken) -> PropertyResult<()> {
1038        self.deny_pending(token, DenialReason::DefaultDenied)
1039    }
1040
1041    /// The ordered event log (oldest first).
1042    pub fn events(&self) -> &[PropertyEvent] {
1043        &self.events
1044    }
1045
1046    /// Takes every recorded event, leaving the log empty.
1047    pub fn drain_events(&mut self) -> Vec<PropertyEvent> {
1048        std::mem::take(&mut self.events)
1049    }
1050
1051    /// Discards the recorded events without returning them.
1052    pub fn clear_events(&mut self) {
1053        self.events.clear();
1054    }
1055
1056    /// Replaces the value of a property node — the documented programmatic
1057    /// edit path.
1058    ///
1059    /// Applies immediately and is blocked only by `read_only` (typed
1060    /// `ReadOnly`); categories, unknown ids, incompatible editors, and
1061    /// invalid values are rejected without mutation. Exactly one `Changed`
1062    /// event is emitted per real value change and the node is marked
1063    /// `modified`; a no-op set emits nothing and marks nothing.
1064    pub fn set_value(&mut self, id: PropertyId, value: PropertyValue) -> PropertyResult<()> {
1065        let (editor, read_only, previous) = {
1066            let node = self.get(id).ok_or(PropertyError::UnknownNode(id))?;
1067            if node.kind == PropertyNodeKind::Category {
1068                return Err(PropertyError::CategoryHasNoValue(id));
1069            }
1070            let editor = node.editor.ok_or(PropertyError::InconsistentStructure(
1071                "property is missing its editor",
1072            ))?;
1073            let previous = node
1074                .value
1075                .clone()
1076                .ok_or(PropertyError::InconsistentStructure(
1077                    "property is missing its value",
1078                ))?;
1079            (editor, node.read_only, previous)
1080        };
1081        if read_only {
1082            return Err(PropertyError::ReadOnly(id));
1083        }
1084        if !value.is_compatible(editor) {
1085            return Err(PropertyError::IncompatibleEditor {
1086                editor,
1087                value: value.kind_name(),
1088            });
1089        }
1090        value.validate()?;
1091        if previous == value {
1092            return Ok(());
1093        }
1094        let node = self
1095            .nodes
1096            .iter_mut()
1097            .find(|node| node.id == id)
1098            .ok_or(PropertyError::UnknownNode(id))?;
1099        node.value = Some(value.clone());
1100        node.modified = true;
1101        self.events.push(PropertyEvent::Changed {
1102            id,
1103            previous,
1104            current: value,
1105        });
1106        Ok(())
1107    }
1108
1109    /// Removes a node and its whole subtree.
1110    ///
1111    /// Dependent state resolves before the structural event: a staged change
1112    /// under the subtree is `Withdrawn`, a selection inside it is cleared
1113    /// (`SelectionChanged`), and one `Removed` event then lists every removed
1114    /// id, root first.
1115    pub fn remove(&mut self, id: PropertyId) -> PropertyResult<()> {
1116        let Some(node) = self.get(id) else {
1117            return Err(PropertyError::UnknownNode(id));
1118        };
1119        let parent = node.parent;
1120        // Pre-order: the root first, then each child's subtree in display order.
1121        let mut doomed = Vec::new();
1122        let mut stack = vec![id];
1123        while let Some(current) = stack.pop() {
1124            doomed.push(current);
1125            if let Some(node) = self.get(current) {
1126                for child in node.children.iter().rev() {
1127                    stack.push(*child);
1128                }
1129            }
1130        }
1131        self.withdraw_pending_for_subtree(Some(id));
1132        if let Some(selected) = self.selected {
1133            if doomed.contains(&selected) {
1134                self.set_selection_internal(None);
1135            }
1136        }
1137        match parent {
1138            Some(parent) => {
1139                if let Some(node) = self.nodes.iter_mut().find(|node| node.id == parent) {
1140                    node.children.retain(|child| *child != id);
1141                }
1142            }
1143            None => self.roots.retain(|root| *root != id),
1144        }
1145        self.nodes.retain(|node| !doomed.contains(&node.id));
1146        for id in &doomed {
1147            self.collapsed.remove(id);
1148        }
1149        self.events.push(PropertyEvent::Removed { ids: doomed });
1150        Ok(())
1151    }
1152
1153    /// Whether the node's children are currently shown (default: shown).
1154    pub fn is_expanded(&self, id: PropertyId) -> bool {
1155        !self.collapsed.contains(&id)
1156    }
1157
1158    /// Sets the expansion state of a node.
1159    ///
1160    /// Emits `ExpansionChanged` only when the state actually changes.
1161    pub fn set_expanded(&mut self, id: PropertyId, expanded: bool) -> PropertyResult<()> {
1162        if self.get(id).is_none() {
1163            return Err(PropertyError::UnknownNode(id));
1164        }
1165        let changed = if expanded {
1166            self.collapsed.remove(&id)
1167        } else {
1168            self.collapsed.insert(id)
1169        };
1170        if changed {
1171            self.events
1172                .push(PropertyEvent::ExpansionChanged { id, expanded });
1173        }
1174        Ok(())
1175    }
1176
1177    /// Projects the tree into display rows in document order.
1178    ///
1179    /// Hidden nodes and their subtrees are omitted in both modes; collapsed
1180    /// subtrees are skipped; `CategoryFree` omits category rows and surfaces
1181    /// their children at the category's depth.
1182    pub fn rows(&self, mode: ProjectionMode) -> Vec<PropertyRow<'_>> {
1183        let mut rows = Vec::new();
1184        for root in &self.roots {
1185            self.push_rows(*root, 0, mode, &mut rows);
1186        }
1187        rows
1188    }
1189
1190    fn push_rows<'a>(
1191        &'a self,
1192        id: PropertyId,
1193        depth: usize,
1194        mode: ProjectionMode,
1195        rows: &mut Vec<PropertyRow<'a>>,
1196    ) {
1197        let Some(node) = self.get(id) else {
1198            return;
1199        };
1200        if node.hidden {
1201            return;
1202        }
1203        let hidden_category =
1204            node.kind == PropertyNodeKind::Category && mode == ProjectionMode::CategoryFree;
1205        let child_depth = if hidden_category { depth } else { depth + 1 };
1206        if !hidden_category {
1207            rows.push(PropertyRow {
1208                id,
1209                depth,
1210                category: node.kind == PropertyNodeKind::Category,
1211                label: &node.label,
1212                value: node.value.as_ref(),
1213                editor: node.editor,
1214                expanded: self.is_expanded(id),
1215                has_children: !node.children.is_empty(),
1216                enabled: node.enabled,
1217                read_only: node.read_only,
1218                modified: node.modified,
1219                selected: self.selected == Some(id),
1220                validation: node.validation.as_deref(),
1221            });
1222        }
1223        if self.is_expanded(id) {
1224            for child in &node.children {
1225                self.push_rows(*child, child_depth, mode, rows);
1226            }
1227        }
1228    }
1229
1230    /// Verifies every structural and value invariant.
1231    ///
1232    /// This is the deserialization contract: duplicate ids, dangling
1233    /// parents, inconsistent child lists, unreachable nodes, cycles,
1234    /// category values, and invalid value/editor pairs are all rejected.
1235    pub fn validate(&self) -> PropertyResult<()> {
1236        let mut seen = HashSet::new();
1237        for node in &self.nodes {
1238            if !seen.insert(node.id) {
1239                return Err(PropertyError::DuplicateId(node.id));
1240            }
1241        }
1242        // Pass 1: every parent exists (or the node is a root), so a dangling
1243        // parent reports `MissingParent` before downstream link mismatches.
1244        for node in &self.nodes {
1245            match node.parent {
1246                Some(parent) => {
1247                    if self.get(parent).is_none() {
1248                        return Err(PropertyError::MissingParent(parent));
1249                    }
1250                }
1251                None => {
1252                    if !self.roots.contains(&node.id) {
1253                        return Err(PropertyError::InconsistentStructure(
1254                            "parentless node is not a root",
1255                        ));
1256                    }
1257                }
1258            }
1259        }
1260        // Pass 2: child lists agree, and every node's kind/value/editor
1261        // combination is legal.
1262        for node in &self.nodes {
1263            if let Some(parent) = node.parent {
1264                let parent_node = self
1265                    .get(parent)
1266                    .ok_or(PropertyError::MissingParent(parent))?;
1267                if !parent_node.children.contains(&node.id) {
1268                    return Err(PropertyError::InconsistentStructure(
1269                        "child is missing from its parent's children list",
1270                    ));
1271                }
1272            }
1273            for child in &node.children {
1274                let Some(child_node) = self.get(*child) else {
1275                    return Err(PropertyError::MissingParent(*child));
1276                };
1277                if child_node.parent != Some(node.id) {
1278                    return Err(PropertyError::InconsistentStructure(
1279                        "child does not point back to its parent",
1280                    ));
1281                }
1282            }
1283            match node.kind {
1284                PropertyNodeKind::Category => {
1285                    if node.value.is_some() || node.editor.is_some() {
1286                        return Err(PropertyError::CategoryHasNoValue(node.id));
1287                    }
1288                }
1289                PropertyNodeKind::Property => {
1290                    let (Some(value), Some(editor)) = (&node.value, node.editor) else {
1291                        return Err(PropertyError::InconsistentStructure(
1292                            "property is missing its value or editor",
1293                        ));
1294                    };
1295                    if !value.is_compatible(editor) {
1296                        return Err(PropertyError::IncompatibleEditor {
1297                            editor,
1298                            value: value.kind_name(),
1299                        });
1300                    }
1301                    value.validate()?;
1302                }
1303            }
1304        }
1305        for root in &self.roots {
1306            if self.get(*root).is_none() {
1307                return Err(PropertyError::MissingParent(*root));
1308            }
1309        }
1310        let mut reachable = HashSet::new();
1311        let mut stack = self.roots.clone();
1312        while let Some(id) = stack.pop() {
1313            if !reachable.insert(id) {
1314                return Err(PropertyError::InconsistentStructure(
1315                    "node reachable twice (cycle or duplicate child)",
1316                ));
1317            }
1318            if let Some(node) = self.get(id) {
1319                stack.extend(node.children.iter().copied());
1320            }
1321        }
1322        if reachable.len() != self.nodes.len() {
1323            return Err(PropertyError::InconsistentStructure(
1324                "orphan node is not reachable from any root",
1325            ));
1326        }
1327        if let Some(selected) = self.selected {
1328            if self.get(selected).is_none() {
1329                return Err(PropertyError::UnknownNode(selected));
1330            }
1331        }
1332        Ok(())
1333    }
1334
1335    fn insert(
1336        &mut self,
1337        parent: Option<PropertyId>,
1338        index: usize,
1339        label: String,
1340        kind: PropertyNodeKind,
1341        editor: Option<PropertyEditor>,
1342        value: Option<PropertyValue>,
1343    ) -> PropertyResult<PropertyId> {
1344        let len = self.sibling_count(parent)?;
1345        if index > len {
1346            return Err(PropertyError::InvalidIndex { index, len });
1347        }
1348        let id = self.mint_id();
1349        self.nodes.push(PropertyNode {
1350            id,
1351            label,
1352            kind,
1353            value,
1354            editor,
1355            parent,
1356            children: Vec::new(),
1357            enabled: true,
1358            hidden: false,
1359            read_only: false,
1360            modified: false,
1361            validation: None,
1362        });
1363        match parent {
1364            Some(parent) => {
1365                if let Some(node) = self.nodes.iter_mut().find(|node| node.id == parent) {
1366                    node.children.insert(index, id);
1367                }
1368            }
1369            None => self.roots.insert(index, id),
1370        }
1371        self.events.push(PropertyEvent::Added { id });
1372        Ok(id)
1373    }
1374
1375    /// Number of siblings the insertion index refers to; also validates the
1376    /// parent.
1377    fn sibling_count(&self, parent: Option<PropertyId>) -> PropertyResult<usize> {
1378        match parent {
1379            Some(parent) => self
1380                .get(parent)
1381                .map(|node| node.children.len())
1382                .ok_or(PropertyError::MissingParent(parent)),
1383            None => Ok(self.roots.len()),
1384        }
1385    }
1386
1387    fn node_mut(&mut self, id: PropertyId) -> PropertyResult<&mut PropertyNode> {
1388        self.nodes
1389            .iter_mut()
1390            .find(|node| node.id == id)
1391            .ok_or(PropertyError::UnknownNode(id))
1392    }
1393
1394    /// Moves the selection and records the transition; an unchanged
1395    /// selection emits nothing.
1396    fn set_selection_internal(&mut self, next: Option<PropertyId>) {
1397        if self.selected != next {
1398            let previous = self.selected;
1399            self.selected = next;
1400            self.events.push(PropertyEvent::SelectionChanged {
1401                previous,
1402                current: next,
1403            });
1404        }
1405    }
1406
1407    /// Whether `root`'s subtree contains `id` (the root itself included).
1408    fn subtree_contains(&self, root: PropertyId, id: PropertyId) -> bool {
1409        let mut stack = vec![root];
1410        while let Some(current) = stack.pop() {
1411            if current == id {
1412                return true;
1413            }
1414            if let Some(node) = self.get(current) {
1415                stack.extend(node.children.iter().copied());
1416            }
1417        }
1418        false
1419    }
1420
1421    /// The hidden node that hides `id` from projections: `id` itself or its
1422    /// nearest hidden ancestor, when one exists.
1423    fn hidden_hint(&self, id: PropertyId) -> Option<PropertyId> {
1424        let mut current = Some(id);
1425        while let Some(node_id) = current {
1426            let node = self.get(node_id)?;
1427            if node.hidden {
1428                return Some(node_id);
1429            }
1430            current = node.parent;
1431        }
1432        None
1433    }
1434
1435    /// Withdraws a staged change targeting exactly `id`.
1436    fn withdraw_pending_for(&mut self, id: PropertyId) {
1437        if let Some(pending) = self.pending.take() {
1438            if pending.id == id {
1439                self.events.push(PropertyEvent::ChangeDenied {
1440                    token: pending.token,
1441                    id: pending.id,
1442                    reason: DenialReason::Withdrawn,
1443                });
1444            } else {
1445                self.pending = Some(pending);
1446            }
1447        }
1448    }
1449
1450    /// Withdraws a staged change targeting a node inside `root`'s subtree
1451    /// (`None` matches anywhere in the model).
1452    fn withdraw_pending_for_subtree(&mut self, root: Option<PropertyId>) {
1453        if let Some(pending) = self.pending.take() {
1454            let inside = match root {
1455                Some(root) => self.subtree_contains(root, pending.id),
1456                None => true,
1457            };
1458            if inside {
1459                self.events.push(PropertyEvent::ChangeDenied {
1460                    token: pending.token,
1461                    id: pending.id,
1462                    reason: DenialReason::Withdrawn,
1463                });
1464            } else {
1465                self.pending = Some(pending);
1466            }
1467        }
1468    }
1469
1470    /// Takes the staged change matching `token`; stale tokens never resolve
1471    /// anything.
1472    fn take_pending(&mut self, token: ChangeToken) -> PropertyResult<PendingChange> {
1473        match self.pending.take() {
1474            Some(pending) if pending.token == token => Ok(pending),
1475            other => {
1476                self.pending = other;
1477                Err(PropertyError::StaleChange(token))
1478            }
1479        }
1480    }
1481
1482    fn deny_pending(&mut self, token: ChangeToken, reason: DenialReason) -> PropertyResult<()> {
1483        let pending = self.take_pending(token)?;
1484        self.events.push(PropertyEvent::ChangeDenied {
1485            token,
1486            id: pending.id,
1487            reason,
1488        });
1489        Ok(())
1490    }
1491
1492    fn mint_id(&mut self) -> PropertyId {
1493        loop {
1494            let id = PropertyId(self.next_id);
1495            self.next_id = self.next_id.saturating_add(1);
1496            if self.get(id).is_none() {
1497                return id;
1498            }
1499        }
1500    }
1501}
1502
1503#[cfg(test)]
1504mod tests {
1505    use super::*;
1506
1507    fn sample() -> PropertyModel {
1508        let mut model = PropertyModel::new();
1509        let appearance = model.add_category(None, "Appearance").unwrap();
1510        model
1511            .add_property(
1512                Some(appearance),
1513                "Background",
1514                PropertyEditor::Color,
1515                PropertyValue::Color(Color::rgb(28, 105, 190)),
1516            )
1517            .unwrap();
1518        let layout = model.add_category(None, "Layout").unwrap();
1519        model
1520            .add_property(
1521                Some(layout),
1522                "Width",
1523                PropertyEditor::Numeric,
1524                PropertyValue::Int(320),
1525            )
1526            .unwrap();
1527        model
1528    }
1529
1530    #[test]
1531    fn add_and_get_round_trip() {
1532        let model = sample();
1533        assert_eq!(model.len(), 4);
1534        assert_eq!(
1535            model.roots(),
1536            &[
1537                PropertyId(1), // Appearance
1538                PropertyId(3), // Layout
1539            ]
1540        );
1541        let appearance = model.get(PropertyId(1)).unwrap();
1542        assert_eq!(appearance.kind, PropertyNodeKind::Category);
1543        assert_eq!(appearance.children, vec![PropertyId(2)]);
1544        assert!(appearance.value.is_none());
1545        let background = model.get(PropertyId(2)).unwrap();
1546        assert_eq!(background.parent, Some(PropertyId(1)));
1547        assert_eq!(
1548            model.value(PropertyId(2)),
1549            Some(&PropertyValue::Color(Color::rgb(28, 105, 190)))
1550        );
1551        assert!(model.get(PropertyId(99)).is_none());
1552        model.validate().unwrap();
1553    }
1554
1555    #[test]
1556    fn missing_parent_is_rejected() {
1557        let mut model = PropertyModel::new();
1558        assert_eq!(
1559            model.add_category(Some(PropertyId(41)), "Orphan"),
1560            Err(PropertyError::MissingParent(PropertyId(41)))
1561        );
1562        assert_eq!(
1563            model.add_property(
1564                Some(PropertyId(41)),
1565                "Orphan",
1566                PropertyEditor::Text,
1567                PropertyValue::Text("x".to_owned())
1568            ),
1569            Err(PropertyError::MissingParent(PropertyId(41)))
1570        );
1571        assert!(model.is_empty());
1572    }
1573
1574    #[test]
1575    fn nested_properties_are_legal_under_properties() {
1576        let mut model = PropertyModel::new();
1577        let font = model
1578            .add_property(
1579                None,
1580                "Font",
1581                PropertyEditor::Composite,
1582                PropertyValue::Aggregate(vec![
1583                    PropertyValue::Text("Inter".to_owned()),
1584                    PropertyValue::Float(12.0),
1585                ]),
1586            )
1587            .unwrap();
1588        let size = model
1589            .add_property(
1590                Some(font),
1591                "Size",
1592                PropertyEditor::Numeric,
1593                PropertyValue::Float(12.0),
1594            )
1595            .unwrap();
1596        assert_eq!(model.get(size).unwrap().parent, Some(font));
1597        model.validate().unwrap();
1598    }
1599
1600    #[test]
1601    fn ids_are_unique_and_survive_removal() {
1602        let mut model = PropertyModel::new();
1603        let first = model
1604            .add_property(
1605                None,
1606                "A",
1607                PropertyEditor::Text,
1608                PropertyValue::Text("a".to_owned()),
1609            )
1610            .unwrap();
1611        let second = model
1612            .add_property(
1613                None,
1614                "B",
1615                PropertyEditor::Text,
1616                PropertyValue::Text("b".to_owned()),
1617            )
1618            .unwrap();
1619        let third = model
1620            .add_property(
1621                None,
1622                "C",
1623                PropertyEditor::Text,
1624                PropertyValue::Text("c".to_owned()),
1625            )
1626            .unwrap();
1627        assert_ne!(first, second);
1628        assert_ne!(second, third);
1629
1630        model.remove(second).unwrap();
1631        let remaining: Vec<PropertyId> = model
1632            .rows(ProjectionMode::Categorized)
1633            .iter()
1634            .map(|row| row.id)
1635            .collect();
1636        assert_eq!(remaining, vec![first, third]);
1637
1638        // The removed id is never reused.
1639        let fourth = model
1640            .add_property(
1641                None,
1642                "D",
1643                PropertyEditor::Text,
1644                PropertyValue::Text("d".to_owned()),
1645            )
1646            .unwrap();
1647        assert_ne!(fourth, second);
1648        model.validate().unwrap();
1649    }
1650
1651    #[test]
1652    fn remove_drops_the_whole_subtree() {
1653        let mut model = sample();
1654        let appearance = PropertyId(1);
1655        model.remove(appearance).unwrap();
1656        assert!(model.get(appearance).is_none());
1657        assert!(
1658            model.get(PropertyId(2)).is_none(),
1659            "child removed with parent"
1660        );
1661        assert_eq!(model.roots(), &[PropertyId(3)]);
1662        assert_eq!(
1663            model.remove(PropertyId(77)),
1664            Err(PropertyError::UnknownNode(PropertyId(77)))
1665        );
1666        model.validate().unwrap();
1667    }
1668
1669    #[test]
1670    fn incompatible_value_editor_pairs_are_rejected() {
1671        let mut model = sample();
1672        assert_eq!(
1673            model.add_property(
1674                None,
1675                "Broken",
1676                PropertyEditor::Text,
1677                PropertyValue::Bool(true)
1678            ),
1679            Err(PropertyError::IncompatibleEditor {
1680                editor: PropertyEditor::Text,
1681                value: "bool",
1682            })
1683        );
1684        let background = PropertyId(2);
1685        assert_eq!(
1686            model.set_value(background, PropertyValue::Text("blue".to_owned())),
1687            Err(PropertyError::IncompatibleEditor {
1688                editor: PropertyEditor::Color,
1689                value: "text",
1690            })
1691        );
1692        // The failed mutation leaves the stored value untouched.
1693        assert_eq!(
1694            model.value(background),
1695            Some(&PropertyValue::Color(Color::rgb(28, 105, 190)))
1696        );
1697        model.validate().unwrap();
1698    }
1699
1700    #[test]
1701    fn category_values_are_rejected() {
1702        let mut model = sample();
1703        let layout = PropertyId(3);
1704        assert_eq!(
1705            model.set_value(layout, PropertyValue::Int(1)),
1706            Err(PropertyError::CategoryHasNoValue(layout))
1707        );
1708    }
1709
1710    #[test]
1711    fn value_invariants_are_enforced() {
1712        let mut model = PropertyModel::new();
1713        let cases = [
1714            PropertyValue::Enum {
1715                selected: 2,
1716                options: vec!["a".to_owned(), "b".to_owned()],
1717            },
1718            PropertyValue::Flags {
1719                selected: vec![1, 0],
1720                options: vec!["a".to_owned(), "b".to_owned()],
1721            },
1722            PropertyValue::Flags {
1723                selected: vec![3],
1724                options: vec!["a".to_owned(), "b".to_owned()],
1725            },
1726            PropertyValue::Float(f64::NAN),
1727            PropertyValue::Date(String::new()),
1728            PropertyValue::Path(String::new()),
1729            PropertyValue::Aggregate(Vec::new()),
1730        ];
1731        for value in cases {
1732            let kind = value.kind_name();
1733            let editor = match value {
1734                PropertyValue::Enum { .. } | PropertyValue::Flags { .. } => PropertyEditor::Choice,
1735                PropertyValue::Float(_) => PropertyEditor::Numeric,
1736                PropertyValue::Date(_) => PropertyEditor::Date,
1737                PropertyValue::Path(_) => PropertyEditor::Path,
1738                _ => PropertyEditor::Composite,
1739            };
1740            let error = model
1741                .add_property(None, "Bad", editor, value)
1742                .expect_err("invalid value rejected");
1743            assert!(
1744                matches!(error, PropertyError::InvalidValue { kind: k, .. } if k == kind),
1745                "unexpected error for {kind}: {error:?}"
1746            );
1747        }
1748        assert!(model.is_empty());
1749        model.validate().unwrap();
1750    }
1751
1752    #[test]
1753    fn expansion_defaults_to_expanded_and_toggles() {
1754        let mut model = sample();
1755        let appearance = PropertyId(1);
1756        assert!(model.is_expanded(appearance));
1757        model.set_expanded(appearance, false).unwrap();
1758        assert!(!model.is_expanded(appearance));
1759        let ids: Vec<PropertyId> = model
1760            .rows(ProjectionMode::Categorized)
1761            .iter()
1762            .map(|row| row.id)
1763            .collect();
1764        assert_eq!(ids, vec![appearance, PropertyId(3), PropertyId(4)]);
1765        model.set_expanded(appearance, true).unwrap();
1766        let ids: Vec<PropertyId> = model
1767            .rows(ProjectionMode::Categorized)
1768            .iter()
1769            .map(|row| row.id)
1770            .collect();
1771        assert_eq!(
1772            ids,
1773            vec![PropertyId(1), PropertyId(2), PropertyId(3), PropertyId(4)]
1774        );
1775        assert_eq!(
1776            model.set_expanded(PropertyId(88), true),
1777            Err(PropertyError::UnknownNode(PropertyId(88)))
1778        );
1779    }
1780
1781    #[test]
1782    fn category_free_projection_drops_group_rows() {
1783        let mut model = sample();
1784        let rows = model.rows(ProjectionMode::CategoryFree);
1785        let ids: Vec<PropertyId> = rows.iter().map(|row| row.id).collect();
1786        assert_eq!(ids, vec![PropertyId(2), PropertyId(4)]);
1787        assert!(rows.iter().all(|row| !row.category));
1788        assert!(
1789            rows.iter().all(|row| row.depth == 0),
1790            "categories drop out of the depth chain"
1791        );
1792        assert_eq!(rows[0].label, "Background");
1793        assert_eq!(
1794            rows[0].value,
1795            Some(&PropertyValue::Color(Color::rgb(28, 105, 190)))
1796        );
1797
1798        let categorized = model.rows(ProjectionMode::Categorized);
1799        assert_eq!(categorized.len(), 4);
1800        assert_eq!(categorized[1].depth, 1);
1801
1802        // Ids are stable across projection modes.
1803        model.set_expanded(PropertyId(1), false).unwrap();
1804        let collapsed: Vec<PropertyId> = model
1805            .rows(ProjectionMode::CategoryFree)
1806            .iter()
1807            .map(|row| row.id)
1808            .collect();
1809        assert_eq!(
1810            collapsed,
1811            vec![PropertyId(4)],
1812            "collapsed subtrees stay hidden"
1813        );
1814    }
1815
1816    #[test]
1817    fn nested_collapse_hides_only_that_subtree() {
1818        let mut model = PropertyModel::new();
1819        let group = model.add_category(None, "Group").unwrap();
1820        let child = model
1821            .add_property(
1822                Some(group),
1823                "Child",
1824                PropertyEditor::Text,
1825                PropertyValue::Text("c".to_owned()),
1826            )
1827            .unwrap();
1828        let grandchild = model
1829            .add_property(
1830                Some(child),
1831                "Grandchild",
1832                PropertyEditor::Text,
1833                PropertyValue::Text("g".to_owned()),
1834            )
1835            .unwrap();
1836        model.set_expanded(child, false).unwrap();
1837        let ids: Vec<PropertyId> = model
1838            .rows(ProjectionMode::Categorized)
1839            .iter()
1840            .map(|row| row.id)
1841            .collect();
1842        assert_eq!(ids, vec![group, child]);
1843        model.set_expanded(child, true).unwrap();
1844        let ids: Vec<PropertyId> = model
1845            .rows(ProjectionMode::Categorized)
1846            .iter()
1847            .map(|row| row.id)
1848            .collect();
1849        assert_eq!(ids, vec![group, child, grandchild]);
1850        assert!(
1851            model.get(grandchild).is_some(),
1852            "collapse never removes nodes"
1853        );
1854    }
1855
1856    #[test]
1857    #[cfg(feature = "serde")]
1858    fn serde_round_trip_preserves_the_model() {
1859        let mut model = sample();
1860        model.set_expanded(PropertyId(3), false).unwrap();
1861        let json = serde_json::to_string(&model).unwrap();
1862        let parsed: PropertyModel = serde_json::from_str(&json).unwrap();
1863        assert_eq!(parsed, model);
1864        parsed.validate().unwrap();
1865        assert_eq!(
1866            parsed.rows(ProjectionMode::Categorized),
1867            model.rows(ProjectionMode::Categorized)
1868        );
1869    }
1870
1871    #[test]
1872    #[cfg(feature = "serde")]
1873    fn fixture_document_validates_and_projects() {
1874        let fixture = r#"{
1875            "nodes": [
1876                {"id": 1, "label": "Flags", "kind": "Category", "value": null, "editor": null, "parent": null, "children": [2]},
1877                {"id": 2, "label": "Options", "kind": "Property", "value": {"Flags": {"selected": [0, 2], "options": ["bold", "italic", "underline"]}}, "editor": "Choice", "parent": 1, "children": []}
1878            ],
1879            "roots": [1],
1880            "next_id": 3,
1881            "collapsed": []
1882        }"#;
1883        let model: PropertyModel = serde_json::from_str(fixture).unwrap();
1884        model.validate().unwrap();
1885        assert_eq!(model.len(), 2);
1886        assert_eq!(
1887            model.value(PropertyId(2)),
1888            Some(&PropertyValue::Flags {
1889                selected: vec![0, 2],
1890                options: vec![
1891                    "bold".to_owned(),
1892                    "italic".to_owned(),
1893                    "underline".to_owned()
1894                ],
1895            })
1896        );
1897        let rows = model.rows(ProjectionMode::CategoryFree);
1898        assert_eq!(rows.len(), 1);
1899        assert_eq!(rows[0].id, PropertyId(2));
1900    }
1901
1902    #[test]
1903    #[cfg(feature = "serde")]
1904    fn crafted_duplicate_ids_are_rejected() {
1905        let model = sample();
1906        let mut json: serde_json::Value = serde_json::to_value(&model).unwrap();
1907        let nodes = json.get_mut("nodes").unwrap().as_array_mut().unwrap();
1908        nodes[1]["id"] = serde_json::json!(1);
1909        let crafted: PropertyModel = serde_json::from_value(json).unwrap();
1910        assert_eq!(
1911            crafted.validate(),
1912            Err(PropertyError::DuplicateId(PropertyId(1)))
1913        );
1914    }
1915
1916    #[test]
1917    #[cfg(feature = "serde")]
1918    fn crafted_dangling_parent_is_rejected() {
1919        let model = sample();
1920        let mut json: serde_json::Value = serde_json::to_value(&model).unwrap();
1921        let nodes = json.get_mut("nodes").unwrap().as_array_mut().unwrap();
1922        nodes[1]["parent"] = serde_json::json!(999);
1923        let crafted: PropertyModel = serde_json::from_value(json).unwrap();
1924        assert_eq!(
1925            crafted.validate(),
1926            Err(PropertyError::MissingParent(PropertyId(999)))
1927        );
1928    }
1929
1930    #[test]
1931    #[cfg(feature = "serde")]
1932    fn crafted_value_editor_mismatch_is_rejected() {
1933        let model = sample();
1934        let mut json: serde_json::Value = serde_json::to_value(&model).unwrap();
1935        let nodes = json.get_mut("nodes").unwrap().as_array_mut().unwrap();
1936        nodes[1]["value"] = serde_json::json!({"Text": "not a color"});
1937        let crafted: PropertyModel = serde_json::from_value(json).unwrap();
1938        assert_eq!(
1939            crafted.validate(),
1940            Err(PropertyError::IncompatibleEditor {
1941                editor: PropertyEditor::Color,
1942                value: "text",
1943            })
1944        );
1945    }
1946
1947    // --- P4 mutation/lookup and P5 validation/events ---
1948
1949    fn text_property(model: &mut PropertyModel, label: &str, text: &str) -> PropertyId {
1950        model
1951            .add_property(
1952                None,
1953                label,
1954                PropertyEditor::Text,
1955                PropertyValue::Text(text.to_owned()),
1956            )
1957            .unwrap()
1958    }
1959
1960    fn text_property_under(
1961        model: &mut PropertyModel,
1962        parent: PropertyId,
1963        label: &str,
1964        text: &str,
1965    ) -> PropertyId {
1966        model
1967            .add_property(
1968                Some(parent),
1969                label,
1970                PropertyEditor::Text,
1971                PropertyValue::Text(text.to_owned()),
1972            )
1973            .unwrap()
1974    }
1975
1976    fn text_value(text: &str) -> PropertyValue {
1977        PropertyValue::Text(text.to_owned())
1978    }
1979
1980    fn text_of(model: &PropertyModel, id: PropertyId) -> String {
1981        match model.value(id) {
1982            Some(PropertyValue::Text(text)) => text.clone(),
1983            other => panic!("expected a text value for {id}, got {other:?}"),
1984        }
1985    }
1986
1987    #[test]
1988    fn pg_p4_001_append_and_insert_keep_sibling_order() {
1989        let mut model = PropertyModel::new();
1990        let first = text_property(&mut model, "First", "1");
1991        let last = text_property(&mut model, "Last", "2");
1992        let middle = model
1993            .insert_property(None, 1, "Middle", PropertyEditor::Text, text_value("3"))
1994            .unwrap();
1995        assert_eq!(model.roots(), &[first, middle, last]);
1996
1997        let group = model.add_category(None, "Group").unwrap();
1998        let child_b = text_property_under(&mut model, group, "B", "b");
1999        let child_a = model
2000            .insert_property(Some(group), 0, "A", PropertyEditor::Text, text_value("a"))
2001            .unwrap();
2002        assert_eq!(model.get(group).unwrap().children, vec![child_a, child_b]);
2003
2004        assert_eq!(
2005            model.events(),
2006            &[
2007                PropertyEvent::Added { id: first },
2008                PropertyEvent::Added { id: last },
2009                PropertyEvent::Added { id: middle },
2010                PropertyEvent::Added { id: group },
2011                PropertyEvent::Added { id: child_b },
2012                PropertyEvent::Added { id: child_a },
2013            ]
2014        );
2015
2016        // Past-the-end indices are typed and mutate nothing.
2017        assert_eq!(
2018            model.insert_property(None, 99, "Nope", PropertyEditor::Text, text_value("x")),
2019            Err(PropertyError::InvalidIndex { index: 99, len: 4 })
2020        );
2021        assert_eq!(model.len(), 6);
2022        model.validate().unwrap();
2023    }
2024
2025    #[test]
2026    fn pg_p4_002_remove_reports_ids_and_rejects_stale_ones() {
2027        let mut model = PropertyModel::new();
2028        let group = model.add_category(None, "Group").unwrap();
2029        let child = text_property_under(&mut model, group, "Child", "c");
2030        let grandchild = text_property_under(&mut model, child, "Grandchild", "g");
2031        model.clear_events();
2032        model.remove(group).unwrap();
2033        assert_eq!(
2034            model.events(),
2035            &[PropertyEvent::Removed {
2036                ids: vec![group, child, grandchild],
2037            }]
2038        );
2039        assert!(model.is_empty());
2040        assert_eq!(
2041            model.remove(grandchild),
2042            Err(PropertyError::UnknownNode(grandchild))
2043        );
2044        assert!(model.events().len() == 1, "stale removal emits nothing");
2045    }
2046
2047    #[test]
2048    fn pg_p4_003_clear_resets_state_without_reusing_ids() {
2049        let mut model = sample();
2050        let old_root = model.roots()[0];
2051        model.set_selected(Some(old_root)).unwrap();
2052        model.clear_events();
2053        assert_eq!(model.clear(), 4);
2054        assert!(model.is_empty());
2055        assert_eq!(model.selected(), None);
2056        assert_eq!(
2057            model.events(),
2058            &[
2059                PropertyEvent::SelectionChanged {
2060                    previous: Some(old_root),
2061                    current: None,
2062                },
2063                PropertyEvent::Cleared { removed: 4 },
2064            ]
2065        );
2066
2067        // Clearing an empty model is silent.
2068        model.clear_events();
2069        assert_eq!(model.clear(), 0);
2070        assert!(model.events().is_empty());
2071
2072        // Cleared ids are retired: the counter never rewinds.
2073        let fresh = model.add_category(None, "Fresh").unwrap();
2074        assert!(fresh.0 > old_root.0);
2075        model.validate().unwrap();
2076    }
2077
2078    #[test]
2079    fn pg_p4_004_get_and_set_cover_the_lookup_surface() {
2080        let mut model = sample();
2081        let background = PropertyId(2);
2082        assert_eq!(
2083            model.get(background).map(|node| node.label.as_str()),
2084            Some("Background")
2085        );
2086        assert_eq!(
2087            model.value(background),
2088            Some(&PropertyValue::Color(Color::rgb(28, 105, 190)))
2089        );
2090        assert!(
2091            model.value(PropertyId(1)).is_none(),
2092            "categories carry no value"
2093        );
2094        assert_eq!(model.value(PropertyId(77)), None);
2095
2096        model.clear_events();
2097        model
2098            .set_value(background, PropertyValue::Color(Color::rgb(1, 2, 3)))
2099            .unwrap();
2100        assert_eq!(
2101            model.events(),
2102            &[PropertyEvent::Changed {
2103                id: background,
2104                previous: PropertyValue::Color(Color::rgb(28, 105, 190)),
2105                current: PropertyValue::Color(Color::rgb(1, 2, 3)),
2106            }]
2107        );
2108
2109        // A repeated identical set is a no-op: no event.
2110        model.clear_events();
2111        model
2112            .set_value(background, PropertyValue::Color(Color::rgb(1, 2, 3)))
2113            .unwrap();
2114        assert!(model.events().is_empty());
2115        model.validate().unwrap();
2116    }
2117
2118    #[test]
2119    fn pg_p4_005_disabled_nodes_reject_user_edits_only() {
2120        let mut model = PropertyModel::new();
2121        let id = text_property(&mut model, "Name", "a");
2122        model.set_enabled(id, false).unwrap();
2123        assert!(!model.is_enabled(id));
2124        assert_eq!(
2125            model.request_change(id, text_value("b")),
2126            Err(PropertyError::Disabled(id))
2127        );
2128        // The programmatic path still applies to disabled nodes.
2129        model.set_value(id, text_value("b")).unwrap();
2130        assert_eq!(text_of(&model, id), "b");
2131
2132        // Activation needs an enabled node.
2133        assert_eq!(model.activate(id), Err(PropertyError::Disabled(id)));
2134        model.set_enabled(id, true).unwrap();
2135        assert!(model.is_enabled(id));
2136        model.activate(id).unwrap();
2137
2138        // Disabling resolves a staged change on that node as withdrawn.
2139        let token = model.request_change(id, text_value("c")).unwrap();
2140        model.clear_events();
2141        model.set_enabled(id, false).unwrap();
2142        assert_eq!(
2143            model.events(),
2144            &[PropertyEvent::ChangeDenied {
2145                token,
2146                id,
2147                reason: DenialReason::Withdrawn,
2148            }]
2149        );
2150        assert_eq!(text_of(&model, id), "b");
2151        model.validate().unwrap();
2152    }
2153
2154    #[test]
2155    fn pg_p4_006_hidden_subtrees_leave_the_projection() {
2156        let mut model = sample();
2157        let appearance = PropertyId(1);
2158        let background = PropertyId(2);
2159        model.set_selected(Some(background)).unwrap();
2160        model.clear_events();
2161        model.set_hidden(appearance, true).unwrap();
2162        assert!(model.is_hidden(appearance));
2163        // Hiding a category drops its whole subtree from both projections.
2164        assert_eq!(
2165            model
2166                .rows(ProjectionMode::CategoryFree)
2167                .iter()
2168                .map(|row| row.id)
2169                .collect::<Vec<_>>(),
2170            vec![PropertyId(4)]
2171        );
2172        // The selection inside the hidden subtree is cleared first.
2173        assert_eq!(
2174            model.events(),
2175            &[PropertyEvent::SelectionChanged {
2176                previous: Some(background),
2177                current: None,
2178            }]
2179        );
2180        assert_eq!(model.selected(), None);
2181
2182        // Hidden nodes — and nodes under a hidden ancestor — reject user
2183        // edits, selection, and activation; the error names the hidden node.
2184        assert_eq!(
2185            model.request_change(background, PropertyValue::Color(Color::rgb(0, 0, 0))),
2186            Err(PropertyError::Hidden(appearance))
2187        );
2188        assert_eq!(
2189            model.set_selected(Some(background)),
2190            Err(PropertyError::Hidden(appearance))
2191        );
2192        assert_eq!(
2193            model.activate(background),
2194            Err(PropertyError::Hidden(appearance))
2195        );
2196        assert_eq!(
2197            model.set_selected(Some(appearance)),
2198            Err(PropertyError::Hidden(appearance))
2199        );
2200        // The programmatic path still applies.
2201        model
2202            .set_value(background, PropertyValue::Color(Color::rgb(0, 0, 0)))
2203            .unwrap();
2204
2205        // Revealing restores visibility without touching the value.
2206        model.set_hidden(appearance, false).unwrap();
2207        assert!(!model.is_hidden(appearance));
2208        assert_eq!(model.rows(ProjectionMode::CategoryFree).len(), 2);
2209        assert_eq!(
2210            model.value(background),
2211            Some(&PropertyValue::Color(Color::rgb(0, 0, 0)))
2212        );
2213        model.validate().unwrap();
2214    }
2215
2216    #[test]
2217    fn pg_p4_007_read_only_blocks_both_edit_paths() {
2218        let mut model = PropertyModel::new();
2219        let id = text_property(&mut model, "Name", "a");
2220        model.set_read_only(id, true).unwrap();
2221        assert!(model.is_read_only(id));
2222        let recorded = model.events().len();
2223        assert_eq!(
2224            model.set_value(id, text_value("b")),
2225            Err(PropertyError::ReadOnly(id))
2226        );
2227        assert_eq!(
2228            model.request_change(id, text_value("b")),
2229            Err(PropertyError::ReadOnly(id))
2230        );
2231        assert_eq!(text_of(&model, id), "a");
2232        assert_eq!(
2233            model.events().len(),
2234            recorded,
2235            "rejected edits emit no events"
2236        );
2237
2238        // The flag itself can always be toggled; a staged change on a node
2239        // that becomes read-only is withdrawn.
2240        model.set_read_only(id, false).unwrap();
2241        let token = model.request_change(id, text_value("b")).unwrap();
2242        model.clear_events();
2243        model.set_read_only(id, true).unwrap();
2244        assert_eq!(
2245            model.events(),
2246            &[PropertyEvent::ChangeDenied {
2247                token,
2248                id,
2249                reason: DenialReason::Withdrawn,
2250            }]
2251        );
2252        assert_eq!(text_of(&model, id), "a");
2253
2254        // Read-only rows stay visible and carry their state.
2255        let rows = model.rows(ProjectionMode::Categorized);
2256        assert!(rows[0].read_only);
2257        assert!(rows[0].enabled);
2258        model.validate().unwrap();
2259    }
2260
2261    #[test]
2262    fn pg_p4_008_ensure_visible_expands_ancestors_root_first() {
2263        let mut model = PropertyModel::new();
2264        let outer = model.add_category(None, "Outer").unwrap();
2265        let inner = model.add_category(Some(outer), "Inner").unwrap();
2266        let leaf = text_property_under(&mut model, inner, "Leaf", "l");
2267        model.set_expanded(outer, false).unwrap();
2268        model.set_expanded(inner, false).unwrap();
2269        model.clear_events();
2270        model.ensure_visible(leaf).unwrap();
2271        assert_eq!(
2272            model.events(),
2273            &[
2274                PropertyEvent::ExpansionChanged {
2275                    id: outer,
2276                    expanded: true,
2277                },
2278                PropertyEvent::ExpansionChanged {
2279                    id: inner,
2280                    expanded: true,
2281                },
2282            ]
2283        );
2284
2285        // Already-visible nodes emit nothing.
2286        model.clear_events();
2287        model.ensure_visible(leaf).unwrap();
2288        assert!(model.events().is_empty());
2289
2290        // Unknown ids and hidden ancestors are typed errors.
2291        assert_eq!(
2292            model.ensure_visible(PropertyId(99)),
2293            Err(PropertyError::UnknownNode(PropertyId(99)))
2294        );
2295        model.set_hidden(inner, true).unwrap();
2296        assert_eq!(
2297            model.ensure_visible(leaf),
2298            Err(PropertyError::Hidden(inner))
2299        );
2300        assert_eq!(
2301            model.ensure_visible(inner),
2302            Err(PropertyError::Hidden(inner))
2303        );
2304        model.validate().unwrap();
2305    }
2306
2307    #[test]
2308    fn pg_p5_001_changing_precedes_changed() {
2309        let mut model = PropertyModel::new();
2310        let id = text_property(&mut model, "Name", "a");
2311        model.clear_events();
2312        let token = model.request_change(id, text_value("b")).unwrap();
2313        assert_eq!(
2314            model.pending_change(),
2315            Some(&PendingChange {
2316                token,
2317                id,
2318                previous: text_value("a"),
2319                proposed: text_value("b"),
2320            })
2321        );
2322        // Nothing is applied while the change is pending.
2323        assert_eq!(text_of(&model, id), "a");
2324        assert_eq!(
2325            model.events(),
2326            &[PropertyEvent::Changing {
2327                token,
2328                id,
2329                previous: text_value("a"),
2330                proposed: text_value("b"),
2331            }]
2332        );
2333
2334        model.commit_change(token).unwrap();
2335        assert_eq!(text_of(&model, id), "b");
2336        assert!(model.pending_change().is_none());
2337        assert_eq!(
2338            model.events(),
2339            &[
2340                PropertyEvent::Changing {
2341                    token,
2342                    id,
2343                    previous: text_value("a"),
2344                    proposed: text_value("b"),
2345                },
2346                PropertyEvent::Changed {
2347                    id,
2348                    previous: text_value("a"),
2349                    current: text_value("b"),
2350                },
2351            ]
2352        );
2353        assert!(model.is_modified(id));
2354
2355        // Tokens are one-shot.
2356        assert_eq!(
2357            model.commit_change(token),
2358            Err(PropertyError::StaleChange(token))
2359        );
2360        assert_eq!(
2361            model.deny_change(token),
2362            Err(PropertyError::StaleChange(token))
2363        );
2364        model.validate().unwrap();
2365    }
2366
2367    #[test]
2368    fn pg_p5_002_timeout_rolls_back_without_changed_event() {
2369        let mut model = PropertyModel::new();
2370        let id = text_property(&mut model, "Name", "a");
2371        model.clear_events();
2372        let token = model.request_change(id, text_value("b")).unwrap();
2373        model.timeout_change(token).unwrap();
2374        assert_eq!(
2375            model.events(),
2376            &[
2377                PropertyEvent::Changing {
2378                    token,
2379                    id,
2380                    previous: text_value("a"),
2381                    proposed: text_value("b"),
2382                },
2383                PropertyEvent::ChangeDenied {
2384                    token,
2385                    id,
2386                    reason: DenialReason::TimedOut,
2387                },
2388            ]
2389        );
2390        assert_eq!(text_of(&model, id), "a");
2391        assert!(!model.is_modified(id));
2392        assert!(model.pending_change().is_none());
2393        model.validate().unwrap();
2394    }
2395
2396    #[test]
2397    fn pg_p5_003_veto_rolls_back_without_changed_event() {
2398        let mut model = PropertyModel::new();
2399        let id = text_property(&mut model, "Name", "a");
2400        model.clear_events();
2401        let token = model.request_change(id, text_value("b")).unwrap();
2402        model.deny_change(token).unwrap();
2403        assert_eq!(
2404            model.events(),
2405            &[
2406                PropertyEvent::Changing {
2407                    token,
2408                    id,
2409                    previous: text_value("a"),
2410                    proposed: text_value("b"),
2411                },
2412                PropertyEvent::ChangeDenied {
2413                    token,
2414                    id,
2415                    reason: DenialReason::Vetoed,
2416                },
2417            ]
2418        );
2419        assert!(
2420            !model
2421                .events()
2422                .iter()
2423                .any(|event| matches!(event, PropertyEvent::Changed { .. })),
2424            "a vetoed edit never emits Changed"
2425        );
2426        assert_eq!(text_of(&model, id), "a");
2427        assert!(!model.is_modified(id));
2428        model.validate().unwrap();
2429    }
2430
2431    #[test]
2432    fn pg_p5_004_default_deny_and_supersede_resolve_stale_tokens() {
2433        let mut model = PropertyModel::new();
2434        let id = text_property(&mut model, "Name", "a");
2435        model.clear_events();
2436        let undecided = model.request_change(id, text_value("b")).unwrap();
2437        model.resolve_change(undecided).unwrap();
2438        assert_eq!(
2439            model.events().last(),
2440            Some(&PropertyEvent::ChangeDenied {
2441                token: undecided,
2442                id,
2443                reason: DenialReason::DefaultDenied,
2444            })
2445        );
2446        assert_eq!(text_of(&model, id), "a");
2447
2448        // Staging a second request supersedes the first.
2449        let first = model.request_change(id, text_value("b")).unwrap();
2450        model.clear_events();
2451        let second = model.request_change(id, text_value("c")).unwrap();
2452        assert_eq!(
2453            model.events(),
2454            &[
2455                PropertyEvent::ChangeDenied {
2456                    token: first,
2457                    id,
2458                    reason: DenialReason::Superseded,
2459                },
2460                PropertyEvent::Changing {
2461                    token: second,
2462                    id,
2463                    previous: text_value("a"),
2464                    proposed: text_value("c"),
2465                },
2466            ]
2467        );
2468        // A stale token resolves nothing — the live proposal survives.
2469        assert_eq!(
2470            model.commit_change(first),
2471            Err(PropertyError::StaleChange(first))
2472        );
2473        assert!(model.pending_change().is_some());
2474        model.commit_change(second).unwrap();
2475        assert_eq!(text_of(&model, id), "c");
2476        assert!(model.is_modified(id));
2477        model.validate().unwrap();
2478    }
2479
2480    #[test]
2481    fn pg_p5_005_rejected_edits_emit_no_events() {
2482        let mut model = sample();
2483        let background = PropertyId(2);
2484        let when = model
2485            .add_property(
2486                None,
2487                "When",
2488                PropertyEditor::Date,
2489                PropertyValue::Date("2026-01-01".to_owned()),
2490            )
2491            .unwrap();
2492        model.clear_events();
2493
2494        assert_eq!(
2495            model.request_change(background, text_value("not a color")),
2496            Err(PropertyError::IncompatibleEditor {
2497                editor: PropertyEditor::Color,
2498                value: "text",
2499            })
2500        );
2501        assert_eq!(
2502            model.request_change(when, PropertyValue::Date(String::new())),
2503            Err(PropertyError::InvalidValue {
2504                kind: "date",
2505                reason: "date text must not be empty",
2506            })
2507        );
2508        assert_eq!(
2509            model.request_change(PropertyId(77), text_value("x")),
2510            Err(PropertyError::UnknownNode(PropertyId(77)))
2511        );
2512        assert_eq!(
2513            model.request_change(PropertyId(1), PropertyValue::Int(1)),
2514            Err(PropertyError::CategoryHasNoValue(PropertyId(1)))
2515        );
2516        assert_eq!(
2517            model.commit_change(ChangeToken(99)),
2518            Err(PropertyError::StaleChange(ChangeToken(99)))
2519        );
2520        assert_eq!(
2521            model.deny_change(ChangeToken(99)),
2522            Err(PropertyError::StaleChange(ChangeToken(99)))
2523        );
2524
2525        assert!(
2526            model.events().is_empty(),
2527            "rejected operations emit nothing"
2528        );
2529        assert_eq!(
2530            model.value(background),
2531            Some(&PropertyValue::Color(Color::rgb(28, 105, 190)))
2532        );
2533        assert!(model.pending_change().is_none());
2534        model.validate().unwrap();
2535    }
2536
2537    #[test]
2538    fn pg_p5_006_programmatic_set_follows_its_documented_rule() {
2539        let mut model = PropertyModel::new();
2540        let id = text_property(&mut model, "Name", "a");
2541        model.clear_events();
2542        assert_eq!(model.modified_count(), 0);
2543
2544        // One Changed per real value change.
2545        model.set_value(id, text_value("b")).unwrap();
2546        assert_eq!(
2547            model.events(),
2548            &[PropertyEvent::Changed {
2549                id,
2550                previous: text_value("a"),
2551                current: text_value("b"),
2552            }]
2553        );
2554        assert_eq!(model.modified_count(), 1);
2555        assert!(model.is_modified(id));
2556
2557        // A no-op set emits nothing and does not re-dirty a saved node.
2558        assert_eq!(model.clear_all_modified(), 1);
2559        model.clear_events();
2560        model.set_value(id, text_value("b")).unwrap();
2561        assert!(model.events().is_empty());
2562        assert_eq!(model.modified_count(), 0);
2563
2564        // Dirty tracking clears per node or model-wide.
2565        model.set_value(id, text_value("c")).unwrap();
2566        assert_eq!(model.modified_count(), 1);
2567        model.clear_modified(id).unwrap();
2568        assert!(!model.is_modified(id));
2569        assert_eq!(
2570            model.clear_modified(PropertyId(77)),
2571            Err(PropertyError::UnknownNode(PropertyId(77)))
2572        );
2573        model.validate().unwrap();
2574    }
2575
2576    #[test]
2577    fn pg_p5_007_selection_activation_and_expansion_order_is_exact() {
2578        let mut model = sample();
2579        model.clear_events();
2580        model.set_selected(Some(PropertyId(4))).unwrap();
2581        model.set_selected(Some(PropertyId(4))).unwrap();
2582        model.activate(PropertyId(4)).unwrap();
2583        model.set_expanded(PropertyId(3), false).unwrap();
2584        model.set_expanded(PropertyId(3), false).unwrap();
2585        model.set_selected(None).unwrap();
2586        assert_eq!(
2587            model.events(),
2588            &[
2589                PropertyEvent::SelectionChanged {
2590                    previous: None,
2591                    current: Some(PropertyId(4)),
2592                },
2593                PropertyEvent::Activated { id: PropertyId(4) },
2594                PropertyEvent::ExpansionChanged {
2595                    id: PropertyId(3),
2596                    expanded: false,
2597                },
2598                PropertyEvent::SelectionChanged {
2599                    previous: Some(PropertyId(4)),
2600                    current: None,
2601                },
2602            ]
2603        );
2604
2605        // Unknown ids are typed on every interaction path.
2606        assert_eq!(
2607            model.set_selected(Some(PropertyId(88))),
2608            Err(PropertyError::UnknownNode(PropertyId(88)))
2609        );
2610        assert_eq!(
2611            model.activate(PropertyId(88)),
2612            Err(PropertyError::UnknownNode(PropertyId(88)))
2613        );
2614        assert_eq!(model.selected(), None);
2615        model.validate().unwrap();
2616    }
2617
2618    #[test]
2619    fn pg_p5_008_validation_and_dirty_state_are_observable() {
2620        let mut model = PropertyModel::new();
2621        let id = text_property(&mut model, "Name", "a");
2622        model.clear_events();
2623
2624        model
2625            .set_validation(id, Some("must not be empty".to_owned()))
2626            .unwrap();
2627        assert_eq!(model.validation(id), Some("must not be empty"));
2628        // Re-setting the same message emits nothing.
2629        model
2630            .set_validation(id, Some("must not be empty".to_owned()))
2631            .unwrap();
2632        model.set_validation(id, None).unwrap();
2633        assert_eq!(
2634            model.events(),
2635            &[
2636                PropertyEvent::ValidationChanged {
2637                    id,
2638                    message: Some("must not be empty".to_owned()),
2639                },
2640                PropertyEvent::ValidationChanged { id, message: None },
2641            ]
2642        );
2643        assert_eq!(model.validation(id), None);
2644        assert_eq!(
2645            model.set_validation(PropertyId(77), None),
2646            Err(PropertyError::UnknownNode(PropertyId(77)))
2647        );
2648
2649        // Rows carry the interactive state a renderer needs.
2650        model
2651            .set_validation(id, Some("check this".to_owned()))
2652            .unwrap();
2653        model.set_selected(Some(id)).unwrap();
2654        model.set_value(id, text_value("b")).unwrap();
2655        let rows = model.rows(ProjectionMode::Categorized);
2656        assert_eq!(rows.len(), 1);
2657        assert!(rows[0].selected);
2658        assert!(rows[0].modified);
2659        assert_eq!(rows[0].validation, Some("check this"));
2660
2661        // A committed edit dirties the node exactly like the programmatic path.
2662        let token = model.request_change(id, text_value("c")).unwrap();
2663        assert_eq!(model.modified_count(), 1);
2664        model.commit_change(token).unwrap();
2665        assert!(model.is_modified(id));
2666        model.clear_all_modified();
2667        assert_eq!(model.modified_count(), 0);
2668        model.validate().unwrap();
2669    }
2670
2671    #[test]
2672    fn pg_p5_009_removal_and_clear_resolve_pending_state_first() {
2673        let mut model = PropertyModel::new();
2674        let group = model.add_category(None, "Group").unwrap();
2675        let child = text_property_under(&mut model, group, "Child", "c");
2676        let grandchild = text_property_under(&mut model, child, "Grandchild", "g");
2677        model.set_selected(Some(child)).unwrap();
2678        let token = model.request_change(child, text_value("changed")).unwrap();
2679        model.clear_events();
2680
2681        model.remove(group).unwrap();
2682        assert_eq!(
2683            model.events(),
2684            &[
2685                PropertyEvent::ChangeDenied {
2686                    token,
2687                    id: child,
2688                    reason: DenialReason::Withdrawn,
2689                },
2690                PropertyEvent::SelectionChanged {
2691                    previous: Some(child),
2692                    current: None,
2693                },
2694                PropertyEvent::Removed {
2695                    ids: vec![group, child, grandchild],
2696                },
2697            ]
2698        );
2699        assert_eq!(
2700            model.commit_change(token),
2701            Err(PropertyError::StaleChange(token))
2702        );
2703        assert!(model.is_empty());
2704
2705        // `clear` follows the same rule.
2706        let fresh = text_property(&mut model, "Fresh", "f");
2707        model.set_selected(Some(fresh)).unwrap();
2708        let token = model.request_change(fresh, text_value("g")).unwrap();
2709        model.clear_events();
2710        assert_eq!(model.clear(), 1);
2711        assert_eq!(
2712            model.events(),
2713            &[
2714                PropertyEvent::ChangeDenied {
2715                    token,
2716                    id: fresh,
2717                    reason: DenialReason::Withdrawn,
2718                },
2719                PropertyEvent::SelectionChanged {
2720                    previous: Some(fresh),
2721                    current: None,
2722                },
2723                PropertyEvent::Cleared { removed: 1 },
2724            ]
2725        );
2726        assert_eq!(
2727            model.commit_change(token),
2728            Err(PropertyError::StaleChange(token))
2729        );
2730        model.validate().unwrap();
2731    }
2732
2733    #[test]
2734    #[cfg(feature = "serde")]
2735    fn pg_p5_010_events_drain_and_state_survives_serde() {
2736        let mut model = PropertyModel::new();
2737        let id = text_property(&mut model, "Name", "a");
2738        model.set_validation(id, Some("warn".to_owned())).unwrap();
2739        model.set_read_only(id, true).unwrap();
2740        model.set_selected(Some(id)).unwrap();
2741        model.set_value(id, text_value("b")).unwrap_err(); // read-only: rejected
2742
2743        let drained = model.drain_events();
2744        assert_eq!(
2745            drained,
2746            vec![
2747                PropertyEvent::Added { id },
2748                PropertyEvent::ValidationChanged {
2749                    id,
2750                    message: Some("warn".to_owned()),
2751                },
2752                PropertyEvent::SelectionChanged {
2753                    previous: None,
2754                    current: Some(id),
2755                },
2756            ]
2757        );
2758        assert!(model.events().is_empty());
2759
2760        // Durable state round-trips; the transient log and pending change do not.
2761        let json = serde_json::to_string(&model).unwrap();
2762        let parsed: PropertyModel = serde_json::from_str(&json).unwrap();
2763        assert_eq!(parsed, model);
2764        assert!(parsed.events().is_empty());
2765        assert!(parsed.pending_change().is_none());
2766        assert!(parsed.is_read_only(id));
2767        assert_eq!(parsed.selected(), Some(id));
2768        assert_eq!(parsed.validation(id), Some("warn"));
2769        parsed.validate().unwrap();
2770    }
2771}