ailloli_ui_widgets/controls/
tree_view.rs

1//! Interactive snapshot or retained-model tree with selection, editing, drag/drop,
2//! creation/deletion, context menus, shortcuts, and optional row virtualization.
3//!
4//! Snapshot trees can mutate only through a bound node signal. Retained models
5//! own hierarchy/expansion and support intent-only editing workflows; callbacks
6//! carry application actions or receive direct event-context access.
7
8use std::cell::{Cell, RefCell};
9use std::fmt;
10use std::hash::Hash;
11use std::rc::Rc;
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use crate::layout::layout_ext::{apply_layout_size, finish_view_sized, LayoutExt};
16use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
17use ailloli_ui_core::event::{Event, Key, KeyEvent, KeyState, NamedKey};
18use ailloli_ui_core::geometry::{Constraints, Rect, Size};
19use ailloli_ui_core::style::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
20use ailloli_ui_core::{Color, FontId, IconId, Point, TextStyle, Theme};
21use ailloli_ui_runtime::component::{
22    Binding, ComponentNode, Context, IntoView, Signal, View, Widget,
23};
24use ailloli_ui_runtime::input::{EventCtx, FocusPolicy, InputRole};
25use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
26use ailloli_ui_runtime::scene::PaintCtx;
27use ailloli_ui_runtime::{
28    DrawBorder, DrawCmd, DrawImage, DrawRRect, DrawRect, DrawText, Invalidation,
29};
30use ailloli_ui_text::{
31    PreparedTextLayout, TextBuffer, TextEditState, TextLayoutParams, TextSelection, WrapMode,
32};
33use lucide_icons::Icon as LucideIcon;
34
35use super::text_field_core::{
36    handle_single_line_text_event, ime_cursor_rect, paint_single_line_text, TextFieldEventOptions,
37};
38use super::text_input::TextInputStyle;
39use super::tree_model::{TreeModelHandle, TreeModelSubscription, TreeMutation};
40use crate::transactional_layout::TransactionalLayoutPending;
41
42/// Maximum interval between row clicks that can count as activation.
43const TREE_ACTIVATE_MAX_DELAY: Duration = Duration::from_millis(500);
44/// Maximum pointer displacement, in logical pixels, between activation clicks.
45const TREE_ACTIVATE_MAX_DISTANCE: f32 = 4.0;
46/// Extra rows visited above and below a virtual viewport.
47const TREE_VIRTUAL_OVERSCAN_ROWS: usize = 8;
48
49/// Permanent structural counters for a [`TreeView`]. The handle is UI-local
50/// and intentionally cheap to clone into a benchmark or diagnostics panel.
51///
52/// Clones share counters through `Rc<RefCell<_>>`; updates saturate counters.
53///
54/// # Examples
55///
56/// ```
57/// use ailloli_ui_widgets::controls::TreeViewDiagnostics;
58/// let diagnostics = TreeViewDiagnostics::new();
59/// assert_eq!(diagnostics.snapshot().layout_calls, 0);
60/// ```
61#[derive(Clone, Default)]
62pub struct TreeViewDiagnostics {
63    /// Shared single-threaded counters.
64    inner: Rc<RefCell<TreeViewDiagnosticsSnapshot>>,
65}
66
67#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
68/// Point-in-time copy of tree structural/virtualization counters.
69///
70/// Counters are cumulative except `loaded_rows` and `visible_rows`, which report
71/// the latest measured totals/range.
72///
73/// # Examples
74///
75/// ```
76/// use ailloli_ui_widgets::controls::TreeViewDiagnosticsSnapshot;
77/// let snapshot = TreeViewDiagnosticsSnapshot::default();
78/// assert_eq!((snapshot.loaded_rows, snapshot.flatten_rebuilds), (0, 0));
79/// ```
80pub struct TreeViewDiagnosticsSnapshot {
81    /// Saturating number of widget layout calls.
82    pub layout_calls: u64,
83    /// Saturating number of widget paint calls.
84    pub paint_calls: u64,
85    /// Saturating number of row hit-test attempts.
86    pub hit_tests: u64,
87    /// Total source rows observed by the latest layout/paint.
88    pub loaded_rows: usize,
89    /// Rows visited by the latest layout/paint range.
90    pub visible_rows: usize,
91    /// Saturating cumulative rows visited for layout measurement.
92    pub layout_rows_visited: u64,
93    /// Saturating cumulative rows visited for paint.
94    pub paint_rows_visited: u64,
95    /// Saturating cumulative successful single-row hit-test visits.
96    pub hit_test_rows_visited: u64,
97    /// Greatest observed retained rebuild count or snapshot-cache rebuild count.
98    pub flatten_rebuilds: u64,
99    /// Saturating cumulative snapshot rows cloned while rebuilding flat caches.
100    pub snapshot_rows_cloned: u64,
101    /// Saturating cumulative layout rows submitted for text measurement.
102    pub text_measurements: u64,
103    /// Saturating count of virtual layouts falling back to the entire tree.
104    pub virtualization_fallbacks: u64,
105}
106
107impl TreeViewDiagnostics {
108    /// Creates zeroed shared diagnostics.
109    ///
110    /// # Examples
111    ///
112    /// ```
113    /// use ailloli_ui_widgets::controls::TreeViewDiagnostics;
114    /// assert_eq!(TreeViewDiagnostics::new().snapshot(), Default::default());
115    /// ```
116    pub fn new() -> Self {
117        Self::default()
118    }
119
120    /// Copies current counters.
121    ///
122    /// # Panics
123    ///
124    /// Panics if diagnostics are mutably borrowed reentrantly.
125    ///
126    /// # Examples
127    ///
128    /// ```
129    /// use ailloli_ui_widgets::controls::TreeViewDiagnostics;
130    /// let diagnostics = TreeViewDiagnostics::new();
131    /// assert_eq!(diagnostics.snapshot().paint_calls, 0);
132    /// ```
133    pub fn snapshot(&self) -> TreeViewDiagnosticsSnapshot {
134        *self.inner.borrow()
135    }
136
137    /// Applies one internal counter update under a mutable borrow.
138    fn update(&self, update: impl FnOnce(&mut TreeViewDiagnosticsSnapshot)) {
139        update(&mut self.inner.borrow_mut());
140    }
141}
142
143#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
144/// Density preset used to derive [`TreeViewStyle`].
145///
146/// # Examples
147///
148/// ```
149/// use ailloli_ui_widgets::controls::TreeViewSize;
150/// assert_eq!(TreeViewSize::default(), TreeViewSize::Default);
151/// assert_ne!(TreeViewSize::Compact, TreeViewSize::Default);
152/// ```
153pub enum TreeViewSize {
154    /// 24-pixel rows, 8/4-pixel x/y padding, and 16-pixel indentation.
155    Compact,
156    #[default]
157    /// 28-pixel rows, 10/6-pixel x/y padding, and 18-pixel indentation.
158    Default,
159}
160
161#[derive(Clone, Debug, PartialEq)]
162/// Tree surfaces, typography, focus, geometry, and disabled treatment.
163///
164/// Dimensions are logical pixels and values are consumed as supplied. The
165/// default is the regular preset derived from the default theme.
166///
167/// # Examples
168///
169/// ```
170/// use ailloli_ui_widgets::controls::TreeViewStyle;
171/// let style = TreeViewStyle::default();
172/// assert_eq!((style.row_height, style.indent, style.icon_size), (28.0, 18.0, 16.0));
173/// ```
174pub struct TreeViewStyle {
175    /// Optional root surface; transparent by default.
176    pub background: Color,
177    /// Selected-row surface.
178    pub selected_background: Color,
179    /// Focused keyboard-active row surface.
180    pub active_background: Color,
181    /// Reserved hover-row surface token.
182    pub hover_background: Color,
183    /// Reserved pressed-row surface token.
184    pub pressed_background: Color,
185    /// Before/after drop line and inside-drop border.
186    pub drop_indicator: Color,
187    /// Inside-drop row surface.
188    pub drop_inside_background: Color,
189    /// Inline editor surface.
190    pub editing_background: Color,
191    /// Inline editor border/focus color.
192    pub editing_border: Color,
193    /// Normal row text style.
194    pub text: TextStyle,
195    /// Selected row text style.
196    pub selected_text: TextStyle,
197    /// Disabled tree/node text style.
198    pub disabled_text: TextStyle,
199    /// Normal leading-icon tint.
200    pub icon_tint: Color,
201    /// Selected leading/trailing-icon tint.
202    pub selected_icon_tint: Color,
203    /// Branch chevron tint.
204    pub chevron_tint: Color,
205    /// Keyboard-active row border.
206    pub focus_ring: Border,
207    /// Row/root/editor corner radii.
208    pub radius: Radius,
209    /// Row height in logical pixels.
210    pub row_height: f32,
211    /// Outer horizontal content padding in logical pixels.
212    pub padding_x: f32,
213    /// Outer vertical content padding in logical pixels.
214    pub padding_y: f32,
215    /// Per-depth horizontal indentation in logical pixels.
216    pub indent: f32,
217    /// Chevron/icon/text spacing in logical pixels.
218    pub gap: f32,
219    /// Leading/trailing icon side length in logical pixels.
220    pub icon_size: f32,
221    /// Chevron side length in logical pixels.
222    pub chevron_size: f32,
223    /// Whole-tree or per-node disabled alpha multiplier.
224    pub disabled_opacity: f32,
225}
226
227impl Default for TreeViewStyle {
228    fn default() -> Self {
229        Self::from_theme(Theme::default(), TreeViewSize::Default)
230    }
231}
232
233impl TreeViewStyle {
234    /// Derives appearance from `theme` and density geometry.
235    ///
236    /// Compact uses row/padding/indent/text size `24, 8/4, 16, 12`; default uses
237    /// `28, 10/6, 18, 13`.
238    ///
239    /// # Examples
240    ///
241    /// ```
242    /// use ailloli_ui_core::Theme;
243    /// use ailloli_ui_widgets::controls::{TreeViewSize, TreeViewStyle};
244    /// let style = TreeViewStyle::from_theme(Theme::default(), TreeViewSize::Compact);
245    /// assert_eq!((style.row_height, style.padding_x, style.padding_y), (24.0, 8.0, 4.0));
246    /// ```
247    pub fn from_theme(theme: Theme, size: TreeViewSize) -> Self {
248        let palette = theme.palette();
249        let (row_height, padding_x, padding_y, indent, text_size) = match size {
250            TreeViewSize::Compact => (24.0, 8.0, 4.0, 16.0, 12),
251            TreeViewSize::Default => (28.0, 10.0, 6.0, 18.0, 13),
252        };
253        Self {
254            background: Color::TRANSPARENT,
255            selected_background: palette.accent.with_alpha(0.18),
256            active_background: palette.accent.with_alpha(0.10),
257            hover_background: palette.surface_elevated,
258            pressed_background: Color::hex_rgb(0x20252A),
259            drop_indicator: palette.accent,
260            drop_inside_background: palette.accent.with_alpha(0.12),
261            editing_background: palette.surface,
262            editing_border: palette.focus,
263            text: TextStyle::new(FontId::Ui, text_size, palette.text),
264            selected_text: TextStyle::new(FontId::Ui, text_size, palette.text),
265            disabled_text: TextStyle::new(
266                FontId::Ui,
267                text_size,
268                palette.text_muted.with_alpha(0.70),
269            ),
270            icon_tint: palette.text_muted,
271            selected_icon_tint: palette.accent,
272            chevron_tint: palette.text_muted,
273            focus_ring: Border::new(1.0, palette.focus),
274            radius: Radius::uniform(theme.radius().md),
275            row_height,
276            padding_x,
277            padding_y,
278            indent,
279            gap: 6.0,
280            icon_size: 16.0,
281            chevron_size: 14.0,
282            disabled_opacity: 0.42,
283        }
284    }
285}
286
287#[derive(Debug, Clone, Copy, PartialEq, Eq)]
288/// Drop relation between a dragged source and target row.
289///
290/// # Examples
291///
292/// ```
293/// use ailloli_ui_widgets::controls::TreeDropPosition;
294/// assert_eq!([TreeDropPosition::Before, TreeDropPosition::After, TreeDropPosition::Inside].len(), 3);
295/// ```
296pub enum TreeDropPosition {
297    /// Insert as the target's previous sibling.
298    Before,
299    /// Insert as the target's next sibling.
300    After,
301    /// Append as the target's last child.
302    Inside,
303}
304
305#[derive(Debug, Clone, PartialEq, Eq)]
306/// Drag/drop move intent emitted after a valid drop.
307///
308/// # Examples
309///
310/// ```
311/// use ailloli_ui_widgets::controls::{TreeDropPosition, TreeMove};
312/// let event = TreeMove { source: 1, target: 2, position: TreeDropPosition::After };
313/// assert_eq!(event.source, 1);
314/// ```
315pub struct TreeMove<T> {
316    /// Moved subtree ID.
317    pub source: T,
318    /// Drop target row ID.
319    pub target: T,
320    /// Relationship requested around the target.
321    pub position: TreeDropPosition,
322}
323
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325/// Whether editing operations mutate bound snapshot nodes or emit intent only.
326///
327/// # Examples
328///
329/// ```
330/// use ailloli_ui_widgets::controls::TreeMutationMode;
331/// assert_ne!(TreeMutationMode::ApplyLocal, TreeMutationMode::IntentOnly);
332/// ```
333pub enum TreeMutationMode {
334    /// Mutate a bound snapshot node signal before emitting callbacks.
335    ApplyLocal,
336    /// Leave source state unchanged and emit requested operations to the owner.
337    IntentOnly,
338}
339
340#[derive(Debug, Clone, PartialEq, Eq)]
341/// Supported platform-neutral keyboard command intent.
342///
343/// Paste carries the selected/active target ID or `None` when no target exists.
344///
345/// # Examples
346///
347/// ```
348/// use ailloli_ui_widgets::controls::TreeShortcut;
349/// let shortcut = TreeShortcut::<u8>::Paste { id: None };
350/// assert!(matches!(shortcut, TreeShortcut::Paste { id: None }));
351/// ```
352pub enum TreeShortcut<T> {
353    /// Delete key with an enabled target.
354    Delete {
355        /// Selected or active item to delete.
356        id: T,
357    },
358    /// Control-C with an enabled target.
359    Copy {
360        /// Selected or active item to copy.
361        id: T,
362    },
363    /// Control-X with an enabled target.
364    Cut {
365        /// Selected or active item to cut.
366        id: T,
367    },
368    /// Control-V with an optional enabled target.
369    Paste {
370        /// Destination item, or `None` when the tree has no active target.
371        id: Option<T>,
372    },
373}
374
375#[derive(Debug, Clone, PartialEq, Eq)]
376/// Committed rename intent with trimmed replacement label.
377///
378/// # Examples
379///
380/// ```
381/// use ailloli_ui_widgets::controls::TreeRename;
382/// let rename = TreeRename { id: 1, old_label: "old".into(), new_label: "new".into() };
383/// assert_eq!(rename.new_label, "new");
384/// ```
385pub struct TreeRename<T> {
386    /// Renamed node ID.
387    pub id: T,
388    /// Label before local mutation.
389    pub old_label: String,
390    /// Trimmed committed label.
391    pub new_label: String,
392}
393
394#[derive(Debug, Clone, Copy, PartialEq, Eq)]
395/// Placement requested by tree creation commands.
396///
397/// # Examples
398///
399/// ```
400/// use ailloli_ui_widgets::controls::TreeCreateKind;
401/// assert_ne!(TreeCreateKind::SiblingAfter, TreeCreateKind::Child);
402/// ```
403pub enum TreeCreateKind {
404    /// Insert after a sibling, or append a root when `after` is absent.
405    SiblingAfter,
406    /// Append below the requested parent.
407    Child,
408}
409
410#[derive(Debug, Clone, PartialEq, Eq)]
411/// Input to a user-provided new-node factory.
412///
413/// # Examples
414///
415/// ```
416/// use ailloli_ui_widgets::controls::{TreeCreateKind, TreeCreateRequest};
417/// let request = TreeCreateRequest { parent: Some(1), after: None, kind: TreeCreateKind::Child, default_label: "New item".into() };
418/// assert_eq!(request.parent, Some(1));
419/// ```
420pub struct TreeCreateRequest<T> {
421    /// Parent ID, or `None` for a root-level sibling.
422    pub parent: Option<T>,
423    /// Previous sibling ID for sibling insertion, if any.
424    pub after: Option<T>,
425    /// Sibling or child placement.
426    pub kind: TreeCreateKind,
427    /// Suggested initial editor label.
428    pub default_label: String,
429}
430
431#[derive(Debug, Clone, PartialEq, Eq)]
432/// Successfully committed create intent.
433///
434/// # Examples
435///
436/// ```
437/// use ailloli_ui_widgets::controls::{TreeCreate, TreeCreateKind};
438/// let event = TreeCreate { id: 2, parent: Some(1), after: None, kind: TreeCreateKind::Child, label: "file".into() };
439/// assert_eq!(event.label, "file");
440/// ```
441pub struct TreeCreate<T> {
442    /// Factory-provided new node ID.
443    pub id: T,
444    /// Requested parent ID.
445    pub parent: Option<T>,
446    /// Requested previous sibling ID.
447    pub after: Option<T>,
448    /// Requested placement kind.
449    pub kind: TreeCreateKind,
450    /// Trimmed committed label.
451    pub label: String,
452}
453
454#[derive(Debug, Clone, PartialEq, Eq)]
455/// Cancellation of an in-progress create editor.
456///
457/// # Examples
458///
459/// ```
460/// use ailloli_ui_widgets::controls::{TreeCreateCancel, TreeCreateKind, TreeCreateRequest};
461/// let request = TreeCreateRequest { parent: None, after: None, kind: TreeCreateKind::SiblingAfter, default_label: "New item".into() };
462/// let event = TreeCreateCancel { id: 9, request };
463/// assert_eq!(event.id, 9);
464/// ```
465pub struct TreeCreateCancel<T> {
466    /// Factory-provided draft ID.
467    pub id: T,
468    /// Original creation request.
469    pub request: TreeCreateRequest<T>,
470}
471
472#[derive(Debug, Clone, PartialEq, Eq)]
473/// Delete intent for one node/subtree.
474///
475/// # Examples
476///
477/// ```
478/// use ailloli_ui_widgets::controls::TreeDelete;
479/// let event = TreeDelete { id: 2, parent: Some(1) };
480/// assert_eq!(event.parent, Some(1));
481/// ```
482pub struct TreeDelete<T> {
483    /// Deleted subtree root ID.
484    pub id: T,
485    /// Parent ID before deletion, or `None` for a root.
486    pub parent: Option<T>,
487}
488
489#[derive(Debug, Clone, PartialEq)]
490/// Right-click context carrying pointer geometry for a row or blank area.
491///
492/// # Examples
493///
494/// ```
495/// use ailloli_ui_core::Point;
496/// use ailloli_ui_widgets::controls::TreeContextMenu;
497/// let event = TreeContextMenu::<u8>::Blank { pointer_position: Point::new(2.0, 3.0) };
498/// assert!(matches!(event, TreeContextMenu::Blank { .. }));
499/// ```
500pub enum TreeContextMenu<T> {
501    /// Enabled row context; the row is selected first when necessary.
502    Row {
503        /// Context row ID.
504        row_id: T,
505        /// Pointer location in window coordinates.
506        pointer_position: Point,
507        /// Hit row rectangle in window coordinates.
508        row_rect: Rect,
509    },
510    /// Context request inside tree bounds but outside a row.
511    Blank {
512        /// Pointer location in window coordinates.
513        pointer_position: Point,
514    },
515}
516
517#[derive(Debug, Clone, PartialEq, Eq)]
518/// One-shot externally bound editor command.
519///
520/// The widget consumes a present command by resetting its signal to `None`
521/// during layout or the next routed event.
522///
523/// # Examples
524///
525/// ```
526/// use ailloli_ui_widgets::controls::TreeViewCommand;
527/// let command = TreeViewCommand::BeginRename(4_u8);
528/// assert!(matches!(command, TreeViewCommand::BeginRename(4)));
529/// ```
530pub enum TreeViewCommand<T> {
531    /// Begin editing the visible enabled node with this ID when allowed.
532    BeginRename(T),
533    /// Run the create factory and begin editing the resulting node when allowed.
534    BeginCreate(TreeCreateRequest<T>),
535}
536
537#[derive(Debug, Clone, PartialEq, Eq)]
538/// Icon and optional tooltip metadata for a selected row's trailing action.
539///
540/// # Examples
541///
542/// ```
543/// use ailloli_ui_core::IconId;
544/// use ailloli_ui_widgets::controls::TreeNodeTrailingAction;
545/// let action = TreeNodeTrailingAction::new(IconId::Close).tooltip("Remove");
546/// assert_eq!(action.tooltip.as_deref(), Some("Remove"));
547/// ```
548pub struct TreeNodeTrailingAction {
549    /// Painted action icon.
550    pub icon: IconId,
551    /// Optional presentation tooltip; the tree itself does not display it.
552    pub tooltip: Option<String>,
553}
554
555impl TreeNodeTrailingAction {
556    /// Creates action metadata without a tooltip.
557    ///
558    /// # Examples
559    ///
560    /// ```
561    /// use ailloli_ui_core::IconId;
562    /// use ailloli_ui_widgets::controls::TreeNodeTrailingAction;
563    /// assert!(TreeNodeTrailingAction::new(IconId::Close).tooltip.is_none());
564    /// ```
565    pub fn new(icon: IconId) -> Self {
566        Self {
567            icon,
568            tooltip: None,
569        }
570    }
571
572    /// Sets tooltip metadata, replacing any previous value.
573    ///
574    /// # Examples
575    ///
576    /// ```
577    /// use ailloli_ui_core::IconId;
578    /// use ailloli_ui_widgets::controls::TreeNodeTrailingAction;
579    /// let action = TreeNodeTrailingAction::new(IconId::Close).tooltip("Delete");
580    /// assert_eq!(action.tooltip.as_deref(), Some("Delete"));
581    /// ```
582    pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self {
583        self.tooltip = Some(tooltip.into());
584        self
585    }
586}
587
588#[derive(Clone)]
589/// Recursive snapshot-tree node with static/reactive disabled state.
590///
591/// IDs should be unique for deterministic lookup, but snapshot construction does
592/// not validate uniqueness. Adding any child promotes a leaf to a branch.
593///
594/// # Examples
595///
596/// ```
597/// use ailloli_ui_widgets::controls::TreeNode;
598/// let node = TreeNode::branch(1, "src").child(TreeNode::leaf(2, "lib.rs"));
599/// assert_eq!(node.child_nodes().len(), 1);
600/// ```
601pub struct TreeNode<T> {
602    /// Application-defined node ID.
603    id: T,
604    /// Display label stored unchanged.
605    label: String,
606    /// Explicit branch flag; children also imply branch behavior.
607    branch: bool,
608    /// Child nodes in display order.
609    children: Vec<TreeNode<T>>,
610    /// Static or reactive unavailable state.
611    disabled: Binding<bool>,
612    /// Optional leading icon.
613    leading_icon: Option<IconId>,
614    /// Optional leading-icon tint override.
615    leading_icon_tint: Option<Color>,
616    /// Optional selected-row trailing action metadata.
617    trailing_action: Option<TreeNodeTrailingAction>,
618    /// Whether this node represents provisional UI state.
619    transient: bool,
620}
621
622impl<T> TreeNode<T> {
623    /// Creates an enabled empty branch with no icons/action.
624    ///
625    /// # Examples
626    ///
627    /// ```
628    /// use ailloli_ui_widgets::controls::TreeNode;
629    /// let node = TreeNode::branch("root", "Root");
630    /// assert!(node.child_nodes().is_empty());
631    /// ```
632    pub fn branch(id: T, label: impl Into<String>) -> Self {
633        Self {
634            id,
635            label: label.into(),
636            branch: true,
637            children: Vec::new(),
638            disabled: Binding::Static(false),
639            leading_icon: None,
640            leading_icon_tint: None,
641            trailing_action: None,
642            transient: false,
643        }
644    }
645
646    /// Creates an enabled childless leaf with no icons/action.
647    ///
648    /// # Examples
649    ///
650    /// ```
651    /// use ailloli_ui_widgets::controls::TreeNode;
652    /// let node = TreeNode::leaf(1, "README");
653    /// assert_eq!(node.label(), "README");
654    /// ```
655    pub fn leaf(id: T, label: impl Into<String>) -> Self {
656        Self {
657            id,
658            label: label.into(),
659            branch: false,
660            children: Vec::new(),
661            disabled: Binding::Static(false),
662            leading_icon: None,
663            leading_icon_tint: None,
664            trailing_action: None,
665            transient: false,
666        }
667    }
668
669    /// Appends one child and promotes this node to a branch.
670    ///
671    /// # Examples
672    ///
673    /// ```
674    /// use ailloli_ui_widgets::controls::TreeNode;
675    /// let node = TreeNode::leaf(1, "parent").child(TreeNode::leaf(2, "child"));
676    /// assert_eq!(node.child_nodes()[0].id(), &2);
677    /// ```
678    pub fn child(mut self, child: TreeNode<T>) -> Self {
679        self.branch = true;
680        self.children.push(child);
681        self
682    }
683
684    /// Extends children in iterator order without clearing existing children.
685    ///
686    /// A nonempty input promotes this node to a branch; empty input preserves its
687    /// current branch flag.
688    ///
689    /// # Examples
690    ///
691    /// ```
692    /// use ailloli_ui_widgets::controls::TreeNode;
693    /// let node = TreeNode::branch(1, "root").children([TreeNode::leaf(2, "a"), TreeNode::leaf(3, "b")]);
694    /// assert_eq!(node.child_nodes().len(), 2);
695    /// ```
696    pub fn children(mut self, children: impl IntoIterator<Item = TreeNode<T>>) -> Self {
697        let children = children.into_iter().collect::<Vec<_>>();
698        if !children.is_empty() {
699            self.branch = true;
700        }
701        self.children.extend(children);
702        self
703    }
704
705    /// Sets static or reactive unavailable state.
706    ///
707    /// Disabled nodes are skipped by selection/navigation/editing/drop targets.
708    ///
709    /// # Examples
710    ///
711    /// ```
712    /// use ailloli_ui_widgets::controls::TreeNode;
713    /// let node = TreeNode::leaf(1, "locked").disabled(true);
714    /// let _ = node;
715    /// ```
716    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
717        self.disabled = disabled.into();
718        self
719    }
720
721    /// Sets the leading icon, replacing any previous icon.
722    ///
723    /// # Examples
724    ///
725    /// ```
726    /// use ailloli_ui_core::IconId;
727    /// use ailloli_ui_widgets::controls::TreeNode;
728    /// let node = TreeNode::leaf(1, "file").leading_icon(IconId::History);
729    /// let _ = node;
730    /// ```
731    pub fn leading_icon(mut self, icon: IconId) -> Self {
732        self.leading_icon = Some(icon);
733        self
734    }
735
736    /// Sets a leading-icon tint override.
737    ///
738    /// # Examples
739    ///
740    /// ```
741    /// use ailloli_ui_core::Color;
742    /// use ailloli_ui_widgets::controls::TreeNode;
743    /// let node = TreeNode::leaf(1, "file").leading_icon_tint(Color::WHITE);
744    /// let _ = node;
745    /// ```
746    pub fn leading_icon_tint(mut self, color: Color) -> Self {
747        self.leading_icon_tint = Some(color);
748        self
749    }
750
751    /// Marks or unmarks provisional presentation state.
752    ///
753    /// The tree retains this metadata but otherwise treats the node normally.
754    ///
755    /// # Examples
756    ///
757    /// ```
758    /// use ailloli_ui_widgets::controls::TreeNode;
759    /// assert!(TreeNode::leaf(1, "draft").transient(true).is_transient());
760    /// ```
761    pub fn transient(mut self, transient: bool) -> Self {
762        self.transient = transient;
763        self
764    }
765
766    /// Sets a tooltip-free trailing action.
767    ///
768    /// It is painted and hit-testable only while this row is selected.
769    ///
770    /// # Examples
771    ///
772    /// ```
773    /// use ailloli_ui_core::IconId;
774    /// use ailloli_ui_widgets::controls::TreeNode;
775    /// let node = TreeNode::leaf(1, "file").trailing_action(IconId::Close);
776    /// assert!(node.trailing_action_ref().is_some());
777    /// ```
778    pub fn trailing_action(mut self, icon: IconId) -> Self {
779        self.trailing_action = Some(TreeNodeTrailingAction::new(icon));
780        self
781    }
782
783    /// Sets a trailing action with retained tooltip metadata.
784    ///
785    /// The tree does not itself render the tooltip.
786    ///
787    /// # Examples
788    ///
789    /// ```
790    /// use ailloli_ui_core::IconId;
791    /// use ailloli_ui_widgets::controls::TreeNode;
792    /// let node = TreeNode::leaf(1, "file").trailing_action_with_tooltip(IconId::Close, "Remove");
793    /// assert_eq!(node.trailing_action_ref().unwrap().tooltip.as_deref(), Some("Remove"));
794    /// ```
795    pub fn trailing_action_with_tooltip(
796        mut self,
797        icon: IconId,
798        tooltip: impl Into<String>,
799    ) -> Self {
800        self.trailing_action = Some(TreeNodeTrailingAction::new(icon).tooltip(tooltip));
801        self
802    }
803
804    /// Borrows the application-defined ID.
805    ///
806    /// # Examples
807    ///
808    /// ```
809    /// use ailloli_ui_widgets::controls::TreeNode;
810    /// assert_eq!(TreeNode::leaf(7, "file").id(), &7);
811    /// ```
812    pub fn id(&self) -> &T {
813        &self.id
814    }
815
816    /// Borrows the stored display label.
817    ///
818    /// # Examples
819    ///
820    /// ```
821    /// use ailloli_ui_widgets::controls::TreeNode;
822    /// assert_eq!(TreeNode::leaf(1, "file").label(), "file");
823    /// ```
824    pub fn label(&self) -> &str {
825        &self.label
826    }
827
828    /// Borrows children in display order.
829    ///
830    /// # Examples
831    ///
832    /// ```
833    /// use ailloli_ui_widgets::controls::TreeNode;
834    /// assert!(TreeNode::leaf(1, "file").child_nodes().is_empty());
835    /// ```
836    pub fn child_nodes(&self) -> &[TreeNode<T>] {
837        &self.children
838    }
839
840    /// Reports provisional presentation metadata.
841    ///
842    /// # Examples
843    ///
844    /// ```
845    /// use ailloli_ui_widgets::controls::TreeNode;
846    /// assert!(!TreeNode::leaf(1, "file").is_transient());
847    /// ```
848    pub fn is_transient(&self) -> bool {
849        self.transient
850    }
851
852    /// Borrows optional trailing action metadata.
853    ///
854    /// # Examples
855    ///
856    /// ```
857    /// use ailloli_ui_widgets::controls::TreeNode;
858    /// assert!(TreeNode::leaf(1, "file").trailing_action_ref().is_none());
859    /// ```
860    pub fn trailing_action_ref(&self) -> Option<&TreeNodeTrailingAction> {
861        self.trailing_action.as_ref()
862    }
863}
864
865/// Shared context-aware changed-selection callback.
866type TreeSelectHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T)>;
867/// Shared context-aware explicit-activation callback.
868type TreeActivateHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T)>;
869/// Shared context-aware branch-toggle callback carrying next state.
870type TreeToggleHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T, bool)>;
871/// Shared context-aware selected-row trailing-action callback.
872type TreeTrailingActionHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T)>;
873/// Shared context-aware drag/drop intent callback.
874type TreeMoveHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, TreeMove<T>)>;
875/// Shared context-aware committed-rename callback.
876type TreeRenameHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, TreeRename<T>)>;
877/// Shared context-aware committed-create callback.
878type TreeCreateHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, TreeCreate<T>)>;
879/// Shared context-aware cancelled-create callback.
880type TreeCreateCancelHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, TreeCreateCancel<T>)>;
881/// Shared context-aware delete intent callback.
882type TreeDeleteHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, TreeDelete<T>)>;
883/// Shared context-aware right-click callback.
884type TreeContextMenuHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, TreeContextMenu<T>)>;
885/// Shared context-aware keyboard shortcut callback.
886type TreeShortcutHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, TreeShortcut<T>)>;
887/// Factory that may reject a create request by returning `None`.
888type TreeCreateFactory<T> = Rc<dyn Fn(TreeCreateRequest<T>) -> Option<TreeNode<T>>>;
889
890/// Type-erased visible-row/expansion adapter for retained models.
891trait RetainedTreeSource<T> {
892    /// Returns persistent visible row count.
893    fn visible_len(&self) -> usize;
894    /// Clones one visible presentation row by index.
895    fn flat_node_at(&self, index: usize) -> Option<FlatNode<T>>;
896    /// Looks up visible row index by stable ID.
897    fn row_of(&self, id: &T) -> Option<usize>;
898    /// Returns first visible enabled row.
899    fn first_enabled_row(&self) -> Option<usize>;
900    /// Reads branch expansion state.
901    fn is_expanded(&self, id: &T) -> bool;
902    /// Attempts to change retained expansion state.
903    fn set_expanded(&self, id: T, expanded: bool) -> bool;
904    /// Registers a weak model-revision listener.
905    fn subscribe(&self, callback: &Rc<dyn Fn(u64)>) -> TreeModelSubscription;
906    /// Returns persistent flat-index rebuild count.
907    fn flatten_rebuilds(&self) -> u64;
908}
909
910impl<T> RetainedTreeSource<T> for TreeModelHandle<T>
911where
912    T: Clone + Eq + Hash + fmt::Debug + 'static,
913{
914    /// Reads persistent visible row count from the model.
915    fn visible_len(&self) -> usize {
916        self.read(|model| model.visible_len())
917    }
918
919    /// Projects one retained row/item into paint-ready metadata.
920    fn flat_node_at(&self, index: usize) -> Option<FlatNode<T>> {
921        self.read(|model| {
922            let row = model.flat_index().rows().get(index)?;
923            let item = model.item(row.node_id())?;
924            Some(FlatNode {
925                id: item.id().clone(),
926                label: item.label().to_string(),
927                depth: usize::from(row.depth()),
928                branch: item.is_branch(),
929                disabled: item.is_disabled(),
930                leading_icon: item.leading_icon_ref().cloned(),
931                leading_icon_tint: item.leading_icon_tint_ref(),
932                trailing_action: item.trailing_action_ref().cloned(),
933                parent: model.parent(item.id()).cloned(),
934            })
935        })
936    }
937
938    /// Reads constant-time visible ID lookup.
939    fn row_of(&self, id: &T) -> Option<usize> {
940        self.read(|model| model.flat_index().row_of(id))
941    }
942
943    /// Reads the cached first enabled visible row.
944    fn first_enabled_row(&self) -> Option<usize> {
945        self.read(|model| model.flat_index().first_enabled_row())
946    }
947
948    /// Reads retained branch expansion.
949    fn is_expanded(&self, id: &T) -> bool {
950        self.read(|model| model.is_expanded(id))
951    }
952
953    /// Applies retained expansion and collapses any model error to `false`.
954    fn set_expanded(&self, id: T, expanded: bool) -> bool {
955        self.apply(TreeMutation::SetExpanded { id, expanded })
956            .is_ok()
957    }
958
959    /// Forwards weak revision subscription to the retained handle.
960    fn subscribe(&self, callback: &Rc<dyn Fn(u64)>) -> TreeModelSubscription {
961        TreeModelHandle::subscribe(self, callback)
962    }
963
964    /// Reads retained flat-index full rebuild count.
965    fn flatten_rebuilds(&self) -> u64 {
966        self.read(|model| model.flat_index().rebuilds())
967    }
968}
969
970/// Interactive hierarchical view backed by snapshot nodes or a retained model.
971///
972/// A retained model takes precedence over bound/static snapshot nodes; a bound
973/// snapshot takes precedence over static nodes. Structural snapshot mutations
974/// require [`Self::bind_nodes`]. Retained structural edits use
975/// [`TreeMutationMode::IntentOnly`], leaving ownership to callbacks.
976///
977/// # Examples
978///
979/// ```
980/// use ailloli_ui_widgets::controls::{TreeNode, TreeView};
981/// let tree: TreeView<u64> = TreeView::new().node(TreeNode::leaf(1, "README"));
982/// let _ = tree;
983/// ```
984pub struct TreeView<T, A = ()> {
985    /// Root layout declarations.
986    pub(crate) layout: LayoutStyle,
987    /// Flex-parent participation.
988    pub(crate) flex_item: FlexItemStyle,
989    /// Static snapshot roots.
990    nodes: Vec<TreeNode<T>>,
991    /// Writable snapshot roots, taking precedence over static roots.
992    bound_nodes: Option<Signal<Vec<TreeNode<T>>>>,
993    /// Retained source, taking precedence over snapshot roots.
994    model: Option<Rc<dyn RetainedTreeSource<T>>>,
995    /// Optional readable selected ID.
996    selected: Option<Binding<T>>,
997    /// Optional writable selected ID.
998    bound_selected: Option<Signal<T>>,
999    /// Optional readable expanded IDs for snapshot trees.
1000    expanded: Option<Binding<Vec<T>>>,
1001    /// Optional writable expanded IDs for snapshot trees.
1002    bound_expanded: Option<Signal<Vec<T>>>,
1003    /// Optional one-shot editor command signal.
1004    command: Option<Signal<Option<TreeViewCommand<T>>>>,
1005    /// Deduplicated fallback expanded IDs when no expanded binding exists.
1006    default_expanded: Vec<T>,
1007    /// Whole-tree disabled state.
1008    disabled: Binding<bool>,
1009    /// Whether drag gestures may begin.
1010    draggable: Binding<bool>,
1011    /// Local-versus-intent mutation policy.
1012    mutation_mode: Binding<TreeMutationMode>,
1013    /// Whether rename editors may begin.
1014    editable: Binding<bool>,
1015    /// Whether Delete may request removal.
1016    deletable: Binding<bool>,
1017    /// Whether Insert/create commands may request nodes.
1018    creatable: Binding<bool>,
1019    /// Optional factory for provisional created nodes.
1020    create_node: Option<TreeCreateFactory<T>>,
1021    /// Changed-selection callback.
1022    on_select: Option<TreeSelectHandler<T, A>>,
1023    /// Explicit activation callback.
1024    on_activate: Option<TreeActivateHandler<T, A>>,
1025    /// Branch toggle callback.
1026    on_toggle: Option<TreeToggleHandler<T, A>>,
1027    /// Selected-row trailing-action callback.
1028    on_trailing_action: Option<TreeTrailingActionHandler<T, A>>,
1029    /// Drag/drop callback.
1030    on_move: Option<TreeMoveHandler<T, A>>,
1031    /// Rename callback and local-rename enablement.
1032    on_rename: Option<TreeRenameHandler<T, A>>,
1033    /// Create callback.
1034    on_create: Option<TreeCreateHandler<T, A>>,
1035    /// Cancelled-create callback.
1036    on_create_cancel: Option<TreeCreateCancelHandler<T, A>>,
1037    /// Delete callback.
1038    on_delete: Option<TreeDeleteHandler<T, A>>,
1039    /// Context-menu callback.
1040    on_context_menu: Option<TreeContextMenuHandler<T, A>>,
1041    /// Shortcut callback, which intercepts supported keys.
1042    on_shortcut: Option<TreeShortcutHandler<T, A>>,
1043    /// Appearance and geometry tokens.
1044    style: TreeViewStyle,
1045    /// Whether layout/paint visit viewport row ranges plus overscan.
1046    virtualized: bool,
1047    /// Optional shared structural counters.
1048    diagnostics: Option<TreeViewDiagnostics>,
1049}
1050
1051impl<T: Clone + PartialEq + 'static, A: 'static> Default for TreeView<T, A> {
1052    fn default() -> Self {
1053        Self::new()
1054    }
1055}
1056
1057impl<T: Clone + PartialEq + 'static, A: 'static> LayoutExt for TreeView<T, A> {
1058    /// Returns mutable access to root layout declarations.
1059    fn layout_mut(&mut self) -> &mut LayoutStyle {
1060        &mut self.layout
1061    }
1062}
1063
1064impl<T: Clone + PartialEq + 'static, A: 'static> TreeView<T, A> {
1065    /// Creates an enabled empty snapshot tree with default style.
1066    ///
1067    /// Selection/expansion are uncontrolled, structural features and
1068    /// virtualization are off, and mutation mode defaults to `ApplyLocal`.
1069    ///
1070    /// # Examples
1071    ///
1072    /// ```
1073    /// use ailloli_ui_widgets::controls::TreeView;
1074    /// let tree: TreeView<u8> = TreeView::new();
1075    /// let _ = tree;
1076    /// ```
1077    pub fn new() -> Self {
1078        Self {
1079            layout: LayoutStyle::default(),
1080            flex_item: FlexItemStyle::default(),
1081            nodes: Vec::new(),
1082            bound_nodes: None,
1083            model: None,
1084            selected: None,
1085            bound_selected: None,
1086            expanded: None,
1087            bound_expanded: None,
1088            command: None,
1089            default_expanded: Vec::new(),
1090            disabled: Binding::Static(false),
1091            draggable: Binding::Static(false),
1092            mutation_mode: Binding::Static(TreeMutationMode::ApplyLocal),
1093            editable: Binding::Static(false),
1094            deletable: Binding::Static(false),
1095            creatable: Binding::Static(false),
1096            create_node: None,
1097            on_select: None,
1098            on_activate: None,
1099            on_toggle: None,
1100            on_trailing_action: None,
1101            on_move: None,
1102            on_rename: None,
1103            on_create: None,
1104            on_create_cancel: None,
1105            on_delete: None,
1106            on_context_menu: None,
1107            on_shortcut: None,
1108            style: TreeViewStyle::default(),
1109            virtualized: false,
1110            diagnostics: None,
1111        }
1112    }
1113
1114    /// Appends one static snapshot root.
1115    ///
1116    /// Retained or bound node sources take precedence when configured.
1117    ///
1118    /// # Examples
1119    ///
1120    /// ```
1121    /// use ailloli_ui_widgets::controls::{TreeNode, TreeView};
1122    /// let tree: TreeView<u8> = TreeView::new().node(TreeNode::leaf(1, "file"));
1123    /// let _ = tree;
1124    /// ```
1125    pub fn node(mut self, node: TreeNode<T>) -> Self {
1126        self.nodes.push(node);
1127        self
1128    }
1129
1130    /// Extends static snapshot roots in iterator order.
1131    ///
1132    /// # Examples
1133    ///
1134    /// ```
1135    /// use ailloli_ui_widgets::controls::{TreeNode, TreeView};
1136    /// let tree: TreeView<u8> = TreeView::new().nodes([TreeNode::leaf(1, "a"), TreeNode::leaf(2, "b")]);
1137    /// let _ = tree;
1138    /// ```
1139    pub fn nodes(mut self, nodes: impl IntoIterator<Item = TreeNode<T>>) -> Self {
1140        self.nodes.extend(nodes);
1141        self
1142    }
1143
1144    /// Installs writable snapshot roots, taking precedence over static roots.
1145    ///
1146    /// This enables local structural drag/edit/create/delete operations. A
1147    /// retained model still takes precedence for rendering.
1148    ///
1149    /// # Examples
1150    ///
1151    /// ```
1152    /// use ailloli_ui_runtime::component::State;
1153    /// use ailloli_ui_widgets::controls::{TreeNode, TreeView};
1154    /// let roots = State::new(vec![TreeNode::leaf(1_u8, "file")]);
1155    /// let tree: TreeView<u8> = TreeView::new().bind_nodes(roots);
1156    /// let _ = tree;
1157    /// ```
1158    pub fn bind_nodes(mut self, nodes: impl Into<Signal<Vec<TreeNode<T>>>>) -> Self {
1159        self.bound_nodes = Some(nodes.into());
1160        self
1161    }
1162
1163    /// Uses a retained, revisioned model.
1164    ///
1165    /// This is recommended for large/incremental trees and takes precedence over
1166    /// snapshot roots. Expansion comes from the model. Structural editing must
1167    /// use `IntentOnly`; the owner then applies model mutations.
1168    ///
1169    /// # Examples
1170    ///
1171    /// ```
1172    /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle, TreeView};
1173    /// let model = TreeModelHandle::new(TreeModel::<u64>::new());
1174    /// let tree: TreeView<u64> = TreeView::new().model(model);
1175    /// let _ = tree;
1176    /// ```
1177    pub fn model(mut self, model: TreeModelHandle<T>) -> Self
1178    where
1179        T: Eq + Hash + fmt::Debug,
1180    {
1181        self.model = Some(Rc::new(model));
1182        self
1183    }
1184
1185    /// Sets readable static or reactive selection.
1186    ///
1187    /// Selection is not writable unless [`Self::bind_selected`] was also called.
1188    /// If called after `bind_selected`, the prior writable signal is retained for
1189    /// interaction while this value controls painting/comparison.
1190    ///
1191    /// # Examples
1192    ///
1193    /// ```
1194    /// use ailloli_ui_widgets::controls::TreeView;
1195    /// let tree: TreeView<u8> = TreeView::new().selected(1);
1196    /// let _ = tree;
1197    /// ```
1198    pub fn selected(mut self, selected: impl Into<Binding<T>>) -> Self {
1199        self.selected = Some(selected.into());
1200        self
1201    }
1202
1203    /// Installs readable/writable controlled selection.
1204    ///
1205    /// Selection callbacks run only when activation targets a different ID.
1206    ///
1207    /// # Examples
1208    ///
1209    /// ```
1210    /// use ailloli_ui_runtime::component::State;
1211    /// use ailloli_ui_widgets::controls::TreeView;
1212    /// let tree: TreeView<u8> = TreeView::new().bind_selected(State::new(1));
1213    /// let _ = tree;
1214    /// ```
1215    pub fn bind_selected(mut self, selected: impl Into<Signal<T>>) -> Self {
1216        let signal = selected.into();
1217        self.selected = Some(Binding::Signal(signal.clone()));
1218        self.bound_selected = Some(signal);
1219        self
1220    }
1221
1222    /// Sets readable expanded IDs for snapshot trees.
1223    ///
1224    /// Duplicates are ignored when read. It is not writable unless
1225    /// `bind_expanded` was also called; retained models ignore this value.
1226    ///
1227    /// # Examples
1228    ///
1229    /// ```
1230    /// use ailloli_ui_widgets::controls::TreeView;
1231    /// let tree: TreeView<u8> = TreeView::new().expanded(vec![1, 2]);
1232    /// let _ = tree;
1233    /// ```
1234    pub fn expanded(mut self, expanded: impl Into<Binding<Vec<T>>>) -> Self {
1235        self.expanded = Some(expanded.into());
1236        self
1237    }
1238
1239    /// Installs readable/writable expanded IDs for snapshot trees.
1240    ///
1241    /// Retained models use their own expansion state instead.
1242    ///
1243    /// # Examples
1244    ///
1245    /// ```
1246    /// use ailloli_ui_runtime::component::State;
1247    /// use ailloli_ui_widgets::controls::TreeView;
1248    /// let tree: TreeView<u8> = TreeView::new().bind_expanded(State::new(vec![1]));
1249    /// let _ = tree;
1250    /// ```
1251    pub fn bind_expanded(mut self, expanded: impl Into<Signal<Vec<T>>>) -> Self {
1252        let signal = expanded.into();
1253        self.expanded = Some(Binding::Signal(signal.clone()));
1254        self.bound_expanded = Some(signal);
1255        self
1256    }
1257
1258    /// Installs a writable one-shot editor-command signal.
1259    ///
1260    /// Present commands are consumed by setting the signal to `None` during
1261    /// layout or the next routed event, even when the target cannot begin editing.
1262    ///
1263    /// # Examples
1264    ///
1265    /// ```
1266    /// use ailloli_ui_runtime::component::State;
1267    /// use ailloli_ui_widgets::controls::{TreeView, TreeViewCommand};
1268    /// let command = State::new(Some(TreeViewCommand::BeginRename(1_u8)));
1269    /// let tree: TreeView<u8> = TreeView::new().bind_command(command);
1270    /// let _ = tree;
1271    /// ```
1272    pub fn bind_command(mut self, command: impl Into<Signal<Option<TreeViewCommand<T>>>>) -> Self {
1273        self.command = Some(command.into());
1274        self
1275    }
1276
1277    /// Adds one unique uncontrolled initial expansion ID.
1278    ///
1279    /// It is used only when no explicit expanded binding is configured.
1280    ///
1281    /// # Examples
1282    ///
1283    /// ```
1284    /// use ailloli_ui_widgets::controls::TreeView;
1285    /// let tree: TreeView<u8> = TreeView::new().default_expanded(1).default_expanded(1);
1286    /// let _ = tree;
1287    /// ```
1288    pub fn default_expanded(mut self, id: T) -> Self {
1289        if !self.default_expanded.iter().any(|open| open == &id) {
1290            self.default_expanded.push(id);
1291        }
1292        self
1293    }
1294
1295    /// Replaces uncontrolled initial expansion IDs with unique iterator values.
1296    ///
1297    /// # Examples
1298    ///
1299    /// ```
1300    /// use ailloli_ui_widgets::controls::TreeView;
1301    /// let tree: TreeView<u8> = TreeView::new().default_expanded_many([1, 2, 1]);
1302    /// let _ = tree;
1303    /// ```
1304    pub fn default_expanded_many(mut self, ids: impl IntoIterator<Item = T>) -> Self {
1305        self.default_expanded.clear();
1306        for id in ids {
1307            if !self.default_expanded.iter().any(|open| open == &id) {
1308                self.default_expanded.push(id);
1309            }
1310        }
1311        self
1312    }
1313
1314    /// Sets static or reactive whole-tree disabled state.
1315    ///
1316    /// Disabled trees are not focusable, ignore input, and paint disabled rows.
1317    ///
1318    /// # Examples
1319    ///
1320    /// ```
1321    /// use ailloli_ui_widgets::controls::TreeView;
1322    /// let tree: TreeView<u8> = TreeView::new().disabled(true);
1323    /// let _ = tree;
1324    /// ```
1325    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
1326        self.disabled = disabled.into();
1327        self
1328    }
1329
1330    /// Enables drag gestures when structural mutation capability also exists.
1331    ///
1332    /// A drag activates after moving more than four logical pixels.
1333    ///
1334    /// # Examples
1335    ///
1336    /// ```
1337    /// use ailloli_ui_widgets::controls::TreeView;
1338    /// let tree: TreeView<u8> = TreeView::new().draggable(true);
1339    /// let _ = tree;
1340    /// ```
1341    pub fn draggable(mut self, draggable: impl Into<Binding<bool>>) -> Self {
1342        self.draggable = draggable.into();
1343        self
1344    }
1345
1346    /// Sets reactive local-versus-intent structural mutation policy.
1347    ///
1348    /// `ApplyLocal` requires bound snapshot nodes. Retained structural operations
1349    /// require `IntentOnly`; retained branch toggles apply locally only in
1350    /// `ApplyLocal`.
1351    ///
1352    /// # Examples
1353    ///
1354    /// ```
1355    /// use ailloli_ui_widgets::controls::{TreeMutationMode, TreeView};
1356    /// let tree: TreeView<u8> = TreeView::new().mutation_mode(TreeMutationMode::IntentOnly);
1357    /// let _ = tree;
1358    /// ```
1359    pub fn mutation_mode(mut self, mode: impl Into<Binding<TreeMutationMode>>) -> Self {
1360        self.mutation_mode = mode.into();
1361        self
1362    }
1363
1364    /// Enables inline rename/create editors when mutation capability exists.
1365    ///
1366    /// Rename commits additionally require an `on_rename` callback.
1367    ///
1368    /// # Examples
1369    ///
1370    /// ```
1371    /// use ailloli_ui_widgets::controls::TreeView;
1372    /// let tree: TreeView<u8> = TreeView::new().editable(true);
1373    /// let _ = tree;
1374    /// ```
1375    pub fn editable(mut self, editable: impl Into<Binding<bool>>) -> Self {
1376        self.editable = editable.into();
1377        self
1378    }
1379
1380    /// Enables built-in Delete behavior when mutation capability exists.
1381    ///
1382    /// Installing `on_shortcut` intercepts Delete as a shortcut before built-in
1383    /// deletion.
1384    ///
1385    /// # Examples
1386    ///
1387    /// ```
1388    /// use ailloli_ui_widgets::controls::TreeView;
1389    /// let tree: TreeView<u8> = TreeView::new().deletable(true);
1390    /// let _ = tree;
1391    /// ```
1392    pub fn deletable(mut self, deletable: impl Into<Binding<bool>>) -> Self {
1393        self.deletable = deletable.into();
1394        self
1395    }
1396
1397    /// Enables Insert/create commands when mutation capability and a factory exist.
1398    ///
1399    /// # Examples
1400    ///
1401    /// ```
1402    /// use ailloli_ui_widgets::controls::TreeView;
1403    /// let tree: TreeView<u8> = TreeView::new().creatable(true);
1404    /// let _ = tree;
1405    /// ```
1406    pub fn creatable(mut self, creatable: impl Into<Binding<bool>>) -> Self {
1407        self.creatable = creatable.into();
1408        self
1409    }
1410
1411    /// Sets the factory used to construct provisional nodes for create requests.
1412    ///
1413    /// Returning `None` rejects the request without editing or callbacks.
1414    ///
1415    /// # Examples
1416    ///
1417    /// ```
1418    /// use ailloli_ui_widgets::controls::{TreeNode, TreeView};
1419    /// let tree: TreeView<u8> = TreeView::new().create_node_with(|request| Some(TreeNode::leaf(9, request.default_label)));
1420    /// let _ = tree;
1421    /// ```
1422    pub fn create_node_with(
1423        mut self,
1424        factory: impl Fn(TreeCreateRequest<T>) -> Option<TreeNode<T>> + 'static,
1425    ) -> Self {
1426        self.create_node = Some(Rc::new(factory));
1427        self
1428    }
1429
1430    /// Replaces tree appearance without altering explicit layout declarations.
1431    ///
1432    /// # Examples
1433    ///
1434    /// ```
1435    /// use ailloli_ui_widgets::controls::{TreeView, TreeViewStyle};
1436    /// let tree: TreeView<u8> = TreeView::new().tree_style(TreeViewStyle::default());
1437    /// let _ = tree;
1438    /// ```
1439    pub fn tree_style(mut self, style: TreeViewStyle) -> Self {
1440        self.style = style;
1441        self
1442    }
1443
1444    /// Re-derives every style field from the default theme and density.
1445    ///
1446    /// Explicit layout declarations remain unchanged.
1447    ///
1448    /// # Examples
1449    ///
1450    /// ```
1451    /// use ailloli_ui_widgets::controls::{TreeView, TreeViewSize};
1452    /// let tree: TreeView<u8> = TreeView::new().tree_size(TreeViewSize::Compact);
1453    /// let _ = tree;
1454    /// ```
1455    pub fn tree_size(mut self, size: TreeViewSize) -> Self {
1456        self.style = TreeViewStyle::from_theme(Theme::default(), size);
1457        self
1458    }
1459
1460    /// Enables viewport row-range layout/paint with eight-row overscan.
1461    ///
1462    /// A virtual layout without viewport and without finite maximum height falls
1463    /// back to all rows and increments `virtualization_fallbacks`.
1464    ///
1465    /// # Examples
1466    ///
1467    /// ```
1468    /// use ailloli_ui_widgets::controls::TreeView;
1469    /// let tree: TreeView<u8> = TreeView::new().virtualized(true);
1470    /// let _ = tree;
1471    /// ```
1472    pub fn virtualized(mut self, virtualized: bool) -> Self {
1473        self.virtualized = virtualized;
1474        self
1475    }
1476
1477    /// Attaches shared structural counters, replacing any previous handle.
1478    ///
1479    /// # Examples
1480    ///
1481    /// ```
1482    /// use ailloli_ui_widgets::controls::{TreeView, TreeViewDiagnostics};
1483    /// let diagnostics = TreeViewDiagnostics::new();
1484    /// let tree: TreeView<u8> = TreeView::new().diagnostics(diagnostics.clone());
1485    /// assert_eq!(diagnostics.snapshot().layout_calls, 0);
1486    /// let _ = tree;
1487    /// ```
1488    pub fn diagnostics(mut self, diagnostics: TreeViewDiagnostics) -> Self {
1489        self.diagnostics = Some(diagnostics);
1490        self
1491    }
1492
1493    /// Replaces preferred width; numeric inputs are logical pixels.
1494    ///
1495    /// # Examples
1496    ///
1497    /// ```
1498    /// use ailloli_ui_widgets::controls::TreeView;
1499    /// let tree: TreeView<u8> = TreeView::new().width(320.0);
1500    /// let _ = tree;
1501    /// ```
1502    pub fn width(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
1503        self.layout.width = value.into();
1504        self
1505    }
1506
1507    /// Replaces preferred height; numeric inputs are logical pixels.
1508    ///
1509    /// # Examples
1510    ///
1511    /// ```
1512    /// use ailloli_ui_widgets::controls::TreeView;
1513    /// let tree: TreeView<u8> = TreeView::new().height(480.0);
1514    /// let _ = tree;
1515    /// ```
1516    pub fn height(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
1517        self.layout.height = value.into();
1518        self
1519    }
1520
1521    /// Replaces the minimum-width declaration.
1522    ///
1523    /// # Examples
1524    ///
1525    /// ```
1526    /// use ailloli_ui_widgets::controls::TreeView;
1527    /// let tree: TreeView<u8> = TreeView::new().min_width(160.0);
1528    /// let _ = tree;
1529    /// ```
1530    pub fn min_width(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
1531        self.layout.min_width = value.into();
1532        self
1533    }
1534
1535    /// Replaces the maximum-width declaration.
1536    ///
1537    /// # Examples
1538    ///
1539    /// ```
1540    /// use ailloli_ui_widgets::controls::TreeView;
1541    /// let tree: TreeView<u8> = TreeView::new().max_width(640.0);
1542    /// let _ = tree;
1543    /// ```
1544    pub fn max_width(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
1545        self.layout.max_width = value.into();
1546        self
1547    }
1548
1549    /// Replaces the minimum-height declaration.
1550    ///
1551    /// # Examples
1552    ///
1553    /// ```
1554    /// use ailloli_ui_widgets::controls::TreeView;
1555    /// let tree: TreeView<u8> = TreeView::new().min_height(120.0);
1556    /// let _ = tree;
1557    /// ```
1558    pub fn min_height(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
1559        self.layout.min_height = value.into();
1560        self
1561    }
1562
1563    /// Replaces the maximum-height declaration.
1564    ///
1565    /// # Examples
1566    ///
1567    /// ```
1568    /// use ailloli_ui_widgets::controls::TreeView;
1569    /// let tree: TreeView<u8> = TreeView::new().max_height(720.0);
1570    /// let _ = tree;
1571    /// ```
1572    pub fn max_height(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
1573        self.layout.max_height = value.into();
1574        self
1575    }
1576
1577    /// Requests parent-fill sizing on both axes.
1578    ///
1579    /// # Examples
1580    ///
1581    /// ```
1582    /// use ailloli_ui_widgets::controls::TreeView;
1583    /// let tree: TreeView<u8> = TreeView::new().fill();
1584    /// let _ = tree;
1585    /// ```
1586    pub fn fill(mut self) -> Self {
1587        self.layout.width = ailloli_ui_core::style::Length::Fill;
1588        self.layout.height = ailloli_ui_core::style::Length::Fill;
1589        self
1590    }
1591
1592    /// Requests parent-fill width while preserving height.
1593    ///
1594    /// # Examples
1595    ///
1596    /// ```
1597    /// use ailloli_ui_widgets::controls::TreeView;
1598    /// let tree: TreeView<u8> = TreeView::new().fill_width();
1599    /// let _ = tree;
1600    /// ```
1601    pub fn fill_width(mut self) -> Self {
1602        self.layout.width = ailloli_ui_core::style::Length::Fill;
1603        self
1604    }
1605
1606    /// Requests parent-fill height while preserving width.
1607    ///
1608    /// # Examples
1609    ///
1610    /// ```
1611    /// use ailloli_ui_widgets::controls::TreeView;
1612    /// let tree: TreeView<u8> = TreeView::new().fill_height();
1613    /// let _ = tree;
1614    /// ```
1615    pub fn fill_height(mut self) -> Self {
1616        self.layout.height = ailloli_ui_core::style::Length::Fill;
1617        self
1618    }
1619
1620    /// Sets this tree's flex-grow weight to one.
1621    ///
1622    /// # Examples
1623    ///
1624    /// ```
1625    /// use ailloli_ui_widgets::controls::TreeView;
1626    /// let tree: TreeView<u8> = TreeView::new().flex_grow();
1627    /// let _ = tree;
1628    /// ```
1629    pub fn flex_grow(mut self) -> Self {
1630        self.flex_item = self.flex_item.flex_grow(1.0);
1631        self
1632    }
1633
1634    /// Dispatches the action returned when enabled selection changes.
1635    ///
1636    /// Equal IDs do not emit. Without writable selection, a different row can
1637    /// emit even though controlled painting remains unchanged.
1638    ///
1639    /// # Examples
1640    ///
1641    /// ```
1642    /// use ailloli_ui_widgets::controls::TreeView;
1643    /// let tree: TreeView<u8, u8> = TreeView::new().on_select(|id| id);
1644    /// let _ = tree;
1645    /// ```
1646    pub fn on_select(mut self, f: impl Fn(T) -> A + 'static) -> Self {
1647        self.on_select = Some(Rc::new(move |ctx, id| ctx.dispatch(f(id))));
1648        self
1649    }
1650
1651    /// Handles changed selection with direct event-context access.
1652    ///
1653    /// # Examples
1654    ///
1655    /// ```
1656    /// use ailloli_ui_widgets::controls::TreeView;
1657    /// let tree: TreeView<u8> = TreeView::new().on_select_ctx(|_ctx, _id| {});
1658    /// let _ = tree;
1659    /// ```
1660    pub fn on_select_ctx(mut self, f: impl Fn(&mut EventCtx<A>, T) + 'static) -> Self {
1661        self.on_select = Some(Rc::new(f));
1662        self
1663    }
1664
1665    /// Dispatches the action returned on explicit enabled-row activation.
1666    ///
1667    /// Activation comes from a qualifying second click or Enter. With this
1668    /// handler installed, Enter activates instead of selecting.
1669    ///
1670    /// # Examples
1671    ///
1672    /// ```
1673    /// use ailloli_ui_widgets::controls::TreeView;
1674    /// let tree: TreeView<u8, u8> = TreeView::new().on_activate(|id| id);
1675    /// let _ = tree;
1676    /// ```
1677    pub fn on_activate(mut self, f: impl Fn(T) -> A + 'static) -> Self {
1678        self.on_activate = Some(Rc::new(move |ctx, id| ctx.dispatch(f(id))));
1679        self
1680    }
1681
1682    /// Handles explicit activation with direct event-context access.
1683    ///
1684    /// # Examples
1685    ///
1686    /// ```
1687    /// use ailloli_ui_widgets::controls::TreeView;
1688    /// let tree: TreeView<u8> = TreeView::new().on_activate_ctx(|_ctx, _id| {});
1689    /// let _ = tree;
1690    /// ```
1691    pub fn on_activate_ctx(mut self, f: impl Fn(&mut EventCtx<A>, T) + 'static) -> Self {
1692        self.on_activate = Some(Rc::new(f));
1693        self
1694    }
1695
1696    /// Dispatches the action returned after a valid branch toggle intent.
1697    ///
1698    /// The boolean is the requested next expansion state. In retained
1699    /// `IntentOnly` mode the model remains unchanged until its owner applies it.
1700    ///
1701    /// # Examples
1702    ///
1703    /// ```
1704    /// use ailloli_ui_widgets::controls::TreeView;
1705    /// let tree: TreeView<u8, bool> = TreeView::new().on_toggle(|_id, open| open);
1706    /// let _ = tree;
1707    /// ```
1708    pub fn on_toggle(mut self, f: impl Fn(T, bool) -> A + 'static) -> Self {
1709        self.on_toggle = Some(Rc::new(move |ctx, id, open| ctx.dispatch(f(id, open))));
1710        self
1711    }
1712
1713    /// Handles branch toggle intent with direct event-context access.
1714    ///
1715    /// # Examples
1716    ///
1717    /// ```
1718    /// use ailloli_ui_widgets::controls::TreeView;
1719    /// let tree: TreeView<u8> = TreeView::new().on_toggle_ctx(|_ctx, _id, _open| {});
1720    /// let _ = tree;
1721    /// ```
1722    pub fn on_toggle_ctx(mut self, f: impl Fn(&mut EventCtx<A>, T, bool) + 'static) -> Self {
1723        self.on_toggle = Some(Rc::new(f));
1724        self
1725    }
1726
1727    /// Dispatches the action returned by an enabled selected row's trailing icon.
1728    ///
1729    /// # Examples
1730    ///
1731    /// ```
1732    /// use ailloli_ui_widgets::controls::TreeView;
1733    /// let tree: TreeView<u8, u8> = TreeView::new().on_trailing_action(|id| id);
1734    /// let _ = tree;
1735    /// ```
1736    pub fn on_trailing_action(mut self, f: impl Fn(T) -> A + 'static) -> Self {
1737        self.on_trailing_action = Some(Rc::new(move |ctx, id| ctx.dispatch(f(id))));
1738        self
1739    }
1740
1741    /// Handles a trailing action with direct event-context access.
1742    ///
1743    /// # Examples
1744    ///
1745    /// ```
1746    /// use ailloli_ui_widgets::controls::TreeView;
1747    /// let tree: TreeView<u8> = TreeView::new().on_trailing_action_ctx(|_ctx, _id| {});
1748    /// let _ = tree;
1749    /// ```
1750    pub fn on_trailing_action_ctx(mut self, f: impl Fn(&mut EventCtx<A>, T) + 'static) -> Self {
1751        self.on_trailing_action = Some(Rc::new(f));
1752        self
1753    }
1754
1755    /// Dispatches the action returned after a valid drag/drop move intent.
1756    ///
1757    /// `ApplyLocal` mutates bound snapshot nodes before emitting; `IntentOnly`
1758    /// emits without source mutation.
1759    ///
1760    /// # Examples
1761    ///
1762    /// ```
1763    /// use ailloli_ui_widgets::controls::{TreeMove, TreeView};
1764    /// let tree: TreeView<u8, TreeMove<u8>> = TreeView::new().on_move(|event| event);
1765    /// let _ = tree;
1766    /// ```
1767    pub fn on_move(mut self, f: impl Fn(TreeMove<T>) -> A + 'static) -> Self {
1768        self.on_move = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
1769        self
1770    }
1771
1772    /// Handles drag/drop move intent with direct event-context access.
1773    ///
1774    /// # Examples
1775    ///
1776    /// ```
1777    /// use ailloli_ui_widgets::controls::TreeView;
1778    /// let tree: TreeView<u8> = TreeView::new().on_move_ctx(|_ctx, _event| {});
1779    /// let _ = tree;
1780    /// ```
1781    pub fn on_move_ctx(mut self, f: impl Fn(&mut EventCtx<A>, TreeMove<T>) + 'static) -> Self {
1782        self.on_move = Some(Rc::new(f));
1783        self
1784    }
1785
1786    /// Dispatches the action returned for a nonempty committed rename.
1787    ///
1788    /// Installing a rename handler is required for ordinary rename commits. In
1789    /// local mode bound snapshot labels are changed before emission; intent mode
1790    /// leaves the source unchanged.
1791    ///
1792    /// # Examples
1793    ///
1794    /// ```
1795    /// use ailloli_ui_widgets::controls::{TreeRename, TreeView};
1796    /// let tree: TreeView<u8, TreeRename<u8>> = TreeView::new().on_rename(|event| event);
1797    /// let _ = tree;
1798    /// ```
1799    pub fn on_rename(mut self, f: impl Fn(TreeRename<T>) -> A + 'static) -> Self {
1800        self.on_rename = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
1801        self
1802    }
1803
1804    /// Handles a committed rename with direct event-context access.
1805    ///
1806    /// # Examples
1807    ///
1808    /// ```
1809    /// use ailloli_ui_widgets::controls::TreeView;
1810    /// let tree: TreeView<u8> = TreeView::new().on_rename_ctx(|_ctx, _event| {});
1811    /// let _ = tree;
1812    /// ```
1813    pub fn on_rename_ctx(mut self, f: impl Fn(&mut EventCtx<A>, TreeRename<T>) + 'static) -> Self {
1814        self.on_rename = Some(Rc::new(f));
1815        self
1816    }
1817
1818    /// Dispatches the action returned for a committed create intent.
1819    ///
1820    /// Creation also requires `creatable`, structural mutation capability, and a
1821    /// factory. External create commands emit the trimmed final editor label.
1822    ///
1823    /// # Examples
1824    ///
1825    /// ```
1826    /// use ailloli_ui_widgets::controls::{TreeCreate, TreeView};
1827    /// let tree: TreeView<u8, TreeCreate<u8>> = TreeView::new().on_create(|event| event);
1828    /// let _ = tree;
1829    /// ```
1830    pub fn on_create(mut self, f: impl Fn(TreeCreate<T>) -> A + 'static) -> Self {
1831        self.on_create = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
1832        self
1833    }
1834
1835    /// Handles committed creation with direct event-context access.
1836    ///
1837    /// # Examples
1838    ///
1839    /// ```
1840    /// use ailloli_ui_widgets::controls::TreeView;
1841    /// let tree: TreeView<u8> = TreeView::new().on_create_ctx(|_ctx, _event| {});
1842    /// let _ = tree;
1843    /// ```
1844    pub fn on_create_ctx(mut self, f: impl Fn(&mut EventCtx<A>, TreeCreate<T>) + 'static) -> Self {
1845        self.on_create = Some(Rc::new(f));
1846        self
1847    }
1848
1849    /// Handles cancellation of a create editor with direct context access.
1850    ///
1851    /// Cancellation removes a locally inserted provisional snapshot/draft and
1852    /// carries the original request.
1853    ///
1854    /// # Examples
1855    ///
1856    /// ```
1857    /// use ailloli_ui_widgets::controls::TreeView;
1858    /// let tree: TreeView<u8> = TreeView::new().on_create_cancel_ctx(|_ctx, _event| {});
1859    /// let _ = tree;
1860    /// ```
1861    pub fn on_create_cancel_ctx(
1862        mut self,
1863        f: impl Fn(&mut EventCtx<A>, TreeCreateCancel<T>) + 'static,
1864    ) -> Self {
1865        self.on_create_cancel = Some(Rc::new(f));
1866        self
1867    }
1868
1869    /// Dispatches the action returned for deletion of an enabled subtree.
1870    ///
1871    /// Local mode removes bound snapshot nodes first; intent mode emits only.
1872    /// A configured shortcut handler intercepts Delete before this behavior.
1873    ///
1874    /// # Examples
1875    ///
1876    /// ```
1877    /// use ailloli_ui_widgets::controls::{TreeDelete, TreeView};
1878    /// let tree: TreeView<u8, TreeDelete<u8>> = TreeView::new().on_delete(|event| event);
1879    /// let _ = tree;
1880    /// ```
1881    pub fn on_delete(mut self, f: impl Fn(TreeDelete<T>) -> A + 'static) -> Self {
1882        self.on_delete = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
1883        self
1884    }
1885
1886    /// Handles deletion intent with direct event-context access.
1887    ///
1888    /// # Examples
1889    ///
1890    /// ```
1891    /// use ailloli_ui_widgets::controls::TreeView;
1892    /// let tree: TreeView<u8> = TreeView::new().on_delete_ctx(|_ctx, _event| {});
1893    /// let _ = tree;
1894    /// ```
1895    pub fn on_delete_ctx(mut self, f: impl Fn(&mut EventCtx<A>, TreeDelete<T>) + 'static) -> Self {
1896        self.on_delete = Some(Rc::new(f));
1897        self
1898    }
1899
1900    /// Dispatches the action returned for right-click row/blank context.
1901    ///
1902    /// An enabled row is made active and selected before its callback.
1903    ///
1904    /// # Examples
1905    ///
1906    /// ```
1907    /// use ailloli_ui_widgets::controls::TreeView;
1908    /// let tree: TreeView<u8> = TreeView::new().on_context_menu(|_event| ());
1909    /// let _ = tree;
1910    /// ```
1911    pub fn on_context_menu(mut self, f: impl Fn(TreeContextMenu<T>) -> A + 'static) -> Self {
1912        self.on_context_menu = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
1913        self
1914    }
1915
1916    /// Handles right-click context with direct event-context access.
1917    ///
1918    /// # Examples
1919    ///
1920    /// ```
1921    /// use ailloli_ui_widgets::controls::TreeView;
1922    /// let tree: TreeView<u8> = TreeView::new().on_context_menu_ctx(|_ctx, _event| {});
1923    /// let _ = tree;
1924    /// ```
1925    pub fn on_context_menu_ctx(
1926        mut self,
1927        f: impl Fn(&mut EventCtx<A>, TreeContextMenu<T>) + 'static,
1928    ) -> Self {
1929        self.on_context_menu = Some(Rc::new(f));
1930        self
1931    }
1932
1933    /// Dispatches supported Delete/Control-C/X/V shortcut intent.
1934    ///
1935    /// Installing this handler consumes matching shortcuts before built-in
1936    /// Delete. Alt/Meta-modified keys are ignored; Paste may carry no target.
1937    ///
1938    /// # Examples
1939    ///
1940    /// ```
1941    /// use ailloli_ui_widgets::controls::TreeView;
1942    /// let tree: TreeView<u8> = TreeView::new().on_shortcut(|_event| ());
1943    /// let _ = tree;
1944    /// ```
1945    pub fn on_shortcut(mut self, f: impl Fn(TreeShortcut<T>) -> A + 'static) -> Self {
1946        self.on_shortcut = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
1947        self
1948    }
1949
1950    /// Handles supported shortcut intent with direct event-context access.
1951    ///
1952    /// # Examples
1953    ///
1954    /// ```
1955    /// use ailloli_ui_widgets::controls::TreeView;
1956    /// let tree: TreeView<u8> = TreeView::new().on_shortcut_ctx(|_ctx, _event| {});
1957    /// let _ = tree;
1958    /// ```
1959    pub fn on_shortcut_ctx(
1960        mut self,
1961        f: impl Fn(&mut EventCtx<A>, TreeShortcut<T>) + 'static,
1962    ) -> Self {
1963        self.on_shortcut = Some(Rc::new(f));
1964        self
1965    }
1966}
1967
1968/// Component-stage configuration copied into the retained tree widget.
1969struct TreeViewComponent<T, A> {
1970    /// Root layout declarations.
1971    layout: LayoutStyle,
1972    /// Static snapshot roots.
1973    nodes: Vec<TreeNode<T>>,
1974    /// Optional writable snapshot roots.
1975    bound_nodes: Option<Signal<Vec<TreeNode<T>>>>,
1976    /// Optional retained source.
1977    model: Option<Rc<dyn RetainedTreeSource<T>>>,
1978    /// Optional readable selection.
1979    selected: Option<Binding<T>>,
1980    /// Optional writable selection.
1981    bound_selected: Option<Signal<T>>,
1982    /// Optional readable snapshot expansion IDs.
1983    expanded: Option<Binding<Vec<T>>>,
1984    /// Optional writable snapshot expansion IDs.
1985    bound_expanded: Option<Signal<Vec<T>>>,
1986    /// Optional one-shot editor command signal.
1987    command: Option<Signal<Option<TreeViewCommand<T>>>>,
1988    /// Fallback uncontrolled expansion IDs.
1989    default_expanded: Vec<T>,
1990    /// Whole-tree disabled state.
1991    disabled: Binding<bool>,
1992    /// Drag enablement.
1993    draggable: Binding<bool>,
1994    /// Structural mutation policy.
1995    mutation_mode: Binding<TreeMutationMode>,
1996    /// Rename editor enablement.
1997    editable: Binding<bool>,
1998    /// Delete enablement.
1999    deletable: Binding<bool>,
2000    /// Create enablement.
2001    creatable: Binding<bool>,
2002    /// Optional create factory.
2003    create_node: Option<TreeCreateFactory<T>>,
2004    /// Changed-selection callback.
2005    on_select: Option<TreeSelectHandler<T, A>>,
2006    /// Explicit activation callback.
2007    on_activate: Option<TreeActivateHandler<T, A>>,
2008    /// Toggle callback.
2009    on_toggle: Option<TreeToggleHandler<T, A>>,
2010    /// Trailing action callback.
2011    on_trailing_action: Option<TreeTrailingActionHandler<T, A>>,
2012    /// Move callback.
2013    on_move: Option<TreeMoveHandler<T, A>>,
2014    /// Rename callback.
2015    on_rename: Option<TreeRenameHandler<T, A>>,
2016    /// Create callback.
2017    on_create: Option<TreeCreateHandler<T, A>>,
2018    /// Create cancellation callback.
2019    on_create_cancel: Option<TreeCreateCancelHandler<T, A>>,
2020    /// Delete callback.
2021    on_delete: Option<TreeDeleteHandler<T, A>>,
2022    /// Context-menu callback.
2023    on_context_menu: Option<TreeContextMenuHandler<T, A>>,
2024    /// Keyboard shortcut callback.
2025    on_shortcut: Option<TreeShortcutHandler<T, A>>,
2026    /// Appearance and geometry tokens.
2027    style: TreeViewStyle,
2028    /// Row-range virtualization flag.
2029    virtualized: bool,
2030    /// Optional structural diagnostics.
2031    diagnostics: Option<TreeViewDiagnostics>,
2032}
2033
2034impl<T: Clone + PartialEq + 'static, A: 'static> ComponentNode<A> for TreeViewComponent<T, A> {
2035    /// Allocates uncontrolled expansion, model invalidation, editor, and cache state.
2036    fn build(&self, context: &mut Context<A>) -> View<A> {
2037        let internal_expanded = context.signal_with_invalidation(
2038            unique_vec(self.default_expanded.clone()),
2039            Invalidation::Layout,
2040        );
2041        let expanded = self
2042            .expanded
2043            .clone()
2044            .unwrap_or_else(|| Binding::Signal(internal_expanded.clone()));
2045        let mutable_expanded = self
2046            .bound_expanded
2047            .clone()
2048            .or_else(|| self.expanded.is_none().then_some(internal_expanded));
2049        let model_callback = self.model.as_ref().map(|_| {
2050            let invalidate = context.invalidation_target(Invalidation::Layout);
2051            Rc::new(move |_revision: u64| invalidate()) as Rc<dyn Fn(u64)>
2052        });
2053        let model_subscription = self
2054            .model
2055            .as_ref()
2056            .zip(model_callback.as_ref())
2057            .map(|(model, callback)| model.subscribe(callback));
2058        View::leaf(TreeViewWidget {
2059            layout: self.layout,
2060            nodes: self.nodes.clone(),
2061            bound_nodes: self.bound_nodes.clone(),
2062            model: self.model.clone(),
2063            _model_callback: model_callback,
2064            _model_subscription: model_subscription,
2065            selected: self.selected.clone(),
2066            bound_selected: self.bound_selected.clone(),
2067            expanded,
2068            mutable_expanded,
2069            command: self.command.clone(),
2070            pending_command: RefCell::new(None),
2071            disabled: self.disabled.clone(),
2072            draggable: self.draggable.clone(),
2073            mutation_mode: self.mutation_mode.clone(),
2074            editable: self.editable.clone(),
2075            deletable: self.deletable.clone(),
2076            creatable: self.creatable.clone(),
2077            create_node: self.create_node.clone(),
2078            on_select: self.on_select.clone(),
2079            on_activate: self.on_activate.clone(),
2080            on_toggle: self.on_toggle.clone(),
2081            on_trailing_action: self.on_trailing_action.clone(),
2082            on_move: self.on_move.clone(),
2083            on_rename: self.on_rename.clone(),
2084            on_create: self.on_create.clone(),
2085            on_create_cancel: self.on_create_cancel.clone(),
2086            on_delete: self.on_delete.clone(),
2087            on_context_menu: self.on_context_menu.clone(),
2088            on_shortcut: self.on_shortcut.clone(),
2089            style: self.style.clone(),
2090            virtualized: self.virtualized,
2091            diagnostics: self.diagnostics.clone(),
2092            active_index: context.signal_with_invalidation(None, Invalidation::Paint),
2093            drag: context.signal_with_invalidation(None, Invalidation::Paint),
2094            editing: context.signal_with_invalidation(None, Invalidation::Paint),
2095            draft: context.signal_with_invalidation(None, Invalidation::Layout),
2096            edit_value: context.signal_with_invalidation(String::new(), Invalidation::Paint),
2097            edit_buffer: context.signal_with_invalidation(
2098                TextBuffer::from_string(String::new()),
2099                Invalidation::Paint,
2100            ),
2101            edit_state: context.signal_with_invalidation(TextEditState::new(), Invalidation::Paint),
2102            last_click: context.signal_with_invalidation(None, Invalidation::Paint),
2103            observed_max_width: Rc::new(Cell::new(160.0)),
2104            snapshot_flat_cache: Rc::new(RefCell::new(SnapshotFlatCache::default())),
2105        })
2106    }
2107}
2108
2109impl<T: Clone + PartialEq + 'static, A: 'static> IntoView<A> for TreeView<T, A> {
2110    /// Builds the retained component and preserves flex/size metadata.
2111    fn into_view(self) -> View<A> {
2112        finish_view_sized(
2113            View::component(TreeViewComponent {
2114                layout: self.layout,
2115                nodes: self.nodes,
2116                bound_nodes: self.bound_nodes,
2117                model: self.model,
2118                selected: self.selected,
2119                bound_selected: self.bound_selected,
2120                expanded: self.expanded,
2121                bound_expanded: self.bound_expanded,
2122                command: self.command,
2123                default_expanded: self.default_expanded,
2124                disabled: self.disabled,
2125                draggable: self.draggable,
2126                mutation_mode: self.mutation_mode,
2127                editable: self.editable,
2128                deletable: self.deletable,
2129                creatable: self.creatable,
2130                create_node: self.create_node,
2131                on_select: self.on_select,
2132                on_activate: self.on_activate,
2133                on_toggle: self.on_toggle,
2134                on_trailing_action: self.on_trailing_action,
2135                on_move: self.on_move,
2136                on_rename: self.on_rename,
2137                on_create: self.on_create,
2138                on_create_cancel: self.on_create_cancel,
2139                on_delete: self.on_delete,
2140                on_context_menu: self.on_context_menu,
2141                on_shortcut: self.on_shortcut,
2142                style: self.style,
2143                virtualized: self.virtualized,
2144                diagnostics: self.diagnostics,
2145            }),
2146            self.flex_item,
2147            LayoutSizeHint::from_layout(self.layout),
2148        )
2149    }
2150}
2151
2152#[derive(Clone)]
2153/// Paint-ready visible node projected from snapshot or retained sources.
2154struct FlatNode<T> {
2155    /// Application/retained stable ID.
2156    id: T,
2157    /// Display label.
2158    label: String,
2159    /// Zero-based visible hierarchy depth.
2160    depth: usize,
2161    /// Whether to paint/toggle a branch chevron.
2162    branch: bool,
2163    /// Snapshot of disabled state.
2164    disabled: bool,
2165    /// Optional leading icon.
2166    leading_icon: Option<IconId>,
2167    /// Optional leading-icon tint override.
2168    leading_icon_tint: Option<Color>,
2169    /// Optional selected-row trailing action.
2170    trailing_action: Option<TreeNodeTrailingAction>,
2171    /// Parent ID, or `None` for a root.
2172    parent: Option<T>,
2173}
2174
2175#[derive(Clone)]
2176/// Validated drag/drop target row and relation.
2177struct TreeDropTarget<T> {
2178    /// Target row ID.
2179    target: T,
2180    /// Before/after/inside relation.
2181    position: TreeDropPosition,
2182}
2183
2184#[derive(Clone)]
2185/// Pointer drag candidate/active state.
2186struct TreeDragState<T> {
2187    /// Dragged source ID.
2188    source: T,
2189    /// Pointer-down location.
2190    start: Point,
2191    /// Whether movement passed the activation threshold.
2192    active: bool,
2193    /// Current enabled non-self drop target.
2194    target: Option<TreeDropTarget<T>>,
2195}
2196
2197#[derive(Clone)]
2198/// Last row click used to detect double-click activation.
2199struct TreeClickState<T> {
2200    /// Event or legacy monotonic timestamp.
2201    at: TreeClickTimestamp,
2202    /// Pointer location used for distance threshold.
2203    pos: Point,
2204    /// Clicked row ID.
2205    id: T,
2206    /// Saturating click sequence count capped at three.
2207    count: u8,
2208}
2209
2210#[derive(Clone, Copy)]
2211/// Comparable click timestamp within one timing source.
2212enum TreeClickTimestamp {
2213    /// Runtime event timestamp.
2214    Event(Duration),
2215    /// Monotonic fallback when event metadata is absent.
2216    Legacy(Instant),
2217}
2218
2219impl TreeClickTimestamp {
2220    /// Returns checked elapsed time only for matching timestamp sources.
2221    fn elapsed_since(self, earlier: Self) -> Option<Duration> {
2222        match (self, earlier) {
2223            (Self::Event(now), Self::Event(earlier)) => now.checked_sub(earlier),
2224            (Self::Legacy(now), Self::Legacy(earlier)) => now.checked_duration_since(earlier),
2225            _ => None,
2226        }
2227    }
2228}
2229
2230#[derive(Clone)]
2231/// Active inline editor identity, original label, and optional create request.
2232struct TreeEditing<T> {
2233    /// Edited node/draft ID.
2234    id: T,
2235    /// Label before editing began.
2236    original: String,
2237    /// Present for external/retained create-editor flows.
2238    create: Option<TreeCreateRequest<T>>,
2239}
2240
2241#[derive(Clone)]
2242/// Retained intent-only provisional row not yet present in its model.
2243struct TreeDraft<T> {
2244    /// Paint-ready provisional node.
2245    node: FlatNode<T>,
2246    /// Visible row insertion index.
2247    insert_index: usize,
2248}
2249
2250/// Persistent flattened cache for recursive snapshot trees.
2251struct SnapshotFlatCache<T> {
2252    /// Bound root-signal revision represented by the cache.
2253    nodes_revision: u64,
2254    /// Whether an initial flatten has occurred.
2255    initialized: bool,
2256    /// Deduplicated expansion IDs represented by the cache.
2257    expanded: Vec<T>,
2258    /// Visible paint-ready rows.
2259    rows: Vec<FlatNode<T>>,
2260    /// Saturating full-cache rebuild count.
2261    rebuilds: u64,
2262}
2263
2264impl<T> Default for SnapshotFlatCache<T> {
2265    fn default() -> Self {
2266        Self {
2267            nodes_revision: 0,
2268            initialized: false,
2269            expanded: Vec::new(),
2270            rows: Vec::new(),
2271            rebuilds: 0,
2272        }
2273    }
2274}
2275
2276/// Per-row state passed to the node painter.
2277struct TreeNodePaint<'a, T> {
2278    /// Row rectangle.
2279    row: Rect,
2280    /// Paint-ready node.
2281    node: &'a FlatNode<T>,
2282    /// Whether controlled selection matches the node ID.
2283    selected: bool,
2284    /// Disabled/drag alpha multiplier.
2285    opacity: f32,
2286    /// Current widget layout used by inline text editing.
2287    layout: &'a LayoutResult,
2288    /// Whether tree keyboard focus is active.
2289    focused: bool,
2290    /// Matching inline editor, if any.
2291    editing: Option<&'a TreeEditing<T>>,
2292}
2293
2294/// Retained interactive tree widget and all reactive/cache state.
2295struct TreeViewWidget<T, A> {
2296    /// Root layout declarations.
2297    layout: LayoutStyle,
2298    /// Static snapshot roots.
2299    nodes: Vec<TreeNode<T>>,
2300    /// Optional writable snapshot roots.
2301    bound_nodes: Option<Signal<Vec<TreeNode<T>>>>,
2302    /// Optional retained source.
2303    model: Option<Rc<dyn RetainedTreeSource<T>>>,
2304    /// Strong callback kept alive for weak model subscription.
2305    _model_callback: Option<Rc<dyn Fn(u64)>>,
2306    /// RAII model revision subscription.
2307    _model_subscription: Option<TreeModelSubscription>,
2308    /// Optional readable selection.
2309    selected: Option<Binding<T>>,
2310    /// Optional writable selection.
2311    bound_selected: Option<Signal<T>>,
2312    /// Snapshot expanded-ID binding or internal uncontrolled binding.
2313    expanded: Binding<Vec<T>>,
2314    /// Optional writable snapshot expansion signal.
2315    mutable_expanded: Option<Signal<Vec<T>>>,
2316    /// Optional one-shot external command signal.
2317    command: Option<Signal<Option<TreeViewCommand<T>>>>,
2318    /// Command observed by one exact authoritative layout attempt.
2319    pending_command: RefCell<Option<TransactionalLayoutPending<TreeViewCommand<T>>>>,
2320    /// Whole-tree disabled state.
2321    disabled: Binding<bool>,
2322    /// Drag enablement.
2323    draggable: Binding<bool>,
2324    /// Structural mutation policy.
2325    mutation_mode: Binding<TreeMutationMode>,
2326    /// Rename editor enablement.
2327    editable: Binding<bool>,
2328    /// Delete enablement.
2329    deletable: Binding<bool>,
2330    /// Create enablement.
2331    creatable: Binding<bool>,
2332    /// Optional create-node factory.
2333    create_node: Option<TreeCreateFactory<T>>,
2334    /// Changed-selection callback.
2335    on_select: Option<TreeSelectHandler<T, A>>,
2336    /// Explicit activation callback.
2337    on_activate: Option<TreeActivateHandler<T, A>>,
2338    /// Branch-toggle callback.
2339    on_toggle: Option<TreeToggleHandler<T, A>>,
2340    /// Selected-row trailing-action callback.
2341    on_trailing_action: Option<TreeTrailingActionHandler<T, A>>,
2342    /// Drag/drop callback.
2343    on_move: Option<TreeMoveHandler<T, A>>,
2344    /// Rename callback.
2345    on_rename: Option<TreeRenameHandler<T, A>>,
2346    /// Create callback.
2347    on_create: Option<TreeCreateHandler<T, A>>,
2348    /// Create cancellation callback.
2349    on_create_cancel: Option<TreeCreateCancelHandler<T, A>>,
2350    /// Delete callback.
2351    on_delete: Option<TreeDeleteHandler<T, A>>,
2352    /// Context-menu callback.
2353    on_context_menu: Option<TreeContextMenuHandler<T, A>>,
2354    /// Keyboard shortcut callback.
2355    on_shortcut: Option<TreeShortcutHandler<T, A>>,
2356    /// Appearance and geometry tokens.
2357    style: TreeViewStyle,
2358    /// Whether layout/paint use visible row ranges.
2359    virtualized: bool,
2360    /// Current explicit keyboard-active row.
2361    active_index: Signal<Option<usize>>,
2362    /// Current drag candidate/state.
2363    drag: Signal<Option<TreeDragState<T>>>,
2364    /// Current inline editor.
2365    editing: Signal<Option<TreeEditing<T>>>,
2366    /// Retained intent-only provisional create row.
2367    draft: Signal<Option<TreeDraft<T>>>,
2368    /// Editor's reactive string value.
2369    edit_value: Signal<String>,
2370    /// Editor's text buffer.
2371    edit_buffer: Signal<TextBuffer>,
2372    /// Editor caret/selection state.
2373    edit_state: Signal<TextEditState>,
2374    /// Last click used for activation counting.
2375    last_click: Signal<Option<TreeClickState<T>>>,
2376    /// Monotonic intrinsic-width observation, floored at 160 pixels.
2377    observed_max_width: Rc<Cell<f32>>,
2378    /// Persistent flattened snapshot cache.
2379    snapshot_flat_cache: Rc<RefCell<SnapshotFlatCache<T>>>,
2380    /// Optional shared diagnostics counters.
2381    diagnostics: Option<TreeViewDiagnostics>,
2382}
2383
2384impl<T: Clone + PartialEq + 'static, A: 'static> Widget<A> for TreeViewWidget<T, A> {
2385    /// Returns the stable diagnostic widget name.
2386    fn debug_name(&self) -> &'static str {
2387        "TreeView"
2388    }
2389
2390    /// Consumes commands, visits the selected row range, and resolves intrinsic size.
2391    ///
2392    /// Intrinsic width never shrinks below the greatest previously observed width
2393    /// or 160 logical pixels; intrinsic height covers every source row.
2394    fn layout(
2395        &self,
2396        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
2397        ctx: &mut LayoutCtx<'_>,
2398        _children: &mut [LayoutChild],
2399        constraints: Constraints,
2400    ) -> LayoutResult {
2401        if ctx.layout_pass().is_committed() {
2402            let command = self.command.as_ref().and_then(Signal::read);
2403            self.pending_command
2404                .replace(command.and_then(|command| TransactionalLayoutPending::new(ctx, command)));
2405        }
2406        let total_rows = self.visible_len();
2407        let layout_range = self.layout_row_range(ctx, constraints, total_rows);
2408        let layout_rows = layout_range.len();
2409        let nodes = self.visible_nodes_range(layout_range);
2410        if let Some(diagnostics) = &self.diagnostics {
2411            let flatten_rebuilds = self
2412                .model
2413                .as_ref()
2414                .map_or(0, |model| model.flatten_rebuilds());
2415            let fallback = self.virtualized
2416                && ctx.virtual_viewport().is_none()
2417                && !constraints.max_h.is_finite();
2418            diagnostics.update(|snapshot| {
2419                snapshot.layout_calls = snapshot.layout_calls.saturating_add(1);
2420                snapshot.loaded_rows = total_rows;
2421                snapshot.visible_rows = layout_rows;
2422                snapshot.layout_rows_visited = snapshot
2423                    .layout_rows_visited
2424                    .saturating_add(layout_rows as u64);
2425                snapshot.text_measurements = snapshot
2426                    .text_measurements
2427                    .saturating_add(layout_rows as u64);
2428                snapshot.flatten_rebuilds = flatten_rebuilds.max(snapshot.flatten_rebuilds);
2429                snapshot.virtualization_fallbacks = snapshot
2430                    .virtualization_fallbacks
2431                    .saturating_add(u64::from(fallback));
2432            });
2433        }
2434        let mut max_w = self.observed_max_width.get().max(160.0);
2435        for node in &nodes {
2436            let text_w = measure_text(ctx, &node.label, self.text_style(node)).unwrap_or(80.0);
2437            let icon_w = node
2438                .leading_icon
2439                .as_ref()
2440                .map(|_| self.style.icon_size + self.style.gap)
2441                .unwrap_or(0.0);
2442            let action_w = node
2443                .trailing_action
2444                .as_ref()
2445                .map(|_| self.trailing_action_size() + self.style.gap)
2446                .unwrap_or(0.0);
2447            max_w = max_w.max(
2448                self.style.padding_x * 2.0
2449                    + node.depth as f32 * self.style.indent
2450                    + self.style.chevron_size
2451                    + self.style.gap
2452                    + icon_w
2453                    + text_w
2454                    + action_w,
2455            );
2456        }
2457        self.observed_max_width.set(max_w);
2458        let intrinsic = Size::new(
2459            max_w,
2460            self.style.padding_y * 2.0 + total_rows as f32 * self.style.row_height,
2461        );
2462        let size = apply_layout_size(intrinsic, self.layout, constraints);
2463        LayoutResult {
2464            size,
2465            children: Vec::new(),
2466            paint_bounds: Rect::new(0.0, 0.0, size.w, size.h),
2467            visual_bounds: Rect::new(0.0, 0.0, size.w, size.h),
2468            overlay_hit_bounds: Vec::new(),
2469            clip: None,
2470            is_window_root_clip: false,
2471            artifact: None,
2472        }
2473    }
2474
2475    /// Publishes a staged editor command only after its observing layout won.
2476    ///
2477    /// A create command inserts a row and therefore deliberately schedules a
2478    /// second authoritative layout. Paint fails closed between those frames
2479    /// instead of drawing that fresh draft against older geometry.
2480    fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
2481        let Some(command) = self
2482            .pending_command
2483            .borrow_mut()
2484            .take()
2485            .and_then(|pending| pending.into_committed(ctx))
2486        else {
2487            return;
2488        };
2489        if let Some(command_signal) = &self.command {
2490            command_signal.set(None);
2491        }
2492        self.apply_pending_command(command);
2493    }
2494
2495    /// Paints the current row range, selection/active/drop/editor state, and focus.
2496    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, layout: &LayoutResult) {
2497        let disabled = self.disabled.read();
2498        if self.style.background.a > 0.0 {
2499            ctx.push(DrawCmd::RRect(DrawRRect {
2500                rect: bounds,
2501                radius: self.style.radius.tl,
2502                color: self.style.background,
2503            }));
2504        }
2505
2506        let total_rows = self.visible_len();
2507        let paint_range = self.paint_row_range(ctx, bounds, total_rows);
2508        let paint_rows = paint_range.len();
2509        let nodes = self.visible_nodes_range(paint_range.clone());
2510        if let Some(diagnostics) = &self.diagnostics {
2511            diagnostics.update(|snapshot| {
2512                snapshot.paint_calls = snapshot.paint_calls.saturating_add(1);
2513                snapshot.loaded_rows = total_rows;
2514                snapshot.visible_rows = paint_rows;
2515                snapshot.paint_rows_visited = snapshot
2516                    .paint_rows_visited
2517                    .saturating_add(paint_rows as u64);
2518            });
2519        }
2520        let selected = self.selected_value();
2521        let active = self.normalized_active_index_for_source();
2522        let drag = self.drag.read();
2523        let editing = self.editing.read();
2524        for (local_index, node) in nodes.iter().enumerate() {
2525            let idx = paint_range.start + local_index;
2526            let row = self.row_rect(bounds, idx);
2527            let is_selected = selected.as_ref().is_some_and(|value| value == &node.id);
2528            let is_active = ctx.is_focused() && active == Some(idx);
2529            let is_drag_source = drag
2530                .as_ref()
2531                .is_some_and(|drag| drag.active && drag.source == node.id);
2532            let opacity = if disabled || node.disabled {
2533                self.style.disabled_opacity
2534            } else if is_drag_source {
2535                0.42
2536            } else {
2537                1.0
2538            };
2539            let bg = if is_selected {
2540                self.style.selected_background
2541            } else if is_active {
2542                self.style.active_background
2543            } else {
2544                Color::TRANSPARENT
2545            };
2546            if bg.a > 0.0 {
2547                ctx.push(DrawCmd::RRect(DrawRRect {
2548                    rect: row,
2549                    radius: self.style.radius.tl,
2550                    color: bg.with_alpha(bg.a * opacity),
2551                }));
2552            }
2553
2554            if let Some(drop) = drag
2555                .as_ref()
2556                .and_then(|drag| drag.active.then_some(drag))
2557                .and_then(|drag| drag.target.as_ref())
2558                .filter(|drop| drop.target == node.id)
2559            {
2560                self.paint_drop_target(ctx, row, drop);
2561            }
2562
2563            self.paint_node(
2564                ctx,
2565                TreeNodePaint {
2566                    row,
2567                    node,
2568                    selected: is_selected,
2569                    opacity,
2570                    layout,
2571                    focused: ctx.is_focused(),
2572                    editing: editing.as_ref().filter(|edit| edit.id == node.id),
2573                },
2574            );
2575            if is_active && !disabled && !node.disabled {
2576                ctx.push(DrawCmd::Border(DrawBorder {
2577                    rect: row,
2578                    radius: self.style.radius,
2579                    border: self.style.focus_ring,
2580                }));
2581            }
2582        }
2583    }
2584
2585    /// Consumes queued commands, then routes enabled input to widget logic.
2586    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, layout: &LayoutResult) {
2587        // Events run outside build/layout/paint traversal. Applying the command
2588        // here lets a first typed character reach the freshly opened editor;
2589        // geometry-changing commands still request Layout through their state.
2590        self.consume_pending_command_for_event();
2591        if self.disabled.read() {
2592            return;
2593        }
2594        if self.handle_editing_event(ctx, event, bounds, layout) {
2595            return;
2596        }
2597        match event {
2598            Event::Pointer(PointerEvent::Button {
2599                pos,
2600                button: MouseButton::Left,
2601                pressed: true,
2602                ..
2603            }) if bounds.contains(pos.x, pos.y) => {
2604                self.handle_pointer_press(ctx, bounds, *pos);
2605            }
2606            Event::Pointer(PointerEvent::Button {
2607                pos,
2608                button: MouseButton::Right,
2609                pressed: true,
2610                ..
2611            }) if bounds.contains(pos.x, pos.y) => {
2612                self.handle_context_menu(ctx, bounds, *pos);
2613            }
2614            Event::Pointer(PointerEvent::Button {
2615                pos,
2616                button: MouseButton::Left,
2617                pressed: false,
2618                ..
2619            }) => {
2620                self.handle_pointer_release(ctx, bounds, *pos);
2621            }
2622            Event::Pointer(PointerEvent::Moved { pos, .. }) => {
2623                self.handle_pointer_move(ctx, bounds, *pos);
2624            }
2625            Event::Keyboard(key) if key.state == KeyState::Pressed => {
2626                self.handle_keyboard(ctx, key);
2627            }
2628            _ => {}
2629        }
2630    }
2631
2632    /// Is focusable only when the whole tree and at least one visible row are enabled.
2633    fn focus_policy(&self) -> FocusPolicy {
2634        let has_enabled = self.draft.read().is_some_and(|draft| !draft.node.disabled)
2635            || self.model.as_ref().map_or_else(
2636                || self.visible_nodes().iter().any(|node| !node.disabled),
2637                |model| model.first_enabled_row().is_some(),
2638            );
2639        if self.disabled.read() || !has_enabled {
2640            FocusPolicy::NotFocusable
2641        } else {
2642            FocusPolicy::Focusable
2643        }
2644    }
2645
2646    /// Exposes single-line text input only while an inline editor is active.
2647    fn input_role(&self) -> InputRole {
2648        if self.editing.read().is_some() {
2649            InputRole::TextSingleLine
2650        } else {
2651            InputRole::None
2652        }
2653    }
2654
2655    /// Returns inline editor IME caret geometry, or `None` outside editing.
2656    fn ime_cursor_rect(&self, bounds: Rect, layout: &LayoutResult) -> Option<Rect> {
2657        let editing = self.editing.read()?;
2658        let nodes = self.visible_nodes();
2659        let idx = nodes.iter().position(|node| node.id == editing.id)?;
2660        let row = self.row_rect(bounds, idx);
2661        let edit_rect = self.edit_rect(row, &nodes[idx]);
2662        ime_cursor_rect(
2663            edit_rect,
2664            layout,
2665            &self.edit_value,
2666            &self.edit_buffer,
2667            &self.edit_state,
2668            self.edit_text_style(),
2669        )
2670    }
2671}
2672
2673impl<T: Clone + PartialEq + 'static, A: 'static> TreeViewWidget<T, A> {
2674    /// Applies one queued command at the start of an event traversal.
2675    fn consume_pending_command_for_event(&self) {
2676        let Some(command_signal) = &self.command else {
2677            return;
2678        };
2679        let Some(command) = command_signal.read() else {
2680            return;
2681        };
2682        command_signal.set(None);
2683        self.apply_pending_command(command);
2684    }
2685
2686    /// Applies one command after the layout attempt that observed it committed.
2687    fn apply_pending_command(&self, command: TreeViewCommand<T>) {
2688        match command {
2689            TreeViewCommand::BeginRename(id) => {
2690                let nodes = self.visible_nodes();
2691                if let Some((idx, node)) = nodes.iter().enumerate().find(|(_, node)| node.id == id)
2692                {
2693                    if let Some(bound) = &self.bound_selected {
2694                        bound.set(node.id.clone());
2695                    }
2696                    self.active_index.set(Some(idx));
2697                    self.begin_rename(node);
2698                }
2699            }
2700            TreeViewCommand::BeginCreate(request) => {
2701                self.begin_create_from_request(request);
2702            }
2703        }
2704    }
2705
2706    /// Clones bound snapshot roots when present, otherwise static roots.
2707    fn current_nodes(&self) -> Vec<TreeNode<T>> {
2708        self.bound_nodes
2709            .as_ref()
2710            .map(Signal::read)
2711            .unwrap_or_else(|| self.nodes.clone())
2712    }
2713
2714    /// Returns retained row count or synchronizes/reads snapshot cache length.
2715    fn source_visible_len(&self) -> usize {
2716        self.model.as_ref().map_or_else(
2717            || {
2718                self.sync_snapshot_flat_cache();
2719                self.snapshot_flat_cache.borrow().rows.len()
2720            },
2721            |model| model.visible_len(),
2722        )
2723    }
2724
2725    /// Returns source row count plus an optional provisional draft row.
2726    fn visible_len(&self) -> usize {
2727        self.source_visible_len() + usize::from(self.draft.read().is_some())
2728    }
2729
2730    /// Clones one visible row, inserting a retained draft at its virtual position.
2731    fn visible_node_at(&self, index: usize) -> Option<FlatNode<T>> {
2732        let draft = self.draft.read();
2733        if let Some(draft) = &draft {
2734            if index == draft.insert_index {
2735                return Some(draft.node.clone());
2736            }
2737        }
2738        let source_index = draft
2739            .as_ref()
2740            .filter(|draft| index > draft.insert_index)
2741            .map_or(index, |_| index.saturating_sub(1));
2742        self.model.as_ref().map_or_else(
2743            || {
2744                self.sync_snapshot_flat_cache();
2745                self.snapshot_flat_cache
2746                    .borrow()
2747                    .rows
2748                    .get(source_index)
2749                    .cloned()
2750            },
2751            |model| model.flat_node_at(source_index),
2752        )
2753    }
2754
2755    /// Clones existing visible rows in the requested half-open range.
2756    fn visible_nodes_range(&self, range: std::ops::Range<usize>) -> Vec<FlatNode<T>> {
2757        range
2758            .filter_map(|index| self.visible_node_at(index))
2759            .collect()
2760    }
2761
2762    /// Replaces bound snapshot roots and reports whether a binding existed.
2763    fn set_current_nodes(&self, nodes: Vec<TreeNode<T>>) -> bool {
2764        let Some(bound) = &self.bound_nodes else {
2765            return false;
2766        };
2767        bound.set(nodes);
2768        true
2769    }
2770
2771    /// Reports structural capability: bound snapshot or retained intent-only mode.
2772    fn can_mutate_nodes(&self) -> bool {
2773        self.bound_nodes.is_some()
2774            || (self.model.is_some() && self.mutation_mode.read() == TreeMutationMode::IntentOnly)
2775    }
2776
2777    /// Adjusts a source row index for an inserted provisional draft.
2778    fn source_index_to_visible(&self, source_index: usize) -> usize {
2779        self.draft.read().map_or(source_index, |draft| {
2780            source_index + usize::from(source_index >= draft.insert_index)
2781        })
2782    }
2783
2784    /// Resolves a retained draft's visible insertion row and depth.
2785    fn retained_create_position(&self, request: &TreeCreateRequest<T>) -> Option<(usize, usize)> {
2786        let rows = (0..self.source_visible_len())
2787            .filter_map(|index| {
2788                self.model
2789                    .as_ref()
2790                    .and_then(|model| model.flat_node_at(index))
2791            })
2792            .collect::<Vec<_>>();
2793        match request.kind {
2794            TreeCreateKind::SiblingAfter => {
2795                let Some(after) = &request.after else {
2796                    return Some((rows.len(), 0));
2797                };
2798                let row = rows.iter().position(|node| &node.id == after)?;
2799                let depth = rows[row].depth;
2800                Some((visible_subtree_end(&rows, row), depth))
2801            }
2802            TreeCreateKind::Child => {
2803                let parent = request.parent.as_ref()?;
2804                let row = rows.iter().position(|node| &node.id == parent)?;
2805                let depth = rows[row].depth.saturating_add(1);
2806                Some((visible_subtree_end(&rows, row), depth))
2807            }
2808        }
2809    }
2810
2811    /// Installs one intent-only retained draft and begins its create editor.
2812    ///
2813    /// Rejects concurrent draft/editing and unresolved insertion positions.
2814    fn begin_retained_create(&self, node: TreeNode<T>, request: TreeCreateRequest<T>) -> bool {
2815        if self.draft.read().is_some() || self.editing.read().is_some() {
2816            return false;
2817        }
2818        let Some((insert_index, depth)) = self.retained_create_position(&request) else {
2819            return false;
2820        };
2821        let flat = FlatNode {
2822            id: node.id,
2823            label: node.label,
2824            depth,
2825            branch: node.branch,
2826            disabled: node.disabled.read(),
2827            leading_icon: node.leading_icon,
2828            leading_icon_tint: node.leading_icon_tint,
2829            trailing_action: node.trailing_action,
2830            parent: request.parent.clone(),
2831        };
2832        let created_id = flat.id.clone();
2833        self.draft.set(Some(TreeDraft {
2834            node: flat.clone(),
2835            insert_index,
2836        }));
2837        if let Some(bound) = &self.bound_selected {
2838            bound.set(created_id);
2839        }
2840        self.active_index.set(Some(insert_index));
2841        self.begin_create_rename(&flat, request)
2842    }
2843
2844    /// Reads snapshot expansion IDs and removes later duplicates stably.
2845    fn expanded_values(&self) -> Vec<T> {
2846        unique_vec(self.expanded.read())
2847    }
2848
2849    /// Clones readable controlled selection when configured.
2850    fn selected_value(&self) -> Option<T> {
2851        self.selected.as_ref().map(Binding::read)
2852    }
2853
2854    /// Clones every visible source/draft row.
2855    fn visible_nodes(&self) -> Vec<FlatNode<T>> {
2856        (0..self.visible_len())
2857            .filter_map(|index| self.visible_node_at(index))
2858            .collect()
2859    }
2860
2861    /// Synchronizes then clones snapshot-tree cached rows.
2862    fn visible_nodes_snapshot(&self) -> Vec<FlatNode<T>> {
2863        self.sync_snapshot_flat_cache();
2864        self.snapshot_flat_cache.borrow().rows.clone()
2865    }
2866
2867    /// Rebuilds snapshot rows when bound-node revision or expansion IDs change.
2868    ///
2869    /// Static unbound nodes use revision zero and rebuild only on first access or
2870    /// expansion change.
2871    fn sync_snapshot_flat_cache(&self) {
2872        let expanded = self.expanded_values();
2873        let nodes_revision = self.bound_nodes.as_ref().map_or(0, Signal::revision);
2874        {
2875            let cache = self.snapshot_flat_cache.borrow();
2876            if cache.initialized
2877                && cache.nodes_revision == nodes_revision
2878                && cache.expanded == expanded
2879            {
2880                return;
2881            }
2882        }
2883        let mut out = Vec::new();
2884        for node in &self.current_nodes() {
2885            flatten_node(node, 0, None, &expanded, &mut out);
2886        }
2887        let mut cache = self.snapshot_flat_cache.borrow_mut();
2888        cache.nodes_revision = nodes_revision;
2889        cache.initialized = true;
2890        cache.expanded = expanded;
2891        cache.rows = out;
2892        cache.rebuilds = cache.rebuilds.saturating_add(1);
2893        if let Some(diagnostics) = &self.diagnostics {
2894            let rows = cache.rows.len() as u64;
2895            let rebuilds = cache.rebuilds;
2896            diagnostics.update(|snapshot| {
2897                snapshot.flatten_rebuilds = rebuilds;
2898                snapshot.snapshot_rows_cloned = snapshot.snapshot_rows_cloned.saturating_add(rows);
2899            });
2900        }
2901    }
2902
2903    /// Selects all rows or a viewport/finite-height range plus eight-row overscan.
2904    fn layout_row_range(
2905        &self,
2906        ctx: &LayoutCtx<'_>,
2907        constraints: Constraints,
2908        len: usize,
2909    ) -> std::ops::Range<usize> {
2910        if !self.virtualized || len == 0 {
2911            return 0..len;
2912        }
2913        if let Some(viewport) = ctx.virtual_viewport() {
2914            return row_range_with_overscan(
2915                viewport.rect.y,
2916                viewport.rect.h,
2917                self.style.padding_y,
2918                self.style.row_height,
2919                len,
2920                TREE_VIRTUAL_OVERSCAN_ROWS,
2921            );
2922        }
2923        if constraints.max_h.is_finite() {
2924            return row_range_with_overscan(
2925                0.0,
2926                constraints.max_h,
2927                self.style.padding_y,
2928                self.style.row_height,
2929                len,
2930                TREE_VIRTUAL_OVERSCAN_ROWS,
2931            );
2932        }
2933        0..len
2934    }
2935
2936    /// Normalizes active row against draft, retained, or snapshot sources.
2937    fn normalized_active_index_for_source(&self) -> Option<usize> {
2938        if self.draft.read().is_some() {
2939            let nodes = self.visible_nodes();
2940            return self.normalized_active_index(&nodes);
2941        }
2942        if let Some(model) = &self.model {
2943            if let Some(index) = self.active_index.read() {
2944                if model.flat_node_at(index).is_some_and(|node| !node.disabled) {
2945                    return Some(index);
2946                }
2947            }
2948            if let Some(selected) = self.selected_value() {
2949                if let Some(index) = model.row_of(&selected) {
2950                    if model.flat_node_at(index).is_some_and(|node| !node.disabled) {
2951                        return Some(index);
2952                    }
2953                }
2954            }
2955            return model.first_enabled_row();
2956        }
2957        let nodes = self.visible_nodes_snapshot();
2958        self.normalized_active_index(&nodes)
2959    }
2960
2961    /// Computes one padded logical-pixel row rectangle.
2962    fn row_rect(&self, bounds: Rect, index: usize) -> Rect {
2963        Rect::new(
2964            bounds.x + self.style.padding_x,
2965            bounds.y + self.style.padding_y + index as f32 * self.style.row_height,
2966            (bounds.w - self.style.padding_x * 2.0).max(0.0),
2967            self.style.row_height,
2968        )
2969    }
2970
2971    /// Maps a y coordinate to one row and records bounded hit-test diagnostics.
2972    fn row_index_at(&self, bounds: Rect, y: f32, len: usize) -> Option<usize> {
2973        if let Some(diagnostics) = &self.diagnostics {
2974            diagnostics.update(|snapshot| {
2975                snapshot.hit_tests = snapshot.hit_tests.saturating_add(1);
2976            });
2977        }
2978        let local_y = y - bounds.y - self.style.padding_y;
2979        if local_y < 0.0 {
2980            return None;
2981        }
2982        let idx = (local_y / self.style.row_height).floor() as usize;
2983        let result = (idx < len).then_some(idx);
2984        if result.is_some() {
2985            if let Some(diagnostics) = &self.diagnostics {
2986                diagnostics.update(|snapshot| {
2987                    snapshot.hit_test_rows_visited =
2988                        snapshot.hit_test_rows_visited.saturating_add(1);
2989                });
2990            }
2991        }
2992        result
2993    }
2994
2995    /// Selects all rows or current clip range plus eight-row overscan for paint.
2996    fn paint_row_range(
2997        &self,
2998        ctx: &PaintCtx<'_>,
2999        bounds: Rect,
3000        len: usize,
3001    ) -> std::ops::Range<usize> {
3002        if !self.virtualized || len == 0 {
3003            return 0..len;
3004        }
3005        let clip = ctx.current_clip_bbox().unwrap_or(bounds);
3006        row_range_with_overscan(
3007            clip.y - bounds.y,
3008            clip.h,
3009            self.style.padding_y,
3010            self.style.row_height,
3011            len,
3012            TREE_VIRTUAL_OVERSCAN_ROWS,
3013        )
3014    }
3015
3016    /// Computes depth-indented branch-chevron geometry.
3017    fn chevron_rect(&self, row: Rect, node: &FlatNode<T>) -> Rect {
3018        let x = row.x + node.depth as f32 * self.style.indent;
3019        Rect::new(
3020            x,
3021            row.y + (row.h - self.style.chevron_size) * 0.5,
3022            self.style.chevron_size,
3023            self.style.chevron_size,
3024        )
3025    }
3026
3027    /// Computes text origin after chevron and optional leading icon.
3028    fn label_x(&self, row: Rect, node: &FlatNode<T>) -> f32 {
3029        let chevron = self.chevron_rect(row, node);
3030        let mut x = chevron.right() + self.style.gap;
3031        if node.leading_icon.is_some() {
3032            x += self.style.icon_size + self.style.gap;
3033        }
3034        x
3035    }
3036
3037    /// Computes inline editor bounds with 32x18-pixel minimums.
3038    fn edit_rect(&self, row: Rect, node: &FlatNode<T>) -> Rect {
3039        let x = self.label_x(row, node);
3040        Rect::new(
3041            x - 4.0,
3042            row.y + 2.0,
3043            (row.right() - x + 4.0).max(32.0),
3044            (row.h - 4.0).max(18.0),
3045        )
3046    }
3047
3048    /// Resolves action hit size from row/icon metrics, capped at 28 pixels.
3049    fn trailing_action_size(&self) -> f32 {
3050        self.style
3051            .row_height
3052            .min(28.0)
3053            .max(self.style.icon_size + 6.0)
3054    }
3055
3056    /// Places the selected-row trailing action at the row's right edge.
3057    fn trailing_action_rect(&self, row: Rect) -> Rect {
3058        let size = self.trailing_action_size();
3059        Rect::new(row.right() - size, row.y + (row.h - size) * 0.5, size, size)
3060    }
3061
3062    /// Centers the configured icon size inside an action hit rectangle.
3063    fn trailing_action_icon_rect(&self, action: Rect) -> Rect {
3064        Rect::new(
3065            action.x + (action.w - self.style.icon_size) * 0.5,
3066            action.y + (action.h - self.style.icon_size) * 0.5,
3067            self.style.icon_size,
3068            self.style.icon_size,
3069        )
3070    }
3071
3072    /// Derives single-line editor style from tree tokens and default theme.
3073    fn edit_text_style(&self) -> TextInputStyle {
3074        let theme = Theme::default();
3075        let palette = theme.palette();
3076        TextInputStyle {
3077            bg: self.style.editing_background,
3078            border: self.style.editing_border,
3079            border_focused: self.style.editing_border,
3080            caret: palette.text,
3081            placeholder: palette.text_muted,
3082            selection_bg: palette.accent.with_alpha(0.34),
3083            radius: self.style.radius.tl,
3084            pad_x: 4.0,
3085            pad_y: 2.0,
3086            text: self.style.text,
3087            caret_w: 1.0,
3088            caret_blink_ms: 500,
3089        }
3090    }
3091
3092    /// Paints a two-pixel sibling line or inside surface/border.
3093    fn paint_drop_target(&self, ctx: &mut PaintCtx<'_>, row: Rect, drop: &TreeDropTarget<T>) {
3094        match drop.position {
3095            TreeDropPosition::Before | TreeDropPosition::After => {
3096                let y = if drop.position == TreeDropPosition::Before {
3097                    row.y
3098                } else {
3099                    row.bottom() - 2.0
3100                };
3101                ctx.push(DrawCmd::Rect(DrawRect {
3102                    rect: Rect::new(row.x, y, row.w, 2.0),
3103                    color: self.style.drop_indicator,
3104                }));
3105            }
3106            TreeDropPosition::Inside => {
3107                ctx.push(DrawCmd::RRect(DrawRRect {
3108                    rect: row,
3109                    radius: self.style.radius.tl,
3110                    color: self.style.drop_inside_background,
3111                }));
3112                ctx.push(DrawCmd::Border(DrawBorder {
3113                    rect: row,
3114                    radius: self.style.radius,
3115                    border: Border::new(1.0, self.style.drop_indicator),
3116                }));
3117            }
3118        }
3119    }
3120
3121    /// Paints chevron, leading icon, label/editor, and selected trailing action.
3122    fn paint_node(&self, ctx: &mut PaintCtx<'_>, paint: TreeNodePaint<'_, T>) {
3123        let TreeNodePaint {
3124            row,
3125            node,
3126            selected,
3127            opacity,
3128            layout,
3129            focused,
3130            editing,
3131        } = paint;
3132        let chevron = self.chevron_rect(row, node);
3133        if node.branch {
3134            let icon = if self.is_expanded(&node.id) {
3135                IconId::Lucide(LucideIcon::ChevronDown)
3136            } else {
3137                IconId::Lucide(LucideIcon::ChevronRight)
3138            };
3139            ctx.push(DrawCmd::Image(DrawImage {
3140                rect: chevron,
3141                icon,
3142                tint: self
3143                    .style
3144                    .chevron_tint
3145                    .with_alpha(self.style.chevron_tint.a * opacity),
3146                rotation_rad: 0.0,
3147            }));
3148        }
3149
3150        let mut x = chevron.right() + self.style.gap;
3151        if let Some(icon) = &node.leading_icon {
3152            let rect = Rect::new(
3153                x,
3154                row.y + (row.h - self.style.icon_size) * 0.5,
3155                self.style.icon_size,
3156                self.style.icon_size,
3157            );
3158            let tint = if let Some(tint) = node.leading_icon_tint {
3159                tint
3160            } else if selected {
3161                self.style.selected_icon_tint
3162            } else {
3163                self.style.icon_tint
3164            };
3165            ctx.push(DrawCmd::Image(DrawImage {
3166                rect,
3167                icon: icon.clone(),
3168                tint: tint.with_alpha(tint.a * opacity),
3169                rotation_rad: 0.0,
3170            }));
3171            x += self.style.icon_size + self.style.gap;
3172        }
3173
3174        if editing.is_some() {
3175            let edit_rect = self.edit_rect(row, node);
3176            let style = self.edit_text_style();
3177            ctx.push(DrawCmd::RRect(DrawRRect {
3178                rect: edit_rect,
3179                radius: style.radius,
3180                color: style.bg,
3181            }));
3182            ctx.push(DrawCmd::Border(DrawBorder {
3183                rect: edit_rect,
3184                radius: Radius::uniform(style.radius),
3185                border: Border::new(
3186                    1.0,
3187                    if focused {
3188                        style.border_focused
3189                    } else {
3190                        style.border
3191                    },
3192                ),
3193            }));
3194            paint_single_line_text(
3195                ctx,
3196                edit_rect,
3197                layout,
3198                &self.edit_value,
3199                &self.edit_buffer,
3200                &self.edit_state,
3201                None,
3202                style,
3203                focused,
3204            );
3205        } else {
3206            paint_text_centered(ctx, &node.label, self.text_style(node), row, x, opacity);
3207        }
3208
3209        if selected {
3210            if let Some(action) = &node.trailing_action {
3211                let action_rect = self.trailing_action_rect(row);
3212                let bg = self
3213                    .style
3214                    .selected_background
3215                    .with_alpha((self.style.selected_background.a + 0.10).min(0.42) * opacity);
3216                if bg.a > 0.0 {
3217                    ctx.push(DrawCmd::RRect(DrawRRect {
3218                        rect: action_rect,
3219                        radius: self.style.radius.tl,
3220                        color: bg,
3221                    }));
3222                }
3223                let tint = self
3224                    .style
3225                    .selected_icon_tint
3226                    .with_alpha(self.style.selected_icon_tint.a * opacity);
3227                ctx.push(DrawCmd::Image(DrawImage {
3228                    rect: self.trailing_action_icon_rect(action_rect),
3229                    icon: action.icon.clone(),
3230                    tint,
3231                    rotation_rad: 0.0,
3232                }));
3233            }
3234        }
3235    }
3236
3237    /// Chooses disabled, selected, or normal text style in precedence order.
3238    fn text_style(&self, node: &FlatNode<T>) -> TextStyle {
3239        if node.disabled || self.disabled.read() {
3240            self.style.disabled_text
3241        } else if self
3242            .selected_value()
3243            .as_ref()
3244            .is_some_and(|selected| selected == &node.id)
3245        {
3246            self.style.selected_text
3247        } else {
3248            self.style.text
3249        }
3250    }
3251
3252    /// Returns valid enabled active row, selected match, or first enabled row.
3253    fn normalized_active_index(&self, nodes: &[FlatNode<T>]) -> Option<usize> {
3254        let active = self.active_index.read();
3255        if let Some(idx) = active {
3256            if idx < nodes.len() && !nodes[idx].disabled {
3257                return Some(idx);
3258            }
3259        }
3260        if let Some(selected) = self.selected_value() {
3261            if let Some(idx) = nodes
3262                .iter()
3263                .position(|node| !node.disabled && node.id == selected)
3264            {
3265                return Some(idx);
3266            }
3267        }
3268        nodes.iter().position(|node| !node.disabled)
3269    }
3270
3271    /// Handles enabled row release: chevron toggle or selection/double activation.
3272    fn handle_pointer(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
3273        let Some(idx) = self.row_index_at(bounds, pos.y, self.visible_len()) else {
3274            return;
3275        };
3276        let Some(node) = self.visible_node_at(idx) else {
3277            return;
3278        };
3279        if node.disabled {
3280            return;
3281        }
3282        self.active_index.set(Some(idx));
3283        let row = self.row_rect(bounds, idx);
3284        if node.branch && self.chevron_rect(row, &node).contains(pos.x, pos.y) {
3285            self.toggle_node(ctx, &node);
3286        } else {
3287            let click_count = self.register_row_click(ctx, &node, pos);
3288            self.select_node(ctx, &node);
3289            if click_count == 2 {
3290                self.activate_node(ctx, &node);
3291            }
3292        }
3293    }
3294
3295    /// Emits row/blank context, selecting an enabled row first when needed.
3296    fn handle_context_menu(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
3297        let Some(on_context_menu) = &self.on_context_menu else {
3298            return;
3299        };
3300        if let Some(idx) = self.row_index_at(bounds, pos.y, self.visible_len()) {
3301            let Some(node) = self.visible_node_at(idx) else {
3302                return;
3303            };
3304            if node.disabled {
3305                return;
3306            }
3307            self.active_index.set(Some(idx));
3308            let row = self.row_rect(bounds, idx);
3309            let selected = self.selected_value();
3310            if selected
3311                .as_ref()
3312                .is_none_or(|selected| selected != &node.id)
3313            {
3314                self.select_node(ctx, &node);
3315            }
3316            on_context_menu(
3317                ctx,
3318                TreeContextMenu::Row {
3319                    row_id: node.id.clone(),
3320                    pointer_position: pos,
3321                    row_rect: row,
3322                },
3323            );
3324            ctx.request_repaint();
3325            ctx.stop_propagation();
3326            return;
3327        }
3328        on_context_menu(
3329            ctx,
3330            TreeContextMenu::Blank {
3331                pointer_position: pos,
3332            },
3333        );
3334        ctx.request_repaint();
3335        ctx.stop_propagation();
3336    }
3337
3338    /// Arms trailing-action release or a structurally capable drag candidate.
3339    fn handle_pointer_press(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
3340        let Some(idx) = self.row_index_at(bounds, pos.y, self.visible_len()) else {
3341            return;
3342        };
3343        let Some(node) = self.visible_node_at(idx) else {
3344            return;
3345        };
3346        if node.disabled {
3347            return;
3348        }
3349        self.active_index.set(Some(idx));
3350        let row = self.row_rect(bounds, idx);
3351        if self.trailing_action_hit(row, &node, pos) {
3352            ctx.stop_propagation();
3353            ctx.request_repaint();
3354            return;
3355        }
3356        if self.draggable.read()
3357            && self.can_mutate_nodes()
3358            && !self.chevron_rect(row, &node).contains(pos.x, pos.y)
3359        {
3360            self.drag.set(Some(TreeDragState {
3361                source: node.id.clone(),
3362                start: pos,
3363                active: false,
3364                target: None,
3365            }));
3366            ctx.stop_propagation();
3367        }
3368    }
3369
3370    /// Activates drag after four pixels and updates current drop target.
3371    fn handle_pointer_move(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
3372        let Some(mut drag) = self.drag.read() else {
3373            return;
3374        };
3375        if !drag.active {
3376            let dx = pos.x - drag.start.x;
3377            let dy = pos.y - drag.start.y;
3378            if (dx * dx + dy * dy).sqrt() > 4.0 {
3379                drag.active = true;
3380            }
3381        }
3382        if drag.active {
3383            drag.target = self.drop_target_at(bounds, pos, &drag.source);
3384            ctx.request_repaint();
3385        }
3386        self.drag.set(Some(drag));
3387        ctx.stop_propagation();
3388    }
3389
3390    /// Commits active drag, emits selected trailing action, or handles row click.
3391    fn handle_pointer_release(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
3392        if let Some(drag) = self.drag.read() {
3393            self.drag.set(None);
3394            if drag.active {
3395                if let Some(drop) = drag.target {
3396                    self.apply_drop(ctx, drag.source, drop);
3397                } else {
3398                    ctx.request_repaint();
3399                    ctx.stop_propagation();
3400                }
3401                return;
3402            }
3403        }
3404        if let Some(idx) = self.row_index_at(bounds, pos.y, self.visible_len()) {
3405            let Some(node) = self.visible_node_at(idx) else {
3406                return;
3407            };
3408            let row = self.row_rect(bounds, idx);
3409            if self.trailing_action_hit(row, &node, pos) {
3410                self.active_index.set(Some(idx));
3411                self.emit_trailing_action(ctx, &node);
3412                return;
3413            }
3414        }
3415        if bounds.contains(pos.x, pos.y) {
3416            self.handle_pointer(ctx, bounds, pos);
3417        }
3418    }
3419
3420    /// Tests an enabled selected row's configured trailing-action rectangle.
3421    fn trailing_action_hit(&self, row: Rect, node: &FlatNode<T>, pos: Point) -> bool {
3422        if node.disabled || node.trailing_action.is_none() {
3423            return false;
3424        }
3425        let Some(selected) = self.selected_value() else {
3426            return false;
3427        };
3428        if selected != node.id {
3429            return false;
3430        }
3431        self.trailing_action_rect(row).contains(pos.x, pos.y)
3432    }
3433
3434    /// Invokes configured trailing action and consumes the event when eligible.
3435    fn emit_trailing_action(&self, ctx: &mut EventCtx<A>, node: &FlatNode<T>) {
3436        if node.disabled || node.trailing_action.is_none() {
3437            return;
3438        }
3439        if let Some(on_trailing_action) = &self.on_trailing_action {
3440            on_trailing_action(ctx, node.id.clone());
3441            ctx.request_repaint();
3442            ctx.stop_propagation();
3443        }
3444    }
3445
3446    /// Resolves an enabled non-self target using vertical thirds of its row.
3447    fn drop_target_at(&self, bounds: Rect, pos: Point, source: &T) -> Option<TreeDropTarget<T>> {
3448        let nodes = self.visible_nodes();
3449        let idx = self.row_index_at(bounds, pos.y, nodes.len())?;
3450        let node = &nodes[idx];
3451        if node.disabled || &node.id == source {
3452            return None;
3453        }
3454        let row = self.row_rect(bounds, idx);
3455        let local_y = ((pos.y - row.y) / row.h.max(1.0)).clamp(0.0, 1.0);
3456        let position = if local_y < 0.33 {
3457            TreeDropPosition::Before
3458        } else if local_y > 0.66 {
3459            TreeDropPosition::After
3460        } else {
3461            TreeDropPosition::Inside
3462        };
3463        Some(TreeDropTarget {
3464            target: node.id.clone(),
3465            position,
3466        })
3467    }
3468
3469    /// Routes navigation, expansion, activation, edit/create/delete, and shortcuts.
3470    fn handle_keyboard(&self, ctx: &mut EventCtx<A>, key: &KeyEvent) {
3471        let nodes = self.visible_nodes();
3472        if nodes.is_empty() || self.editing.read().is_some() {
3473            return;
3474        }
3475        let active = self.normalized_active_index(&nodes);
3476        let shortcut_target = self.shortcut_target_node(&nodes, active);
3477        if self.handle_keyboard_shortcut(ctx, key, shortcut_target) {
3478            return;
3479        }
3480        match &key.key {
3481            Key::Named(NamedKey::F(2)) => {
3482                if let Some(idx) = active {
3483                    self.start_rename(ctx, &nodes[idx]);
3484                }
3485            }
3486            Key::Named(NamedKey::Delete) => {
3487                if let Some(idx) = active {
3488                    self.delete_node(ctx, &nodes, idx);
3489                }
3490            }
3491            Key::Named(NamedKey::Insert) if key.modifiers.ctrl => {
3492                if let Some(idx) = active {
3493                    self.create_node(ctx, &nodes, idx, TreeCreateKind::Child);
3494                }
3495            }
3496            Key::Named(NamedKey::Insert) => {
3497                if let Some(idx) = active {
3498                    self.create_node(ctx, &nodes, idx, TreeCreateKind::SiblingAfter);
3499                }
3500            }
3501            Key::Named(NamedKey::ArrowDown) => {
3502                self.move_active(ctx, next_enabled(&nodes, active, 1));
3503            }
3504            Key::Named(NamedKey::ArrowUp) => {
3505                self.move_active(ctx, next_enabled(&nodes, active, -1));
3506            }
3507            Key::Named(NamedKey::Home) => {
3508                self.move_active(ctx, nodes.iter().position(|node| !node.disabled));
3509            }
3510            Key::Named(NamedKey::End) => {
3511                self.move_active(ctx, nodes.iter().rposition(|node| !node.disabled));
3512            }
3513            Key::Named(NamedKey::ArrowRight) => {
3514                if let Some(idx) = active {
3515                    let node = &nodes[idx];
3516                    if node.branch && !self.is_expanded(&node.id) {
3517                        self.toggle_node(ctx, node);
3518                    } else if node.branch {
3519                        self.move_active(ctx, first_visible_child_index(&nodes, idx));
3520                    }
3521                }
3522            }
3523            Key::Named(NamedKey::ArrowLeft) => {
3524                if let Some(idx) = active {
3525                    let node = &nodes[idx];
3526                    if node.branch && self.is_expanded(&node.id) {
3527                        self.toggle_node(ctx, node);
3528                    } else if let Some(parent) = &node.parent {
3529                        self.move_active(ctx, nodes.iter().position(|row| &row.id == parent));
3530                    }
3531                }
3532            }
3533            Key::Named(NamedKey::Enter) => {
3534                if let Some(idx) = active {
3535                    if self.on_activate.is_some() {
3536                        self.activate_node(ctx, &nodes[idx]);
3537                    } else {
3538                        self.select_node(ctx, &nodes[idx]);
3539                    }
3540                }
3541            }
3542            Key::Named(NamedKey::Space) => {
3543                if let Some(idx) = active {
3544                    let node = &nodes[idx];
3545                    if node.branch {
3546                        self.toggle_node(ctx, node);
3547                    } else {
3548                        self.select_node(ctx, node);
3549                    }
3550                }
3551            }
3552            _ => {}
3553        }
3554    }
3555
3556    /// Emits configured Delete or Control-C/X/V shortcut before built-ins.
3557    ///
3558    /// Returns whether a shortcut was emitted and consumed.
3559    fn handle_keyboard_shortcut(
3560        &self,
3561        ctx: &mut EventCtx<A>,
3562        key: &KeyEvent,
3563        active: Option<&FlatNode<T>>,
3564    ) -> bool {
3565        let Some(on_shortcut) = &self.on_shortcut else {
3566            return false;
3567        };
3568        if key.modifiers.alt || key.modifiers.meta {
3569            return false;
3570        }
3571        let shortcut = match &key.key {
3572            Key::Named(NamedKey::Delete) => {
3573                let Some(active) = active else {
3574                    return false;
3575                };
3576                Some(TreeShortcut::Delete {
3577                    id: active.id.clone(),
3578                })
3579            }
3580            Key::Character(_) if key.modifiers.ctrl => match key_character_upper(key).as_deref() {
3581                Some("C") => active.map(|node| TreeShortcut::Copy {
3582                    id: node.id.clone(),
3583                }),
3584                Some("X") => active.map(|node| TreeShortcut::Cut {
3585                    id: node.id.clone(),
3586                }),
3587                Some("V") => Some(TreeShortcut::Paste {
3588                    id: active.map(|node| node.id.clone()),
3589                }),
3590                _ => None,
3591            },
3592            _ => None,
3593        };
3594        let Some(shortcut) = shortcut else {
3595            return false;
3596        };
3597        on_shortcut(ctx, shortcut);
3598        ctx.request_repaint();
3599        ctx.stop_propagation();
3600        true
3601    }
3602
3603    /// Prefers enabled controlled selection, then enabled active row as target.
3604    fn shortcut_target_node<'a>(
3605        &self,
3606        nodes: &'a [FlatNode<T>],
3607        active: Option<usize>,
3608    ) -> Option<&'a FlatNode<T>> {
3609        if let Some(selected) = self.selected_value() {
3610            if let Some(node) = nodes
3611                .iter()
3612                .find(|node| !node.disabled && node.id == selected)
3613            {
3614                return Some(node);
3615            }
3616        }
3617        active.and_then(|idx| nodes.get(idx).filter(|node| !node.disabled))
3618    }
3619
3620    /// Stores a changed active row and consumes the navigation event.
3621    fn move_active(&self, ctx: &mut EventCtx<A>, next: Option<usize>) {
3622        if next != self.active_index.read() {
3623            self.active_index.set(next);
3624            ctx.request_repaint();
3625            ctx.stop_propagation();
3626        }
3627    }
3628
3629    /// Writes/emits only a changed enabled selection.
3630    fn select_node(&self, ctx: &mut EventCtx<A>, node: &FlatNode<T>) {
3631        if node.disabled {
3632            return;
3633        }
3634        let changed = self
3635            .selected_value()
3636            .as_ref()
3637            .is_none_or(|selected| selected != &node.id);
3638        if changed {
3639            if let Some(bound) = &self.bound_selected {
3640                bound.set(node.id.clone());
3641            }
3642            if let Some(on_select) = &self.on_select {
3643                on_select(ctx, node.id.clone());
3644            }
3645            ctx.request_repaint();
3646            ctx.stop_propagation();
3647        }
3648    }
3649
3650    /// Emits explicit activation only for enabled nodes with a handler.
3651    fn activate_node(&self, ctx: &mut EventCtx<A>, node: &FlatNode<T>) {
3652        if node.disabled {
3653            return;
3654        }
3655        if let Some(on_activate) = &self.on_activate {
3656            on_activate(ctx, node.id.clone());
3657            ctx.request_repaint();
3658            ctx.stop_propagation();
3659        }
3660    }
3661
3662    /// Registers a click and returns a 1..=3 count under time/distance/ID rules.
3663    fn register_row_click(&self, ctx: &EventCtx<A>, node: &FlatNode<T>, pos: Point) -> u8 {
3664        let now = ctx
3665            .event_meta()
3666            .map(|meta| TreeClickTimestamp::Event(meta.timestamp().duration()))
3667            .unwrap_or_else(|| TreeClickTimestamp::Legacy(Instant::now()));
3668        let next = self
3669            .last_click
3670            .read()
3671            .filter(|last| {
3672                last.id == node.id
3673                    && now
3674                        .elapsed_since(last.at)
3675                        .is_some_and(|elapsed| elapsed <= TREE_ACTIVATE_MAX_DELAY)
3676                    && point_distance_sq(last.pos, pos)
3677                        <= TREE_ACTIVATE_MAX_DISTANCE * TREE_ACTIVATE_MAX_DISTANCE
3678            })
3679            .map(|last| last.count.saturating_add(1).min(3))
3680            .unwrap_or(1);
3681        self.last_click.set(Some(TreeClickState {
3682            at: now,
3683            pos,
3684            id: node.id.clone(),
3685            count: next,
3686        }));
3687        next
3688    }
3689
3690    /// Applies/emits a valid branch's requested next expansion state.
3691    ///
3692    /// Retained `ApplyLocal` must successfully mutate the model; retained
3693    /// `IntentOnly` emits without mutation. Snapshot mutation uses a writable
3694    /// expansion signal when available.
3695    fn toggle_node(&self, ctx: &mut EventCtx<A>, node: &FlatNode<T>) {
3696        if node.disabled || !node.branch {
3697            return;
3698        }
3699        let next_open = !self.is_expanded(&node.id);
3700        if let Some(model) = &self.model {
3701            if self.mutation_mode.read() == TreeMutationMode::ApplyLocal
3702                && !model.set_expanded(node.id.clone(), next_open)
3703            {
3704                return;
3705            }
3706        } else {
3707            let mut expanded = self.expanded_values();
3708            if next_open {
3709                if !expanded.iter().any(|id| id == &node.id) {
3710                    expanded.push(node.id.clone());
3711                }
3712            } else {
3713                expanded.retain(|id| id != &node.id);
3714            }
3715            if let Some(bound) = &self.mutable_expanded {
3716                bound.set(expanded);
3717            }
3718        }
3719        if let Some(on_toggle) = &self.on_toggle {
3720            on_toggle(ctx, node.id.clone(), next_open);
3721        }
3722        let active = self.model.as_ref().map_or_else(
3723            || {
3724                self.visible_nodes_snapshot()
3725                    .iter()
3726                    .position(|row| !row.disabled && row.id == node.id)
3727            },
3728            |model| {
3729                let row = model.row_of(&node.id)?;
3730                Some(self.source_index_to_visible(row))
3731            },
3732        );
3733        self.active_index.set(active);
3734        ctx.request_repaint();
3735        ctx.stop_propagation();
3736    }
3737
3738    /// Reads expansion from retained model or deduplicated snapshot IDs.
3739    fn is_expanded(&self, id: &T) -> bool {
3740        self.model.as_ref().map_or_else(
3741            || self.expanded_values().iter().any(|expanded| expanded == id),
3742            |model| model.is_expanded(id),
3743        )
3744    }
3745
3746    /// Handles focus loss, Escape/Enter, outside click, or single-line editing.
3747    ///
3748    /// Returns whether an active editor consumed/routed the event.
3749    fn handle_editing_event(
3750        &self,
3751        ctx: &mut EventCtx<A>,
3752        event: &Event,
3753        bounds: Rect,
3754        layout: &LayoutResult,
3755    ) -> bool {
3756        let Some(editing) = self.editing.read() else {
3757            return false;
3758        };
3759        let nodes = self.visible_nodes();
3760        let Some(idx) = nodes.iter().position(|node| node.id == editing.id) else {
3761            self.cancel_rename(ctx);
3762            return true;
3763        };
3764        let row = self.row_rect(bounds, idx);
3765        let edit_rect = self.edit_rect(row, &nodes[idx]);
3766        match event {
3767            Event::Focus(focus) if !focus.focused => {
3768                if !self.commit_rename(ctx) {
3769                    self.cancel_rename(ctx);
3770                }
3771                true
3772            }
3773            Event::Keyboard(key)
3774                if key.state == KeyState::Pressed && key.key == Key::Named(NamedKey::Escape) =>
3775            {
3776                self.cancel_rename(ctx);
3777                ctx.stop_propagation();
3778                true
3779            }
3780            Event::Keyboard(key)
3781                if key.state == KeyState::Pressed && key.key == Key::Named(NamedKey::Enter) =>
3782            {
3783                self.commit_rename(ctx);
3784                ctx.stop_propagation();
3785                true
3786            }
3787            Event::Pointer(PointerEvent::Button {
3788                pos,
3789                button: MouseButton::Left,
3790                pressed: true,
3791                ..
3792            }) if !edit_rect.contains(pos.x, pos.y) => {
3793                self.commit_rename(ctx);
3794                ctx.stop_propagation();
3795                true
3796            }
3797            _ => handle_single_line_text_event(
3798                ctx,
3799                event,
3800                edit_rect,
3801                layout,
3802                &self.edit_value,
3803                &self.edit_buffer,
3804                &self.edit_state,
3805                self.edit_text_style(),
3806                TextFieldEventOptions {
3807                    consume_handled_events: true,
3808                },
3809            ),
3810        }
3811    }
3812
3813    /// Begins an ordinary rename and consumes input on success.
3814    fn start_rename(&self, ctx: &mut EventCtx<A>, node: &FlatNode<T>) {
3815        if self.begin_rename(node) {
3816            ctx.request_repaint();
3817            ctx.stop_propagation();
3818        }
3819    }
3820
3821    /// Initializes full-label selection for an eligible ordinary rename.
3822    fn begin_rename(&self, node: &FlatNode<T>) -> bool {
3823        if !self.editable.read() || !self.can_mutate_nodes() || node.disabled {
3824            return false;
3825        }
3826        let mut edit_state = TextEditState::new();
3827        edit_state.caret_byte = node.label.len();
3828        edit_state.selection = Some(TextSelection {
3829            anchor: 0,
3830            caret: node.label.len(),
3831        });
3832        self.editing.set(Some(TreeEditing {
3833            id: node.id.clone(),
3834            original: node.label.clone(),
3835            create: None,
3836        }));
3837        self.edit_value.set(node.label.clone());
3838        self.edit_buffer
3839            .set(TextBuffer::from_string(node.label.clone()));
3840        self.edit_state.set(edit_state);
3841        true
3842    }
3843
3844    /// Runs the factory and begins external-command create editing when eligible.
3845    fn begin_create_from_request(&self, request: TreeCreateRequest<T>) -> bool {
3846        if !self.creatable.read() || !self.can_mutate_nodes() {
3847            return false;
3848        }
3849        let Some(factory) = &self.create_node else {
3850            return false;
3851        };
3852        let Some(node) = factory(request.clone()) else {
3853            return false;
3854        };
3855        if self.model.is_some() && self.mutation_mode.read() == TreeMutationMode::IntentOnly {
3856            return self.begin_retained_create(node, request);
3857        }
3858        let created_id = node.id.clone();
3859        let mut nodes = self.current_nodes();
3860        if !insert_created_node(&mut nodes, &request, node) {
3861            return false;
3862        }
3863        self.set_current_nodes(nodes);
3864        if request.kind == TreeCreateKind::Child {
3865            if let Some(parent) = &request.parent {
3866                self.ensure_expanded(parent.clone());
3867            }
3868        }
3869        if let Some(bound) = &self.bound_selected {
3870            bound.set(created_id.clone());
3871        }
3872        self.active_index.set(
3873            self.visible_nodes()
3874                .iter()
3875                .position(|node| !node.disabled && node.id == created_id),
3876        );
3877        let nodes = self.visible_nodes();
3878        if let Some(node) = nodes.iter().find(|node| node.id == created_id) {
3879            return self.begin_create_rename(node, request);
3880        }
3881        true
3882    }
3883
3884    /// Initializes full-label selection and retains create cancellation metadata.
3885    fn begin_create_rename(&self, node: &FlatNode<T>, request: TreeCreateRequest<T>) -> bool {
3886        if !self.editable.read() || !self.can_mutate_nodes() || node.disabled {
3887            return false;
3888        }
3889        let mut edit_state = TextEditState::new();
3890        edit_state.caret_byte = node.label.len();
3891        edit_state.selection = Some(TextSelection {
3892            anchor: 0,
3893            caret: node.label.len(),
3894        });
3895        self.editing.set(Some(TreeEditing {
3896            id: node.id.clone(),
3897            original: node.label.clone(),
3898            create: Some(request),
3899        }));
3900        self.edit_value.set(node.label.clone());
3901        self.edit_buffer
3902            .set(TextBuffer::from_string(node.label.clone()));
3903        self.edit_state.set(edit_state);
3904        true
3905    }
3906
3907    /// Clears editor/draft state and removes/callbacks a cancelled create draft.
3908    fn cancel_rename(&self, ctx: &mut EventCtx<A>) {
3909        if let Some(editing) = self.editing.read() {
3910            if let Some(request) = editing.create.clone() {
3911                if let Some(on_create_cancel) = &self.on_create_cancel {
3912                    on_create_cancel(
3913                        ctx,
3914                        TreeCreateCancel {
3915                            id: editing.id.clone(),
3916                            request,
3917                        },
3918                    );
3919                }
3920            }
3921            if editing.create.is_some() {
3922                let mut nodes = self.current_nodes();
3923                if delete_node_by_id(&mut nodes, &editing.id).is_some() {
3924                    let _ = self.set_current_nodes(nodes);
3925                    self.remove_expanded_ids(&[editing.id]);
3926                }
3927            }
3928        }
3929        self.draft.set(None);
3930        self.editing.set(None);
3931        self.edit_value.set(String::new());
3932        self.edit_buffer.set(TextBuffer::from_string(String::new()));
3933        self.edit_state.set(TextEditState::new());
3934        ctx.request_repaint();
3935    }
3936
3937    /// Trims and commits a nonempty editor value according to create/mutation mode.
3938    ///
3939    /// Empty input returns `false` and keeps editing. An unchanged ordinary rename
3940    /// closes successfully without callback. Ordinary changed rename requires a
3941    /// handler; external create emits final label and removes provisional state.
3942    fn commit_rename(&self, ctx: &mut EventCtx<A>) -> bool {
3943        let Some(editing) = self.editing.read() else {
3944            return false;
3945        };
3946        let new_label = self.edit_value.read().trim().to_string();
3947        if new_label.is_empty() {
3948            return false;
3949        }
3950        self.editing.set(None);
3951        let is_create = editing.create.is_some();
3952        if new_label == editing.original && !is_create {
3953            ctx.request_repaint();
3954            return true;
3955        }
3956        if let Some(request) = editing.create {
3957            if self.model.is_some() && self.mutation_mode.read() == TreeMutationMode::IntentOnly {
3958                self.draft.set(None);
3959                if let Some(on_create) = &self.on_create {
3960                    on_create(
3961                        ctx,
3962                        TreeCreate {
3963                            id: editing.id,
3964                            parent: request.parent,
3965                            after: request.after,
3966                            kind: request.kind,
3967                            label: new_label,
3968                        },
3969                    );
3970                }
3971                ctx.request_repaint();
3972                ctx.stop_propagation();
3973                return true;
3974            }
3975            let mut nodes = self.current_nodes();
3976            let _ = delete_node_by_id(&mut nodes, &editing.id);
3977            if !self.set_current_nodes(nodes) {
3978                return false;
3979            }
3980            if let Some(on_create) = &self.on_create {
3981                on_create(
3982                    ctx,
3983                    TreeCreate {
3984                        id: editing.id,
3985                        parent: request.parent,
3986                        after: request.after,
3987                        kind: request.kind,
3988                        label: new_label,
3989                    },
3990                );
3991            }
3992        } else if let Some(on_rename) = &self.on_rename {
3993            if self.model.is_some() && self.mutation_mode.read() == TreeMutationMode::IntentOnly {
3994                on_rename(
3995                    ctx,
3996                    TreeRename {
3997                        id: editing.id,
3998                        old_label: editing.original,
3999                        new_label,
4000                    },
4001                );
4002                ctx.request_repaint();
4003                ctx.stop_propagation();
4004                return true;
4005            }
4006            let mut nodes = self.current_nodes();
4007            let old_label = if new_label == editing.original {
4008                editing.original.clone()
4009            } else {
4010                let Some(old_label) = rename_node_label(&mut nodes, &editing.id, new_label.clone())
4011                else {
4012                    return false;
4013                };
4014                old_label
4015            };
4016            if !self.set_current_nodes(nodes) {
4017                return false;
4018            }
4019            on_rename(
4020                ctx,
4021                TreeRename {
4022                    id: editing.id,
4023                    old_label,
4024                    new_label,
4025                },
4026            );
4027        }
4028        ctx.request_repaint();
4029        ctx.stop_propagation();
4030        true
4031    }
4032
4033    /// Applies local snapshot move or emits intent-only move, then reselects source.
4034    fn apply_drop(&self, ctx: &mut EventCtx<A>, source: T, drop: TreeDropTarget<T>) {
4035        if !self.draggable.read() || !self.can_mutate_nodes() {
4036            return;
4037        }
4038        let apply_local = self.mutation_mode.read() == TreeMutationMode::ApplyLocal;
4039        if apply_local {
4040            let mut nodes = self.current_nodes();
4041            if !move_node(&mut nodes, &source, &drop.target, drop.position) {
4042                ctx.request_repaint();
4043                ctx.stop_propagation();
4044                return;
4045            }
4046            self.set_current_nodes(nodes);
4047            if drop.position == TreeDropPosition::Inside {
4048                self.ensure_expanded(drop.target.clone());
4049            }
4050        }
4051        if let Some(bound) = &self.bound_selected {
4052            bound.set(source.clone());
4053        }
4054        if let Some(on_move) = &self.on_move {
4055            on_move(
4056                ctx,
4057                TreeMove {
4058                    source,
4059                    target: drop.target,
4060                    position: drop.position,
4061                },
4062            );
4063        }
4064        ctx.request_repaint();
4065        ctx.stop_propagation();
4066    }
4067
4068    /// Handles keyboard create request, local insertion/intent, callback, and edit.
4069    fn create_node(
4070        &self,
4071        ctx: &mut EventCtx<A>,
4072        visible: &[FlatNode<T>],
4073        idx: usize,
4074        kind: TreeCreateKind,
4075    ) {
4076        if !self.creatable.read() || !self.can_mutate_nodes() {
4077            return;
4078        }
4079        let Some(factory) = &self.create_node else {
4080            return;
4081        };
4082        let target = &visible[idx];
4083        if target.disabled {
4084            return;
4085        }
4086        let request = match kind {
4087            TreeCreateKind::SiblingAfter => TreeCreateRequest {
4088                parent: target.parent.clone(),
4089                after: Some(target.id.clone()),
4090                kind,
4091                default_label: "New item".to_string(),
4092            },
4093            TreeCreateKind::Child => TreeCreateRequest {
4094                parent: Some(target.id.clone()),
4095                after: None,
4096                kind,
4097                default_label: "New item".to_string(),
4098            },
4099        };
4100        let Some(node) = factory(request.clone()) else {
4101            return;
4102        };
4103        if self.model.is_some() && self.mutation_mode.read() == TreeMutationMode::IntentOnly {
4104            if self.begin_retained_create(node, request) {
4105                ctx.request_repaint();
4106                ctx.stop_propagation();
4107            }
4108            return;
4109        }
4110        let created_id = node.id.clone();
4111        let created_label = node.label.clone();
4112        let mut nodes = self.current_nodes();
4113        if !insert_created_node(&mut nodes, &request, node) {
4114            return;
4115        }
4116        self.set_current_nodes(nodes);
4117        if kind == TreeCreateKind::Child {
4118            self.ensure_expanded(target.id.clone());
4119        }
4120        if let Some(bound) = &self.bound_selected {
4121            bound.set(created_id.clone());
4122        }
4123        if let Some(on_create) = &self.on_create {
4124            on_create(
4125                ctx,
4126                TreeCreate {
4127                    id: created_id.clone(),
4128                    parent: request.parent.clone(),
4129                    after: request.after.clone(),
4130                    kind,
4131                    label: created_label.clone(),
4132                },
4133            );
4134        }
4135        self.start_rename(
4136            ctx,
4137            &FlatNode {
4138                id: created_id,
4139                label: created_label,
4140                depth: target.depth,
4141                branch: false,
4142                disabled: false,
4143                leading_icon: None,
4144                leading_icon_tint: None,
4145                trailing_action: None,
4146                parent: request.parent,
4147            },
4148        );
4149        ctx.request_repaint();
4150        ctx.stop_propagation();
4151    }
4152
4153    /// Deletes locally or emits intent, then chooses the next enabled selection.
4154    fn delete_node(&self, ctx: &mut EventCtx<A>, visible: &[FlatNode<T>], idx: usize) {
4155        if !self.deletable.read() || !self.can_mutate_nodes() {
4156            return;
4157        }
4158        let target = &visible[idx];
4159        if target.disabled {
4160            return;
4161        }
4162        if self.mutation_mode.read() == TreeMutationMode::IntentOnly {
4163            if let Some(on_delete) = &self.on_delete {
4164                on_delete(
4165                    ctx,
4166                    TreeDelete {
4167                        id: target.id.clone(),
4168                        parent: target.parent.clone(),
4169                    },
4170                );
4171            }
4172            ctx.request_repaint();
4173            ctx.stop_propagation();
4174            return;
4175        }
4176        let mut nodes = self.current_nodes();
4177        let Some((deleted, parent)) = delete_node_by_id(&mut nodes, &target.id) else {
4178            return;
4179        };
4180        let deleted_ids = collect_node_ids(&deleted);
4181        self.set_current_nodes(nodes);
4182        self.remove_expanded_ids(&deleted_ids);
4183        let next_idx = next_enabled_after_delete(visible, idx, &deleted_ids);
4184        if let Some(bound) = &self.bound_selected {
4185            if let Some(next) = next_idx.and_then(|idx| visible.get(idx)) {
4186                bound.set(next.id.clone());
4187            }
4188        }
4189        self.active_index.set(next_idx);
4190        if let Some(on_delete) = &self.on_delete {
4191            on_delete(
4192                ctx,
4193                TreeDelete {
4194                    id: deleted.id,
4195                    parent,
4196                },
4197            );
4198        }
4199        ctx.request_repaint();
4200        ctx.stop_propagation();
4201    }
4202
4203    /// Adds an ID to writable snapshot expansion when absent.
4204    fn ensure_expanded(&self, id: T) {
4205        let Some(bound) = &self.mutable_expanded else {
4206            return;
4207        };
4208        let mut expanded = self.expanded_values();
4209        if !expanded.iter().any(|value| value == &id) {
4210            expanded.push(id);
4211            bound.set(expanded);
4212        }
4213    }
4214
4215    /// Removes deleted IDs from writable snapshot expansion.
4216    fn remove_expanded_ids(&self, ids: &[T]) {
4217        let Some(bound) = &self.mutable_expanded else {
4218            return;
4219        };
4220        let mut expanded = self.expanded_values();
4221        expanded.retain(|id| !ids.iter().any(|deleted| deleted == id));
4222        bound.set(expanded);
4223    }
4224}
4225
4226/// Converts viewport geometry to a clamped row range with symmetric overscan.
4227///
4228/// Empty sources, nonpositive row height, or nonpositive viewport height return
4229/// `0..0`; arithmetic uses saturating integer bounds.
4230fn row_range_with_overscan(
4231    viewport_y: f32,
4232    viewport_height: f32,
4233    padding_y: f32,
4234    row_height: f32,
4235    len: usize,
4236    overscan_rows: usize,
4237) -> std::ops::Range<usize> {
4238    if len == 0 || row_height <= 0.0 || viewport_height <= 0.0 {
4239        return 0..0;
4240    }
4241    let top = viewport_y - padding_y;
4242    let bottom = viewport_y + viewport_height - padding_y;
4243    let first = (top / row_height).floor().max(0.0) as usize;
4244    let last = (bottom / row_height).ceil().max(0.0) as usize;
4245    let start = first.saturating_sub(overscan_rows).min(len);
4246    let end = last
4247        .saturating_add(overscan_rows)
4248        .saturating_add(1)
4249        .min(len);
4250    start..end.max(start)
4251}
4252
4253/// Recursively appends a snapshot node and expanded descendants in display order.
4254fn flatten_node<T: Clone + PartialEq>(
4255    node: &TreeNode<T>,
4256    depth: usize,
4257    parent: Option<T>,
4258    expanded: &[T],
4259    out: &mut Vec<FlatNode<T>>,
4260) {
4261    let branch = node.branch || !node.children.is_empty();
4262    let is_expanded = expanded.iter().any(|id| id == &node.id);
4263    out.push(FlatNode {
4264        id: node.id.clone(),
4265        label: node.label.clone(),
4266        depth,
4267        branch,
4268        disabled: node.disabled.read(),
4269        leading_icon: node.leading_icon.clone(),
4270        leading_icon_tint: node.leading_icon_tint,
4271        trailing_action: node.trailing_action.clone(),
4272        parent: parent.clone(),
4273    });
4274    if branch && is_expanded {
4275        for child in &node.children {
4276            flatten_node(child, depth + 1, Some(node.id.clone()), expanded, out);
4277        }
4278    }
4279}
4280
4281/// Finds the first depth-first matching snapshot ID as child indices.
4282fn find_path<T: PartialEq>(nodes: &[TreeNode<T>], id: &T) -> Option<Vec<usize>> {
4283    for (idx, node) in nodes.iter().enumerate() {
4284        if &node.id == id {
4285            return Some(vec![idx]);
4286        }
4287        if let Some(mut child) = find_path(&node.children, id) {
4288            child.insert(0, idx);
4289            return Some(child);
4290        }
4291    }
4292    None
4293}
4294
4295/// Reports whether `path` starts at `ancestor`, including equality.
4296fn path_is_descendant_or_self(path: &[usize], ancestor: &[usize]) -> bool {
4297    path.len() >= ancestor.len() && path.starts_with(ancestor)
4298}
4299
4300/// Resolves an immutable snapshot node from a nonempty index path.
4301fn node_at_path<'a, T>(nodes: &'a [TreeNode<T>], path: &[usize]) -> Option<&'a TreeNode<T>> {
4302    let (first, rest) = path.split_first()?;
4303    let node = nodes.get(*first)?;
4304    if rest.is_empty() {
4305        Some(node)
4306    } else {
4307        node_at_path(&node.children, rest)
4308    }
4309}
4310
4311/// Resolves a mutable snapshot node from a nonempty index path.
4312fn node_mut_at_path<'a, T>(
4313    nodes: &'a mut [TreeNode<T>],
4314    path: &[usize],
4315) -> Option<&'a mut TreeNode<T>> {
4316    let (first, rest) = path.split_first()?;
4317    let node = nodes.get_mut(*first)?;
4318    if rest.is_empty() {
4319        Some(node)
4320    } else {
4321        node_mut_at_path(&mut node.children, rest)
4322    }
4323}
4324
4325/// Removes and returns a snapshot node at a valid nonempty index path.
4326fn remove_node_at_path<T>(nodes: &mut Vec<TreeNode<T>>, path: &[usize]) -> Option<TreeNode<T>> {
4327    if path.len() == 1 {
4328        return (path[0] < nodes.len()).then(|| nodes.remove(path[0]));
4329    }
4330    let parent_path = &path[..path.len() - 1];
4331    let child_idx = *path.last()?;
4332    let parent = node_mut_at_path(nodes, parent_path)?;
4333    (child_idx < parent.children.len()).then(|| parent.children.remove(child_idx))
4334}
4335
4336/// Inserts before/after a target sibling or appends inside the target.
4337fn insert_node_relative<T: Clone + PartialEq>(
4338    nodes: &mut Vec<TreeNode<T>>,
4339    target: &T,
4340    position: TreeDropPosition,
4341    node: TreeNode<T>,
4342) -> bool {
4343    let Some(target_path) = find_path(nodes, target) else {
4344        return false;
4345    };
4346    match position {
4347        TreeDropPosition::Inside => {
4348            if let Some(target_node) = node_mut_at_path(nodes, &target_path) {
4349                target_node.children.push(node);
4350                true
4351            } else {
4352                false
4353            }
4354        }
4355        TreeDropPosition::Before | TreeDropPosition::After => {
4356            let target_idx = *target_path.last().unwrap_or(&0);
4357            let insert_idx = if position == TreeDropPosition::Before {
4358                target_idx
4359            } else {
4360                target_idx + 1
4361            };
4362            if target_path.len() == 1 {
4363                nodes.insert(insert_idx.min(nodes.len()), node);
4364                true
4365            } else {
4366                let parent_path = &target_path[..target_path.len() - 1];
4367                if let Some(parent) = node_mut_at_path(nodes, parent_path) {
4368                    parent
4369                        .children
4370                        .insert(insert_idx.min(parent.children.len()), node);
4371                    true
4372                } else {
4373                    false
4374                }
4375            }
4376        }
4377    }
4378}
4379
4380/// Moves one enabled snapshot subtree while rejecting missing/disabled/cyclic drops.
4381///
4382/// The original roots are restored when insertion unexpectedly fails.
4383fn move_node<T: Clone + PartialEq>(
4384    nodes: &mut Vec<TreeNode<T>>,
4385    source: &T,
4386    target: &T,
4387    position: TreeDropPosition,
4388) -> bool {
4389    let original = nodes.clone();
4390    let Some(source_path) = find_path(nodes, source) else {
4391        return false;
4392    };
4393    let Some(target_path) = find_path(nodes, target) else {
4394        return false;
4395    };
4396    if path_is_descendant_or_self(&target_path, &source_path) {
4397        return false;
4398    }
4399    let source_disabled = node_at_path(nodes, &source_path)
4400        .map(|node| node.disabled.read())
4401        .unwrap_or(true);
4402    let target_disabled = node_at_path(nodes, &target_path)
4403        .map(|node| node.disabled.read())
4404        .unwrap_or(true);
4405    if source_disabled || target_disabled {
4406        return false;
4407    }
4408    let Some(moved) = remove_node_at_path(nodes, &source_path) else {
4409        return false;
4410    };
4411    if insert_node_relative(nodes, target, position, moved) {
4412        true
4413    } else {
4414        *nodes = original;
4415        false
4416    }
4417}
4418
4419/// Replaces the first enabled matching snapshot label and returns its old value.
4420fn rename_node_label<T: PartialEq>(
4421    nodes: &mut [TreeNode<T>],
4422    id: &T,
4423    new_label: String,
4424) -> Option<String> {
4425    for node in nodes {
4426        if &node.id == id {
4427            if node.disabled.read() {
4428                return None;
4429            }
4430            let old = std::mem::replace(&mut node.label, new_label);
4431            return Some(old);
4432        }
4433        if let Some(old) = rename_node_label(&mut node.children, id, new_label.clone()) {
4434            return Some(old);
4435        }
4436    }
4437    None
4438}
4439
4440/// Inserts a factory node according to a validated create request relation.
4441fn insert_created_node<T: Clone + PartialEq>(
4442    nodes: &mut Vec<TreeNode<T>>,
4443    request: &TreeCreateRequest<T>,
4444    node: TreeNode<T>,
4445) -> bool {
4446    match request.kind {
4447        TreeCreateKind::SiblingAfter => {
4448            if let Some(after) = &request.after {
4449                insert_node_relative(nodes, after, TreeDropPosition::After, node)
4450            } else {
4451                nodes.push(node);
4452                true
4453            }
4454        }
4455        TreeCreateKind::Child => {
4456            let Some(parent) = &request.parent else {
4457                return false;
4458            };
4459            insert_node_relative(nodes, parent, TreeDropPosition::Inside, node)
4460        }
4461    }
4462}
4463
4464/// Returns the first visible row after the indexed subtree.
4465fn visible_subtree_end<T>(rows: &[FlatNode<T>], row: usize) -> usize {
4466    let depth = rows[row].depth;
4467    rows.iter()
4468        .enumerate()
4469        .skip(row + 1)
4470        .find_map(|(index, candidate)| (candidate.depth <= depth).then_some(index))
4471        .unwrap_or(rows.len())
4472}
4473
4474/// Removes the first enabled matching snapshot subtree and returns its parent ID.
4475fn delete_node_by_id<T: Clone + PartialEq>(
4476    nodes: &mut Vec<TreeNode<T>>,
4477    id: &T,
4478) -> Option<(TreeNode<T>, Option<T>)> {
4479    let path = find_path(nodes, id)?;
4480    let node = node_at_path(nodes, &path)?;
4481    if node.disabled.read() {
4482        return None;
4483    }
4484    let parent = if path.len() > 1 {
4485        node_at_path(nodes, &path[..path.len() - 1]).map(|node| node.id.clone())
4486    } else {
4487        None
4488    };
4489    remove_node_at_path(nodes, &path).map(|node| (node, parent))
4490}
4491
4492/// Collects a snapshot subtree's IDs in depth-first pre-order.
4493fn collect_node_ids<T: Clone>(node: &TreeNode<T>) -> Vec<T> {
4494    let mut out = vec![node.id.clone()];
4495    for child in &node.children {
4496        out.extend(collect_node_ids(child));
4497    }
4498    out
4499}
4500
4501/// Finds next enabled surviving row, falling back to the preceding range.
4502fn next_enabled_after_delete<T: PartialEq>(
4503    visible: &[FlatNode<T>],
4504    deleted_idx: usize,
4505    deleted_ids: &[T],
4506) -> Option<usize> {
4507    visible
4508        .iter()
4509        .enumerate()
4510        .skip(deleted_idx + 1)
4511        .find(|(_, node)| !node.disabled && !deleted_ids.iter().any(|id| id == &node.id))
4512        .map(|(idx, _)| idx)
4513        .or_else(|| {
4514            visible
4515                .iter()
4516                .enumerate()
4517                .take(deleted_idx)
4518                .rev()
4519                .find(|(_, node)| !node.disabled && !deleted_ids.iter().any(|id| id == &node.id))
4520                .map(|(idx, _)| idx)
4521        })
4522}
4523
4524/// Removes later duplicates while preserving first-occurrence order.
4525fn unique_vec<T: PartialEq>(values: Vec<T>) -> Vec<T> {
4526    let mut out = Vec::new();
4527    for value in values {
4528        if !out.iter().any(|existing| existing == &value) {
4529            out.push(value);
4530        }
4531    }
4532    out
4533}
4534
4535/// Finds the next enabled row with wraparound, or `None` when none exists.
4536fn next_enabled<T>(
4537    nodes: &[FlatNode<T>],
4538    active: Option<usize>,
4539    direction: isize,
4540) -> Option<usize> {
4541    if nodes.is_empty() {
4542        return None;
4543    }
4544    let start = active.unwrap_or(if direction >= 0 { 0 } else { nodes.len() - 1 });
4545    for step in 1..=nodes.len() {
4546        let idx = if direction >= 0 {
4547            (start + step) % nodes.len()
4548        } else {
4549            (start + nodes.len() - (step % nodes.len())) % nodes.len()
4550        };
4551        if !nodes[idx].disabled {
4552            return Some(idx);
4553        }
4554    }
4555    None
4556}
4557
4558/// Finds the first enabled visible direct child after a parent row.
4559fn first_visible_child_index<T>(nodes: &[FlatNode<T>], index: usize) -> Option<usize> {
4560    let parent_depth = nodes.get(index)?.depth;
4561    nodes
4562        .iter()
4563        .enumerate()
4564        .skip(index + 1)
4565        .find(|(_, node)| node.depth == parent_depth + 1 && !node.disabled)
4566        .map(|(idx, _)| idx)
4567}
4568
4569/// Returns squared logical-pixel Euclidean distance without a square root.
4570fn point_distance_sq(a: Point, b: Point) -> f32 {
4571    let dx = a.x - b.x;
4572    let dy = a.y - b.y;
4573    dx * dx + dy * dy
4574}
4575
4576/// ASCII-uppercases a character key for shortcut comparison.
4577fn key_character_upper(key: &KeyEvent) -> Option<String> {
4578    match &key.key {
4579        Key::Character(ch) => Some(ch.to_ascii_uppercase()),
4580        _ => None,
4581    }
4582}
4583
4584/// Measures unwrapped text when layout text services are available.
4585fn measure_text(ctx: &mut LayoutCtx<'_>, text: &str, style: TextStyle) -> Option<f32> {
4586    ctx.text_system.as_deref_mut().map(|text_system| {
4587        text_system
4588            .layout_cached(TextLayoutParams {
4589                text,
4590                style,
4591                max_width: None,
4592                wrap_mode: WrapMode::NoWrap,
4593            })
4594            .metrics
4595            .width
4596    })
4597}
4598
4599/// Obtains a cached unwrapped layout when paint text services are available.
4600fn layout_text(
4601    ctx: &mut PaintCtx<'_>,
4602    text: &str,
4603    style: TextStyle,
4604) -> Option<Arc<PreparedTextLayout>> {
4605    ctx.text_system.as_deref_mut().map(|text_system| {
4606        text_system.layout_cached(TextLayoutParams {
4607            text,
4608            style,
4609            max_width: None,
4610            wrap_mode: WrapMode::NoWrap,
4611        })
4612    })
4613}
4614
4615/// Paints one unwrapped label vertically centered at a fixed x origin.
4616fn paint_text_centered(
4617    ctx: &mut PaintCtx<'_>,
4618    text: &str,
4619    style: TextStyle,
4620    bounds: Rect,
4621    x: f32,
4622    opacity: f32,
4623) {
4624    let Some(layout) = layout_text(ctx, text, style) else {
4625        return;
4626    };
4627    let baseline = layout
4628        .lines
4629        .first()
4630        .map(|line| line.baseline_y)
4631        .unwrap_or(0.0);
4632    let y = bounds.y + (bounds.h - layout.metrics.height) * 0.5 + baseline;
4633    ctx.push(DrawCmd::Text(DrawText {
4634        pos: [x, y],
4635        color: style.color.with_alpha(style.color.a * opacity),
4636        decoration: ailloli_ui_core::TextDecoration::None,
4637        layout,
4638    }));
4639}