teksilo_widgets/tree_view.rs
1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! TreeView — a virtualized, expandable/collapsible hierarchical list widget.
5//!
6//! Displays a [`TreeModel<T>`](teksilo_data::TreeModel) as an indented tree.
7//! Internally each view owns a [`TreeSlice`] for independent
8//! expand state, so two `TreeView`s on the same model can be open at different
9//! depths simultaneously. Only rows in the visible viewport + a small buffer have
10//! live widgets — rows outside the buffer are dormant, matching `ListView`'s
11//! virtualization model. An external [`TreeDataSource`]
12//! is also accepted via [`TreeView::from_source`] when the data lives outside a
13//! `TreeModel`.
14//!
15//! Row heights come in three modes: uniform (`item_height`, default fast path),
16//! exact per-flat-index callback (`item_height_fn`), and auto-measured
17//! (`auto_item_height` — height-for-width per row, scroll-anchored).
18//!
19//! ## Keyboard
20//!
21//! Arrows move the cursor; `Home` / `End` reach the first and last **visible**
22//! row and `PageUp` / `PageDown` a viewport of them, each moving the selection
23//! unless the accelerator is held, which moves the cursor alone. `Shift`
24//! extends a range from the anchor and `Ctrl+Shift` extends it additively.
25//!
26//! `→` opens a closed node and, on one already open, moves into its first
27//! child; `←` closes an open node and, on a leaf or a closed one, ascends to
28//! the parent. Both mirror under RTL. `*` expands the whole subtree, `+` and
29//! `-` one level. `Space` selects or toggles, `Enter` activates, `Ctrl+A` and
30//! `Ctrl+Shift+A` select and deselect everything, and `Ctrl+Arrow` with
31//! `Ctrl+Space` build a disjoint selection. On macOS `⌘↓` opens a row, `⌘↑`
32//! ascends, and `⌥→`/`⌥←` expand or collapse a subtree.
33//!
34//! The full table, and why some of it is platform-specific, is in
35//! [docs/data-view-keyboard.md](https://github.com/ferntech-eu/teksilo/blob/main/docs/data-view-keyboard.md).
36//!
37//! ## Example
38//!
39//! ```rust
40//! # use teksilo_widgets::TreeView;
41//! # use teksilo_widgets::primitives::{HStack, Padding, TextWidget};
42//! # use teksilo_data::TreeModel;
43//! # use teksilo_i18n::lit;
44//! # struct Item { title: String }
45//! # let tree_model: TreeModel<Item> = TreeModel::new();
46//! let _w = TreeView::new(tree_model, |item, entry, _selected| {
47//! let indent = entry.depth as f32 * 20.0;
48//! Box::new(HStack::new()
49//! .child(Padding::new(0.0, 0.0, 0.0, indent))
50//! .child(TextWidget::new(lit!(&item.title))))
51//! })
52//! .item_height(28.0);
53//! ```
54
55use std::cell::{Cell, RefCell};
56use std::rc::Rc;
57use std::time::Duration;
58
59use teksilo_canvas::{Point, Rect, Size, SizeProposal};
60use teksilo_tokens::{BorderRole, Easing};
61
62use teksilo_core::DropFeedback;
63use teksilo_core::accessibility::AccessNodeBuilder;
64use teksilo_core::binding::BindingLevel;
65use teksilo_core::signal::{Prop, Signal};
66use teksilo_core::widget::{LayoutContext, Widget, WidgetPlacement};
67use teksilo_core::widget_builder::HandlerSet;
68use teksilo_core::widget_id::WidgetId;
69
70use teksilo_data::selection_model::SelectionModel;
71use teksilo_data::tree_slice::{TreeSlice, TreeSliceHandle};
72use teksilo_data::{
73 DropPosition, DropResponse, FlatEntry, ItemKey, KeyedSelectionModel, NodeId, TreeDataSource,
74 TreeModel,
75};
76
77use crate::common::row_metrics::{HeightSource, RowMetrics, SharedRowMetrics};
78use crate::common::scroll::OverscrollBehavior;
79use crate::data_views::{DragTransferMode, RowDragData, RowSelection, ViewId, ViewKind};
80use crate::scroll_area::ScrollBarMode;
81use crate::scroll_bar::{ScrollBar, ScrollBarOrientation, ScrollBarVisual};
82use crate::tree_source::{TreeRow, TreeRowMeta, TreeSource};
83
84const BUFFER_ITEMS: usize = 5;
85const DEFAULT_ITEM_HEIGHT: f32 = 28.0;
86const SCROLLBAR_THICKNESS: f32 = 12.0;
87
88/// Per-row context passed to a 4-arg TreeView delegate. Carries a
89/// reference to the slice handle and the row's `NodeId` so the
90/// delegate can wire chevron toggles and other tree-aware behavior
91/// without manually cloning state outside the closure.
92///
93/// Created internally by [`TreeView::new_with_context`]. Not
94/// constructed directly by user code.
95pub struct TreeRowContext<'a, T: 'static> {
96 slice: &'a TreeSliceHandle<T>,
97 node_id: teksilo_data::NodeId,
98}
99
100impl<'a, T: 'static> TreeRowContext<'a, T> {
101 /// Toggle callback for this row's chevron. Wires in one line:
102 /// `.on_toggle_rc(ctx.toggle_callback())`.
103 pub fn toggle_callback(&self) -> std::rc::Rc<dyn Fn(&mut teksilo_core::widget::EventContext)> {
104 let slice = self.slice.clone();
105 let node = self.node_id;
106 std::rc::Rc::new(move |_ctx| slice.toggle_expand(node))
107 }
108
109 /// Cloned handle to the slice — call `.toggle_expand(node)`,
110 /// `.expand(node)`, `.collapse(node)` directly.
111 pub fn slice_handle(&self) -> TreeSliceHandle<T> {
112 self.slice.clone()
113 }
114
115 /// The `NodeId` of this row in the backing `TreeModel`.
116 pub fn node_id(&self) -> teksilo_data::NodeId {
117 self.node_id
118 }
119}
120
121/// Delegate type for the built-in `TreeModel` path: takes the inputs the 3-arg
122/// form gets plus the optional `TreeRowContext`. Both the 3-arg `new` and the
123/// 4-arg `new_with_context` produce a closure of this shape.
124type TreeDelegate<T> = dyn Fn(&T, &FlatEntry, bool, &TreeRowContext<'_, T>) -> Box<dyn Widget>;
125
126/// Delegate type for the generic [`TreeView::from_source`] path: key-erased, so
127/// it receives a [`TreeRow`] (flat metadata + a chevron toggle) instead of the
128/// `NodeId`-typed `FlatEntry` / `TreeRowContext`.
129type SourceTreeDelegate<T> = dyn Fn(&T, &TreeRow, bool) -> Box<dyn Widget>;
130
131/// Internal, uniform per-row builder both constructors lower to:
132/// `(visible_index, &item, &meta, selected) -> row widget`. The built-in
133/// wrapper rebuilds the `NodeId` `TreeRowContext` from the index; the generic
134/// wrapper builds a key-erased `TreeRow`.
135type RowDelegate<T> = dyn Fn(usize, &T, &TreeRowMeta, bool) -> Box<dyn Widget>;
136
137/// A virtualized hierarchical tree widget backed by a `TreeModel<T>`.
138///
139/// ```rust
140/// # use teksilo_widgets::{TreeView};
141/// # use teksilo_widgets::primitives::{HStack, Padding, TextWidget};
142/// # use teksilo_data::TreeModel;
143/// # use teksilo_i18n::lit;
144/// # struct Item { title: String }
145/// # let tree_model: TreeModel<Item> = TreeModel::new();
146/// let _w = TreeView::new(tree_model, |item, entry, _selected| {
147/// let indent = entry.depth as f32 * 20.0;
148/// Box::new(HStack::new()
149/// .child(Padding::new(0.0, 0.0, 0.0, indent))
150/// .child(TextWidget::new(lit!(&item.title))))
151/// })
152/// .item_height(28.0);
153/// ```
154use crate::data_views::DropViz;
155
156pub struct TreeView<T: 'static> {
157 /// Index-keyed erased backing — the built-in `TreeSlice` or an external
158 /// `TreeDataSource`. All virtualization / DnD / keyboard work goes through
159 /// this in flat indices.
160 source: Rc<TreeSource<T>>,
161 /// Present only for the built-in `TreeModel` path; backs the `NodeId`-typed
162 /// public expand API + [`tree_slice`](Self::tree_slice). `None` for
163 /// [`from_source`](Self::from_source).
164 slice: Option<Rc<TreeSlice<T>>>,
165 /// Uniform per-row builder produced by whichever constructor was used.
166 row_delegate: Rc<RowDelegate<T>>,
167 item_height: f32,
168 /// Height-mode selection (uniform / exact callback / auto-measure).
169 height_source: HeightSource,
170 /// Row geometry — all virtualization consumers go through this.
171 metrics: SharedRowMetrics,
172 /// Row selection — index-based `SelectionModel` or keyed
173 /// `KeyedSelectionModel<NodeId>`, unified behind the index-facing facade.
174 row_selection: Option<RowSelection>,
175
176 /// Keyboard-focused flat index.
177 focused_index: Rc<Cell<Option<usize>>>,
178 /// The row identity `focused_index` currently points at, refreshed
179 /// alongside every write to `focused_index`. A tree's structural changes
180 /// (insert/remove/reorder, and — unlike a flat list — expand/collapse)
181 /// surface as a bare version bump with no `DataChange` delta to shift the
182 /// cursor by, so it is reconciled by identity instead: resolved against
183 /// the source on every version bump and used to rewrite `focused_index`
184 /// to wherever the row landed (or drop it if the row is gone). See
185 /// `crate::data_views::RowAnchor` and `reconcile_editing_row`, which
186 /// plays the same role for `TableView`'s `editing_cell`.
187 focused_anchor: Rc<RefCell<Option<crate::data_views::RowAnchor>>>,
188 /// The realized `(flat index -> row wrapper id)` map, filled by the body
189 /// pane each build. Lets this widget's `&self` methods resolve a row index
190 /// to a widget without reaching into the pane. Mirrors `ListView::row_map`.
191 row_map: Rc<RefCell<Vec<(usize, WidgetId)>>>,
192
193 /// Type-ahead ("type to jump") label extractor — opt-in via
194 /// [`type_ahead_label`](Self::type_ahead_label).
195 /// Per-row tooltip resolvers. The view attaches these itself, against the
196 /// row widget the delegate produced — an app cannot reach that widget to
197 /// hang a `.tooltip(...)` on it. Shared with `ListView`; see
198 /// [`RowTooltips`](crate::data_views::RowTooltips).
199 row_tooltips: crate::data_views::RowTooltips<T>,
200 type_ahead_label: Option<Rc<dyn Fn(&T) -> String>>,
201 /// Reset window for the type-ahead search term.
202 type_ahead_timeout: Duration,
203 /// Persistent type-ahead buffer (survives the per-keystroke rebuild).
204 type_ahead: Rc<crate::common::type_ahead::TypeAheadState>,
205
206 /// Enable intra-widget drag reordering.
207 reorderable: bool,
208
209 /// Cross-widget export / foreign-receive machinery — the builders
210 /// (`.exportable`, `.export_external`, `.accept_foreign_rows`,
211 /// `.on_rows_received`, `.on_rows_transferred_out`), the drag-start payload
212 /// build, and the move-out completion, shared by all five data views.
213 export: crate::data_views::RowExport<T>,
214
215 /// Whether a row-body PointerUp on a branch row auto-toggles its
216 /// expansion. Defaults to `true` (legacy behavior — convenient
217 /// for hand-built delegates without an explicit chevron). Set to
218 /// `false` when the delegate provides its own chevron tap target
219 /// (e.g. `StandardTreeItem`) to avoid the auto-toggle firing in
220 /// addition to the chevron's own click and cancelling out.
221 row_click_expands: bool,
222
223 /// Active drop feedback (set by on_drag_hover, cleared by on_drag_leave,
224 /// read by paint). Reactive Signal — bound at `RepaintOnly` so any
225 /// `set(...)` call dirties the TreeView for repaint automatically.
226 drop_feedback: Signal<Option<DropViz>>, // insertion line OR folder highlight
227
228 /// Optional row-activation callback (a click on the row body per
229 /// `activate_on`, or Enter/Space on the focused row) — distinct from
230 /// *selection*, which also moves on arrow navigation. Lets a view
231 /// open/commit a row without firing on every navigation step.
232 on_activate: Option<Rc<dyn Fn(usize, &mut teksilo_core::widget::EventContext)>>,
233 /// Whether activation is a single or double click (default `DoubleClick`).
234 activate_on: crate::data_views::ActivateOn,
235
236 /// `true` while this view (root or descendant) holds keyboard focus — the
237 /// root's inclusive [`BuildContext::view_focus_active`](teksilo_core::BuildContext::view_focus_active) signal, bound
238 /// `RepaintOnly`. With [`focus_visible`](Self::focus_visible) it drives the
239 /// **container focus ring**: when the view is Tab-focused but nothing is
240 /// selected, no row ring shows, so the whole view outlines itself instead —
241 /// the user can see where keyboard focus landed before they arrow.
242 view_focused: Signal<bool>,
243 /// Input-modality `:focus-visible`. Gates the container ring (and row rings)
244 /// to keyboard navigation, never a mouse click. Bound `RepaintOnly`.
245 focus_visible: Signal<bool>,
246
247 // Persistent scroll state
248 scroll_y: Signal<f32>,
249 max_scroll_y: Signal<f32>,
250 /// Scroll-chaining behavior at the boundary (default `Chain`).
251 overscroll_behavior: OverscrollBehavior,
252 viewport_ratio_y: Signal<f32>,
253
254 /// Animate wheel scrolling instead of snapping to the new offset.
255 /// Enabled by default — mirrors `ScrollArea`. Without it, each wheel
256 /// notch jumps by `item_height` per delivered line (typically 3),
257 /// which reads as a coarse multi-row jump rather than a smooth glide.
258 smooth_scrolling: bool,
259 /// Duration of the smooth scroll animation.
260 smooth_scroll_duration: Duration,
261
262 /// How the scroll bar is displayed. Defaults to `Permanent` — a
263 /// layout sibling that reserves its own width. `Overlay` / `Thin`
264 /// float over the content instead, like `ScrollArea`.
265 scroll_bar_style: ScrollBarMode,
266
267 /// Root-level **relayout** trigger. The root's `place_children` owns the
268 /// scrollbar totals (`max_scroll_y`, thumb ratio) and the content-width
269 /// decision, none of which its `build` output depends on — so a source
270 /// change, or a pane measurement that moves the content total, needs a
271 /// re-place here rather than a rebuild. Bumped by the source-version
272 /// observer and by [`body_pane::TreeViewBodyPane::total_refresh`].
273 layout_refresh: Signal<u64>,
274 /// Root-level **repaint** trigger for the container focus ring, which is
275 /// suppressed as soon as anything is selected. Selection changes rebuild
276 /// the pane (the delegate's `selected` argument) but must not rebuild the
277 /// root — they only change what the root paints.
278 paint_refresh: Signal<u64>,
279
280 /// Pane-local rebuild trigger, owned here so it survives pane rebuilds.
281 pane_version: Signal<u64>,
282 /// Buffered row range materialized by the pane's latest build.
283 pane_built_start: Rc<Cell<usize>>,
284 pane_built_end: Rc<Cell<usize>>,
285
286 // Set during build
287 body_pane_id: Option<WidgetId>,
288 scrollbar_id: Option<WidgetId>,
289 viewport_height: Rc<Cell<f32>>,
290 /// The TreeView's own absolute (window) bounds, cached from
291 /// `place_children` so the keyboard handler can chase the selected row
292 /// into enclosing scroll areas via
293 /// [`EventContext::ensure_visible`](teksilo_core::widget::EventContext::ensure_visible).
294 /// Rows are not distinct focusable nodes, so the focus-driven follow never
295 /// reveals the selected row in an outer scroller — this closes that gap.
296 viewport_bounds: Rc<Cell<Rect>>,
297 /// Content width (updated during `place_children`, used by drag
298 /// feedback so the insertion line / into-folder highlight spans the
299 /// row's actual width instead of a guess). Mirrors `ListView`.
300 placed_content_width: Rc<Cell<f32>>,
301 tree_id: ViewId,
302
303 /// Whole-view enabled state, statically or reactively. Forwarded to the
304 /// arena via `ctx.enabled_when(self_id, self.enabled.clone())` at build
305 /// time; a disabled view greys out and stops accepting focus /
306 /// selection / keyboard input (arena-gated).
307 enabled: Prop<bool>,
308}
309
310mod body_pane;
311mod builder;
312mod widget_impl;
313
314// std::fmt::Debug for the (non-Debug) generic fields.
315impl<T: 'static> std::fmt::Debug for TreeView<T> {
316 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317 f.debug_struct("TreeView")
318 .field("visible_count", &self.source.visible_count())
319 .field("item_height", &self.item_height)
320 .field("scroll_bar_style", &self.scroll_bar_style)
321 .field("scroll_y", &self.scroll_y.get())
322 .finish()
323 }
324}
325
326#[cfg(test)]
327mod tests;