teksilo_widgets/table_view.rs
1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! `TableView<T>` — generic, virtualized, accessible tabular widget.
5//!
6//! Built atop the [`ListModel<T>`](teksilo_data::ListModel) /
7//! [`ListDataSource`] data layer in
8//! `teksilo-data` and the `teksilo-tokens` `TableStyle`. Mirrors Qt's
9//! `QTableView`, SwiftUI's `Table`, and JavaFX's `TableView`.
10//! The core skeleton: single body pane, row-virtualized with alternating
11//! backgrounds, grid lines, `Role::Table > Role::Row > Role::Cell`
12//! accessibility, multi-row selection, and an empty-state slot. Headers,
13//! sort, filter, resize, reorder, pinning, cell selection, and editing are
14//! also included. Row heights come in three modes: uniform (`row_height`,
15//! the default fast path), exact per-row callback (`row_height_fn`), and
16//! auto-measured (`auto_row_height` — rows grow to their tallest cell,
17//! height-for-width). See docs/table-view.md "Row heights".
18//!
19//! ```ignore
20//! use teksilo_data::ListModel;
21//! use teksilo_widgets::table_view::{Column, ColumnWidth, TableView};
22//! use teksilo_i18n::lit;
23//!
24//! struct Person { name: String, age: u32 }
25//!
26//! let model: ListModel<Person> = ListModel::new();
27//! let _table = TableView::new(model)
28//! .add_column(Column::new("name", ColumnWidth::Flex(1.0))
29//! .label(lit!("Name"))
30//! .cell(|p: &Person, _cx| Box::new(
31//! teksilo_widgets::primitives::TextWidget::new(
32//! teksilo_i18n::lit!(p.name.clone())
33//! )
34//! )))
35//! .add_column(Column::new("age", ColumnWidth::Fixed(60.0))
36//! .label(lit!("Age"))
37//! .cell(|p: &Person, _cx| Box::new(
38//! teksilo_widgets::primitives::TextWidget::new(
39//! teksilo_i18n::lit!(p.age.to_string())
40//! )
41//! )))
42//! .alternating_rows(true)
43//! .row_height(32.0);
44//! ```
45
46pub mod a11y;
47pub mod body;
48pub mod body_pane;
49pub mod column;
50pub mod filter;
51pub mod header;
52pub mod imperative;
53pub mod keyboard;
54pub mod layout;
55pub mod row_navigator;
56pub mod selection;
57#[cfg(test)]
58mod tests;
59
60use std::cell::{Cell, RefCell};
61use std::collections::HashMap;
62use std::rc::Rc;
63use std::time::Duration;
64
65use teksilo_canvas::{Canvas, Point, Rect, Size, SizeProposal};
66
67use teksilo_core::ObserverHandle;
68use teksilo_core::accessibility::{AccessNodeBuilder, widget_id_to_node_id};
69use teksilo_core::binding::BindingLevel;
70use teksilo_core::build_context::BuildContext;
71use teksilo_core::signal::{Prop, Signal};
72use teksilo_core::widget::{LayoutContext, PaintContext, Widget, WidgetPlacement};
73use teksilo_core::widget_builder::HandlerSet;
74use teksilo_core::widget_id::WidgetId;
75use teksilo_data::{
76 DataChange, DropPosition, DropResponse, ItemKey, KeyedSelectionModel, ListDataSource,
77 ListModel, SelectionModel,
78};
79use teksilo_i18n::LocalizedString;
80use teksilo_tokens::{BorderRole, Easing, SurfaceRole};
81
82use crate::styles::recipe_table_style as cp;
83
84use crate::common::row_metrics::{HeightSource, RowMetrics, SharedRowMetrics};
85use crate::common::scroll::OverscrollBehavior;
86use crate::data_views::{
87 DragTransferMode, RowDragData, RowSelection, ViewId, ViewKind, flat_insertion_target,
88};
89use crate::list_source::DndLazy;
90use crate::scroll_area::ScrollBarMode;
91use crate::scroll_bar::{ScrollBar, ScrollBarOrientation, ScrollBarVisual};
92
93pub use self::column::{
94 Alignment, CellContext, Column, ColumnContext, ColumnResizePolicy, ColumnWidth, EditTriggers,
95 GridLines, PinnedSide, TabTraversal, TruncationPolicy,
96};
97pub use self::selection::{CellSelectionModel, TableSelectionMode};
98pub use teksilo_data::SortDirection;
99
100const BUFFER_ROWS: usize = 5;
101const SCROLLBAR_THICKNESS: f32 = 12.0;
102
103/// Pane partition produced by [`TableView::display_order`].
104///
105/// `leading_count` columns sit in the leading-pinned region, the next
106/// `middle_end - leading_count` columns sit in the middle (scrollable
107/// in future phases) region, and the remainder are trailing-pinned.
108/// All counts are positions inside the display-order vector.
109#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
110pub(crate) struct PaneBoundaries {
111 pub leading_count: usize,
112 pub middle_end: usize,
113}
114
115impl PaneBoundaries {
116 pub(crate) fn new(leading_count: usize, middle_end: usize) -> Self {
117 Self {
118 leading_count,
119 middle_end,
120 }
121 }
122}
123
124/// Drag payload for column reorder. Carried via `DragPayload::typed`.
125#[derive(Debug, Clone)]
126pub(crate) struct ColumnReorderDragData {
127 pub col_id: String,
128 /// Stable id of the source TableView, so dropping into a sibling
129 /// table is rejected by the on_drop matcher.
130 pub source_table_id: usize,
131}
132
133// ── Source erasure ─────────────────────────────────────────────────────────
134
135type LenFn = Rc<dyn Fn() -> usize>;
136type WithItemFn<T> = Rc<dyn Fn(usize, &dyn Fn(&T))>;
137type ObserveFn = Rc<dyn Fn(Box<dyn Fn(&DataChange)>) -> ObserverHandle>;
138/// Divergence side-channel for `DataChange::Reset`-emitting proxies
139/// (`ListDataSource::first_changed_index`). Raw `ListModel`s report
140/// `None` — their observers already get fine-grained variants.
141type FirstChangedFn = Rc<dyn Fn() -> Option<usize>>;
142
143/// The multi-cell read erasure. `TableView` reads each row's item once
144/// per cell (each column's `cell` delegate), so it keeps the side-effect
145/// `with_item_fn` form rather than `ListSource`'s single-widget reader.
146/// The DnD + lazy protocol is shared from `DndLazy` (built separately in
147/// the constructors). Returned alongside the `Rc<S>` source so the caller
148/// can build a `DndLazy` from the same handle without re-wrapping.
149fn erase_list_model<T: 'static>(
150 model: ListModel<T>,
151) -> (LenFn, WithItemFn<T>, ObserveFn, FirstChangedFn) {
152 let m_len = model.clone();
153 let m_read = model.clone();
154 let m_obs = model;
155 let len_fn: LenFn = Rc::new(move || m_len.len());
156 let with_item_fn: WithItemFn<T> = Rc::new(move |idx, f| {
157 m_read.with_item(idx, |item| f(item));
158 });
159 let observe_fn: ObserveFn =
160 Rc::new(move |callback| m_obs.observe_changes(move |change| callback(change)));
161 (len_fn, with_item_fn, observe_fn, Rc::new(|| None))
162}
163
164fn erase_data_source<S: ListDataSource<Item = T>, T: 'static>(
165 s: Rc<S>,
166) -> (LenFn, WithItemFn<T>, ObserveFn, FirstChangedFn) {
167 let s_len = s.clone();
168 let s_read = s.clone();
169 let s_obs = s.clone();
170 let s_changed = s;
171 let len_fn: LenFn = Rc::new(move || s_len.len());
172 let with_item_fn: WithItemFn<T> = Rc::new(move |idx, f| {
173 s_read.with_item(idx, |item| f(item));
174 });
175 let observe_fn: ObserveFn =
176 Rc::new(move |callback| s_obs.observe_changes(move |change| callback(change)));
177 let first_changed_fn: FirstChangedFn = Rc::new(move || s_changed.first_changed_index());
178 (len_fn, with_item_fn, observe_fn, first_changed_fn)
179}
180
181// `read_item` lived here for the inline body-row build; that loop now
182// lives in `BodyPane` which has its own copy. Keeping it removed
183// avoids dead-code drift between the two paths.
184
185// ── Public widget ──────────────────────────────────────────────────────────
186
187/// Generic, virtualized, accessible table with sortable / filterable / resizable columns.
188///
189/// Construct with [`TableView::new`] (from a [`ListModel<T>`](teksilo_data::ListModel))
190/// or [`TableView::from_source`] (any [`ListDataSource`]), then chain builder methods
191/// to configure columns, row heights, selection, and so on. See module docs for the full
192/// feature list and row-height modes.
193pub struct TableView<T: 'static> {
194 // Source erasure (multi-cell read path; DnD + lazy live in `dnd`).
195 len_fn: LenFn,
196 with_item_fn: WithItemFn<T>,
197 observe_fn: ObserveFn,
198 first_changed_fn: FirstChangedFn,
199 /// Source-owned DnD validation + lazy windowing, erased from the
200 /// backing `ListDataSource`. A `ListModel` reorders in place via its
201 /// `accept_drop`; an external source routes the move to its store and
202 /// can forbid a drop by returning `DropResponse::Reject` (the view
203 /// then paints no insertion line).
204 dnd: DndLazy,
205 /// Resolve a row index to a movement-proof handle (see `RowAnchor`).
206 anchor_fn: Rc<dyn Fn(usize) -> crate::data_views::RowAnchor>,
207 /// Anchor for the row with an open cell editor, so the editor follows its
208 /// row instead of its index. See `reconcile_editing_row`.
209 editing_anchor: Rc<RefCell<Option<crate::data_views::RowAnchor>>>,
210
211 // Configuration
212 columns: Vec<Column<T>>,
213 row_height: Option<f32>,
214 /// Height-mode selection (uniform / exact callback / auto-measure).
215 height_source: HeightSource,
216 /// Row geometry — shared with `BodyPane` and the keyboard handler.
217 row_metrics: SharedRowMetrics,
218 header_height: Option<f32>,
219 show_header: bool,
220 selection_mode: TableSelectionMode,
221 /// Row selection — index-based `SelectionModel` or keyed
222 /// `KeyedSelectionModel<K>`, unified behind the index-facing facade.
223 row_selection: Option<RowSelection>,
224 cell_selection: Option<CellSelectionModel>,
225 alternating_rows: bool,
226 grid_lines: GridLines,
227 a11y_label: Option<LocalizedString>,
228 show_internal_scrollbars: bool,
229 empty_view: Option<Rc<dyn Fn() -> Box<dyn Widget>>>,
230 column_resize_policy: ColumnResizePolicy,
231
232 /// Animate wheel scrolling instead of snapping to the new offset.
233 /// Enabled by default — mirrors `ScrollArea`. Without it, each wheel
234 /// notch jumps by `row_height` per delivered line (typically 3),
235 /// which reads as a coarse multi-row jump rather than a smooth glide.
236 smooth_scrolling: bool,
237 /// Duration of the smooth scroll animation.
238 smooth_scroll_duration: Duration,
239
240 /// How the scroll bar is displayed. Defaults to `Permanent` — a
241 /// layout sibling that reserves its own width. `Overlay` / `Thin`
242 /// float over the content instead, like `ScrollArea`.
243 scroll_bar_style: ScrollBarMode,
244
245 // Public reactive signals
246 scroll_y: Signal<f32>,
247 max_scroll_y: Signal<f32>,
248 /// Scroll-chaining behavior at the boundary (default `Chain`).
249 overscroll_behavior: OverscrollBehavior,
250 viewport_ratio_y: Signal<f32>,
251 /// Horizontal scroll offset of the Middle (unpinned) pane — see
252 /// `PaneBoundaries`. Leading/Trailing-pinned columns never move; the
253 /// Middle pane's content shifts by `-scroll_x`.
254 scroll_x: Signal<f32>,
255 /// Maximum `scroll_x` — `middle_content_width − middle_viewport_width`.
256 max_scroll_x: Signal<f32>,
257 /// Middle-pane viewport-to-content width ratio, for the horizontal
258 /// scroll bar's thumb.
259 viewport_ratio_x: Signal<f32>,
260 sort_signal: Signal<Option<(String, SortDirection)>>,
261 column_widths_signal: Signal<HashMap<String, f32>>,
262 /// Column ids in display order. Empty means "use declaration order".
263 column_order_signal: Signal<Vec<String>>,
264 /// Per-id override for `Column::pinned`. Missing keys mean "use the
265 /// declared pinning". The drag-to-reorder UI updates this when a
266 /// column crosses a pane boundary.
267 column_pinning_signal: Signal<HashMap<String, PinnedSide>>,
268 /// Currently keyboard-focused cell `(row_index, display_col)`, or
269 /// `None` when no cell is focused.
270 focused_cell: Signal<Option<(usize, usize)>>,
271 /// Type-ahead ("type to jump") label extractor — opt-in via
272 /// [`type_ahead_label`](Self::type_ahead_label).
273 #[allow(clippy::type_complexity)]
274 type_ahead_label: Option<Rc<dyn Fn(&T) -> String>>,
275 /// Reset window for the type-ahead search term.
276 type_ahead_timeout: Duration,
277 /// Persistent type-ahead buffer (survives the per-keystroke rebuild).
278 type_ahead: Rc<crate::common::type_ahead::TypeAheadState>,
279 tab_traversal: TabTraversal,
280 /// Cell currently in edit mode, or `None` when no editor is open.
281 /// Cell delegates inspect this through `CellContext::is_editing` to
282 /// swap in an editor widget.
283 editing_cell: Signal<Option<(usize, usize)>>,
284 edit_triggers: EditTriggers,
285 /// User callback invoked when an edit trigger fires on the focused
286 /// cell.
287 #[allow(clippy::type_complexity)]
288 on_cell_edit_request: Option<Rc<dyn Fn(usize, &str, &mut teksilo_core::widget::EventContext)>>,
289 #[allow(clippy::type_complexity)]
290 on_cell_edit_dismissed:
291 Option<Rc<dyn Fn(usize, &str, &mut teksilo_core::widget::EventContext)>>,
292 /// Per-column filter text. Updated by filter affordances in the
293 /// header, by `set_filter` / `clear_filters`, and by
294 /// downstream consumers binding it (e.g., `SortFilterListModel`).
295 filters_signal: Signal<HashMap<String, String>>,
296 /// User callback invoked on every row activation (Enter on the
297 /// focused row).
298 #[allow(clippy::type_complexity)]
299 on_row_activate: Option<Rc<dyn Fn(usize, &mut teksilo_core::widget::EventContext)>>,
300 reorderable: bool,
301 /// Active row-drop insertion indicator `(body_local_y, width)` —
302 /// `body_local_y` is measured from the body band top (below the
303 /// header). Set by `on_drag_hover` when the source accepts the
304 /// hovered position, cleared on leave / drop, read by `paint`.
305 /// Reactive (`RepaintOnly`) so a `set(...)` dirties the table.
306 drop_feedback: Signal<Option<(f32, f32)>>,
307
308 /// Whether activation is a single or double click (default `DoubleClick`).
309 activate_on: crate::data_views::ActivateOn,
310
311 /// `true` while this view — its root or any descendant (e.g. a cell
312 /// editor) — holds keyboard focus. Captured at build from
313 /// [`BuildContext::view_focus_active`] and bound `RepaintOnly`. Drives
314 /// **focus-aware selection**: the selection band paints with the active
315 /// `Selected` chrome while focused and the muted `SelectedInactive` chrome
316 /// once focus leaves the table — the standard desktop affordance.
317 view_focused: Signal<bool>,
318 /// Input-modality `:focus-visible` — `true` after keyboard input, `false`
319 /// after a pointer press. Gates the cell focus ring so it shows only
320 /// during keyboard navigation, never on a mouse click. Bound `RepaintOnly`.
321 focus_visible: Signal<bool>,
322
323 // Build state
324 header_row_id: Option<WidgetId>,
325 body_pane_id: Option<WidgetId>,
326 scrollbar_id: Option<WidgetId>,
327 /// Horizontal scroll bar along the bottom of the Middle pane only —
328 /// built whenever `show_internal_scrollbars` is set, placed/sized (and
329 /// hidden at zero size, mirroring the vertical bar) in `place_children`.
330 h_scrollbar_id: Option<WidgetId>,
331 empty_id: Option<WidgetId>,
332 /// Pane-local rebuild trigger + buffered range, owned here so they
333 /// survive `TableView` rebuilds (each rebuild constructs a fresh
334 /// `BodyPane` struct that inherits these handles).
335 pane_version: Signal<u64>,
336 pane_built_start: Rc<Cell<usize>>,
337 pane_built_end: Rc<Cell<usize>>,
338 /// Bumped by the pane when a measure pass changes the content
339 /// total; bound at `Relayout` on this root so `max_scroll_y` / the
340 /// thumb ratio are recomputed with the corrected total next frame.
341 pane_total_refresh: Signal<u64>,
342
343 // Layout state
344 /// Resolved widths in **display order** (parallel to
345 /// `display_indices`).
346 column_widths: Rc<RefCell<Vec<f32>>>,
347 /// Display-order indices into `self.columns`. Recomputed each
348 /// `build()`; read by `place_children` and `paint`.
349 display_indices: Rc<RefCell<Vec<usize>>>,
350 /// `(row, display_pos) -> WidgetId` for every cell realized by the
351 /// body pane's latest `build()`. Shared with `BodyPane` (the GridView
352 /// `tile_map` pattern — two holders across the sibling-of-scrollbar
353 /// split): the pane overwrites it wholesale each time it rebuilds, so
354 /// a cell that scrolled out of the realized buffer simply isn't in
355 /// the map. `accessibility()` reads it to point `active_descendant`
356 /// at the keyboard-focused cell's own AT node.
357 cell_map: Rc<RefCell<Vec<((usize, usize), WidgetId)>>>,
358 /// Counts of (leading-pinned, middle, trailing-pinned) columns —
359 /// used by paint to draw pane dividers and by the drop-zone math
360 /// to classify a drop position.
361 pane_boundaries: Rc<RefCell<PaneBoundaries>>,
362 viewport_height: Rc<Cell<f32>>,
363 /// Middle-pane viewport width, snapshotted by `place_children` — the
364 /// horizontal analogue of `viewport_height`. Read by the keyboard
365 /// handler's ensure-column-visible follow.
366 middle_viewport_width: Rc<Cell<f32>>,
367 /// Set on the first `place_children`. Until then `viewport_height` still
368 /// holds its construction placeholder, so viewport-relative imperatives
369 /// (`ensure_row_visible`) would scroll against a size that was never real.
370 laid_out: Rc<Cell<bool>>,
371 /// The row-area's absolute (window) rect (below the header), cached by
372 /// `place_children`. Threaded into the keyboard handler so it can chase the
373 /// focused row into any *enclosing* scroll area via
374 /// [`EventContext::ensure_visible`](teksilo_core::widget::EventContext::ensure_visible).
375 body_bounds: Rc<Cell<Rect>>,
376 /// Width of the header strip (= the column band) snapshotted by
377 /// `place_children`. The reorder-drop handler needs it to mirror the
378 /// drop x under RTL, where the column content is right-anchored in
379 /// the band (`local.x` is measured from the strip's physical left).
380 header_strip_width: Rc<Cell<f32>>,
381
382 // Header-cell shared state — tracked across the table so the
383 // pointer-capture'd resize delivers PointerMove events back to the
384 // active HeaderCell.
385 resize_state: header::ResizeStateHandle,
386 /// Display slot of the column under an active resize drag, or `None`.
387 /// Shared with every `HeaderCell` so the *target* column shows the
388 /// "resizing" chrome — which is not always the cell holding the pointer
389 /// capture, since a grip straddles the divider between two cells.
390 resize_target: Signal<Option<usize>>,
391 /// Window x of the prospective divider while a
392 /// [`ColumnResizePolicy::OnRelease`] drag is in flight. Painted as a
393 /// guide line by `paint`; `None` at rest. Under `Live` the columns
394 /// themselves move, so nothing is published here.
395 resize_preview_x: Signal<Option<f32>>,
396
397 /// Stable id used by the column-reorder drag payload to disambiguate
398 /// inter-table drops. Unrelated to row DnD — a wholly separate
399 /// mechanism (`ColumnReorderDragData` + header handlers).
400 table_id: usize,
401
402 /// Stable, kind-tagged ID for this TableView instance's **row** DnD
403 /// (identifies its own row reorder vs. a foreign row drop, even across
404 /// widget kinds / windows). Distinct from `table_id` above, which only
405 /// disambiguates the separate column-reorder mechanism.
406 model_id: ViewId,
407
408 /// Cross-widget export / foreign-receive machinery — the builders
409 /// (`.exportable`, `.export_external`, `.accept_foreign_rows`,
410 /// `.on_rows_received`, `.on_rows_transferred_out`), the drag-start payload
411 /// build, and the move-out completion, shared by all four data views.
412 export: crate::data_views::RowExport<T>,
413
414 /// Whole-view enabled state, statically or reactively. Forwarded to the
415 /// arena via `ctx.enabled_when(self_id, self.enabled.clone())` at build
416 /// time; a disabled view greys out and stops accepting focus /
417 /// selection / keyboard input (arena-gated).
418 enabled: Prop<bool>,
419}
420
421/// Build the anchor factory for a keyed source: capture the row's key now,
422/// resolve its current index later. Keyless sources fall back to a fixed anchor.
423fn anchor_factory<S: ListDataSource<Item = T> + 'static, T: 'static>(
424 s: Rc<S>,
425) -> Rc<dyn Fn(usize) -> crate::data_views::RowAnchor> {
426 Rc::new(move |index| match s.key_at(index) {
427 Some(key) => {
428 let src = s.clone();
429 crate::data_views::RowAnchor::new(Rc::new(move || {
430 if src.key_at(index).as_ref() == Some(&key) {
431 return Some(index);
432 }
433 src.index_of(&key)
434 }))
435 }
436 None => crate::data_views::RowAnchor::fixed(index),
437 })
438}
439
440impl<T: 'static> TableView<T> {
441 /// Wrap a `ListModel<T>`.
442 pub fn new(model: ListModel<T>) -> Self {
443 let dnd = DndLazy::from_source(Rc::new(model.clone()));
444 let (len_fn, with_item_fn, observe_fn, first_changed_fn) = erase_list_model(model);
445 // A bare `ListModel` exposes no row identity.
446 let anchor_fn = Rc::new(crate::data_views::RowAnchor::fixed) as Rc<dyn Fn(usize) -> _>;
447 Self::create(
448 len_fn,
449 with_item_fn,
450 observe_fn,
451 first_changed_fn,
452 dnd,
453 anchor_fn,
454 )
455 }
456
457 /// Wrap any `ListDataSource<Item = T>` (e.g. a
458 /// [`SortFilterListModel<T>`](teksilo_data::SortFilterListModel)).
459 ///
460 /// The source owns DnD validation (`can_accept` / `accept_drop`) and
461 /// lazy windowing (`row_state` / `request_window` / `fetch_more`); a
462 /// read-only source leaves the defaults inert.
463 pub fn from_source<S: ListDataSource<Item = T>>(source: S) -> Self {
464 let s = Rc::new(source);
465 let dnd = DndLazy::from_source(s.clone());
466 let anchor_fn = anchor_factory::<S, T>(s.clone());
467 let (len_fn, with_item_fn, observe_fn, first_changed_fn) = erase_data_source::<S, T>(s);
468 Self::create(
469 len_fn,
470 with_item_fn,
471 observe_fn,
472 first_changed_fn,
473 dnd,
474 anchor_fn,
475 )
476 }
477
478 /// Wrap any `ListDataSource<Item = T>` with **keyed** row selection. The
479 /// `KeyedSelectionModel<S::Key>` tracks selection by source identity, so it
480 /// survives reorders / filters / lazy window-slides and stays consistent
481 /// across two views of the same source. The view stays `TableView<T>` — the
482 /// index↔key mapping is captured from the concrete source here. Equivalent
483 /// to `from_source(..)` plus an identity-based replacement for
484 /// [`selection`](Self::selection).
485 pub fn from_source_keyed<S: ListDataSource<Item = T>>(
486 source: S,
487 keyed: KeyedSelectionModel<S::Key>,
488 ) -> Self
489 where
490 S::Key: ItemKey,
491 {
492 let s = Rc::new(source);
493 let dnd = DndLazy::from_source(s.clone());
494 let key_at = {
495 let s = s.clone();
496 Rc::new(move |i| s.key_at(i)) as Rc<dyn Fn(usize) -> Option<S::Key>>
497 };
498 let len = {
499 let s = s.clone();
500 Rc::new(move || s.len()) as Rc<dyn Fn() -> usize>
501 };
502 let contains = {
503 let s = s.clone();
504 Rc::new(move |k: &S::Key| (0..s.len()).any(|i| s.key_at(i).as_ref() == Some(k)))
505 as Rc<dyn Fn(&S::Key) -> bool>
506 };
507 let row_selection = RowSelection::from_keyed(keyed, key_at, len, contains);
508 let anchor_fn = anchor_factory::<S, T>(s.clone());
509 let (len_fn, with_item_fn, observe_fn, first_changed_fn) = erase_data_source::<S, T>(s);
510 let mut view = Self::create(
511 len_fn,
512 with_item_fn,
513 observe_fn,
514 first_changed_fn,
515 dnd,
516 anchor_fn,
517 );
518 view.row_selection = Some(row_selection);
519 view
520 }
521
522 fn create(
523 len_fn: LenFn,
524 with_item_fn: WithItemFn<T>,
525 observe_fn: ObserveFn,
526 first_changed_fn: FirstChangedFn,
527 dnd: DndLazy,
528 anchor_fn: Rc<dyn Fn(usize) -> crate::data_views::RowAnchor>,
529 ) -> Self {
530 use std::sync::atomic::{AtomicUsize, Ordering};
531 static NEXT_ID: AtomicUsize = AtomicUsize::new(1);
532 let table_id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
533 Self {
534 len_fn,
535 with_item_fn,
536 observe_fn,
537 first_changed_fn,
538 dnd,
539 anchor_fn,
540 editing_anchor: Rc::new(RefCell::new(None)),
541 columns: Vec::new(),
542 row_height: None,
543 height_source: HeightSource::Uniform,
544 row_metrics: Rc::new(RefCell::new(RowMetrics::uniform(cp::ROW_HEIGHT, 0.0))),
545 header_height: None,
546 show_header: true,
547 selection_mode: TableSelectionMode::default(),
548 row_selection: None,
549 cell_selection: None,
550 alternating_rows: false,
551 grid_lines: GridLines::None,
552 a11y_label: None,
553 show_internal_scrollbars: true,
554 empty_view: None,
555 column_resize_policy: ColumnResizePolicy::default(),
556 smooth_scrolling: true,
557 smooth_scroll_duration: Duration::from_millis(150),
558 scroll_bar_style: ScrollBarMode::Permanent,
559 overscroll_behavior: OverscrollBehavior::default(),
560 scroll_y: Signal::new_animated(0.0),
561 max_scroll_y: Signal::new(0.0),
562 viewport_ratio_y: Signal::new(1.0),
563 scroll_x: Signal::new_animated(0.0),
564 max_scroll_x: Signal::new(0.0),
565 viewport_ratio_x: Signal::new(1.0),
566 sort_signal: Signal::new(None),
567 column_widths_signal: Signal::new(HashMap::new()),
568 column_order_signal: Signal::new(Vec::new()),
569 column_pinning_signal: Signal::new(HashMap::new()),
570 focused_cell: Signal::new(None),
571 type_ahead_label: None,
572 type_ahead_timeout: crate::common::type_ahead::DEFAULT_TYPE_AHEAD_TIMEOUT,
573 type_ahead: crate::common::type_ahead::TypeAheadState::new(),
574 // Replaced at build with the live tree signals; the defaults are
575 // only the pre-build values (treat as focused, pointer modality).
576 view_focused: Signal::new(true),
577 focus_visible: Signal::new(false),
578 tab_traversal: TabTraversal::default(),
579 editing_cell: Signal::new(None),
580 edit_triggers: EditTriggers::default(),
581 on_cell_edit_request: None,
582 on_cell_edit_dismissed: None,
583 filters_signal: Signal::new(HashMap::new()),
584 on_row_activate: None,
585 reorderable: false,
586 drop_feedback: Signal::new(None),
587 activate_on: crate::data_views::ActivateOn::default(),
588 header_row_id: None,
589 body_pane_id: None,
590 scrollbar_id: None,
591 h_scrollbar_id: None,
592 empty_id: None,
593 pane_version: Signal::new(0_u64),
594 pane_built_start: Rc::new(Cell::new(0)),
595 pane_built_end: Rc::new(Cell::new(0)),
596 pane_total_refresh: Signal::new(0_u64),
597 column_widths: Rc::new(RefCell::new(Vec::new())),
598 display_indices: Rc::new(RefCell::new(Vec::new())),
599 cell_map: Rc::new(RefCell::new(Vec::new())),
600 pane_boundaries: Rc::new(RefCell::new(PaneBoundaries::default())),
601 viewport_height: Rc::new(Cell::new(600.0)),
602 middle_viewport_width: Rc::new(Cell::new(600.0)),
603 laid_out: Rc::new(Cell::new(false)),
604 body_bounds: Rc::new(Cell::new(Rect::ZERO)),
605 header_strip_width: Rc::new(Cell::new(0.0)),
606 resize_state: Rc::new(std::cell::RefCell::new(None)),
607 resize_target: Signal::new(None),
608 resize_preview_x: Signal::new(None),
609 table_id,
610 model_id: ViewId::next(ViewKind::Table),
611 export: crate::data_views::RowExport::default(),
612 enabled: Prop::Static(true),
613 }
614 }
615
616 // ── Builder ────────────────────────────────────────────────────────
617
618 /// Enable or disable the whole view. A disabled view greys out and stops
619 /// accepting focus / selection / keyboard input (arena-gated).
620 pub fn enabled(mut self, enabled: impl Into<Prop<bool>>) -> Self {
621 self.enabled = enabled.into();
622 self
623 }
624
625 /// Set the scroll-chaining behavior at the boundary (default
626 /// [`OverscrollBehavior::Chain`]; [`Contain`](OverscrollBehavior::Contain)
627 /// disables chaining to an ancestor scrollable).
628 pub fn overscroll_behavior(mut self, behavior: OverscrollBehavior) -> Self {
629 self.overscroll_behavior = behavior;
630 self
631 }
632
633 /// Enable or disable animated wheel scrolling (enabled by default).
634 /// When disabled, wheel events snap immediately to the new offset.
635 pub fn smooth_scrolling(mut self, enabled: bool) -> Self {
636 self.smooth_scrolling = enabled;
637 self
638 }
639
640 /// Enable **type-ahead** ("type to jump"): typing a printable character
641 /// while the table has keyboard focus jumps the focused row to the next
642 /// row whose label starts with the accumulated search term, wrapping
643 /// around (Qt `keyboardSearch` / macOS & Windows type-select).
644 /// `label(&item)` yields the searchable text for a row; matching is
645 /// ASCII-case-insensitive. A pause longer than the
646 /// [`type_ahead_timeout`](Self::type_ahead_timeout) starts a fresh term.
647 ///
648 /// On an editable column whose [`EditTriggers`] is type-to-edit, typing
649 /// starts an edit instead — type-ahead applies on non-editable columns
650 /// (or when no type-to-edit trigger is configured).
651 pub fn type_ahead_label(mut self, label: impl Fn(&T) -> String + 'static) -> Self {
652 self.type_ahead_label = Some(Rc::new(label));
653 self
654 }
655
656 /// Reset window between keystrokes before the type-ahead search term
657 /// clears (default 500 ms). A zero duration disables type-ahead.
658 pub fn type_ahead_timeout(mut self, timeout: Duration) -> Self {
659 self.type_ahead_timeout = timeout;
660 self
661 }
662
663 /// Duration of the smooth scroll animation (default 150 ms).
664 pub fn smooth_scroll_duration(mut self, duration: Duration) -> Self {
665 self.smooth_scroll_duration = duration;
666 self
667 }
668
669 /// How the scroll bar is displayed (default `Permanent`). `Overlay`
670 /// and `Thin` float the bar over the content instead of reserving a
671 /// layout column for it, mirroring `ScrollArea::scroll_bar_style`.
672 pub fn scroll_bar_style(mut self, style: ScrollBarMode) -> Self {
673 self.scroll_bar_style = style;
674 self
675 }
676
677 /// Append a single [`Column<T>`] definition to the table.
678 pub fn add_column(mut self, col: Column<T>) -> Self {
679 self.columns.push(col);
680 self
681 }
682
683 /// Append multiple [`Column<T>`] definitions from an iterator.
684 pub fn columns(mut self, cols: impl IntoIterator<Item = Column<T>>) -> Self {
685 self.columns.extend(cols);
686 self
687 }
688
689 /// Re-materialize `self.row_metrics` after a height-mode /
690 /// row-height builder call.
691 fn remake_metrics(&self) {
692 *self.row_metrics.borrow_mut() = self
693 .height_source
694 .make_metrics(self.effective_row_height(), 0.0);
695 }
696
697 /// Fixed row height (default: the table style's 28 px) — the
698 /// uniform fast path. Mutually exclusive with
699 /// [`row_height_fn`](Self::row_height_fn) and
700 /// [`auto_row_height`](Self::auto_row_height); the last mode setter
701 /// wins.
702 pub fn row_height(mut self, height: f32) -> Self {
703 self.row_height = Some(height);
704 self.height_source = HeightSource::Uniform;
705 self.remake_metrics();
706 self
707 }
708
709 /// Per-row heights from a callback over the visible row index. The
710 /// callback must be pure (same index + same data → same height); it
711 /// is re-swept from the first changed index on every model change
712 /// (a `SortFilterListModel` source reports that index through
713 /// `first_changed_index`, so sort/filter/append keep the valid
714 /// prefix). No measurement pass runs.
715 pub fn row_height_fn(mut self, f: impl Fn(usize) -> f32 + 'static) -> Self {
716 self.height_source = HeightSource::Exact(Rc::new(f));
717 self.remake_metrics();
718 self
719 }
720
721 /// Auto-measured row heights: each realized row reports the height
722 /// of its tallest cell measured at the cell's column width
723 /// (height-for-width), unrealized rows assume `estimated`. Scroll
724 /// anchoring keeps content above the viewport stationary as
725 /// estimates are corrected; the scrollbar settles one frame after a
726 /// measurement change.
727 pub fn auto_row_height(mut self, estimated: f32) -> Self {
728 self.height_source = HeightSource::Auto { estimated };
729 self.remake_metrics();
730 self
731 }
732
733 /// Override the column header row height in logical pixels. Default: the table style's `HEADER_HEIGHT`.
734 pub fn header_height(mut self, height: f32) -> Self {
735 self.header_height = Some(height);
736 self
737 }
738
739 /// Show or hide the column header row. Default: visible.
740 pub fn show_header(mut self, visible: bool) -> Self {
741 self.show_header = visible;
742 self
743 }
744
745 /// Set how column widths are redistributed when columns are
746 /// added, resized, or the table's own width changes. See
747 /// [`ColumnResizePolicy`].
748 pub fn column_resize_policy(mut self, policy: ColumnResizePolicy) -> Self {
749 self.column_resize_policy = policy;
750 self
751 }
752
753 /// Control how Tab / Shift+Tab navigate between cells. See
754 /// [`TabTraversal`].
755 pub fn tab_traversal(mut self, mode: TabTraversal) -> Self {
756 self.tab_traversal = mode;
757 self
758 }
759
760 /// Set which user action opens a cell editor. See [`EditTriggers`].
761 pub fn edit_triggers(mut self, trigger: EditTriggers) -> Self {
762 self.edit_triggers = trigger;
763 self
764 }
765
766 /// Hook fired by the keyboard handler when an edit trigger fires
767 /// on the focused cell. Receives `(row_index, col_id, ctx)`.
768 pub fn on_cell_edit_request(
769 mut self,
770 f: impl Fn(usize, &str, &mut teksilo_core::widget::EventContext) + 'static,
771 ) -> Self {
772 self.on_cell_edit_request = Some(Rc::new(f));
773 self
774 }
775
776 /// Callback invoked when an **open** cell editor should end because the
777 /// pointer went somewhere else: a press that lands on any cell other than
778 /// the one being edited. Receives the editing cell's flat row index and
779 /// column id, so the owner can commit (or discard) whatever is in its
780 /// buffer, then clear its own editing state.
781 ///
782 /// The counterpart of [`on_cell_edit_request`](Self::on_cell_edit_request),
783 /// and the view cannot do it alone: the framework owns *which* cell is being
784 /// edited, but only the owner knows what an ended edit means — commit,
785 /// discard, or refuse a value that will not parse.
786 ///
787 /// **Why a press and not a focus change.** "The editor lost focus" is the
788 /// obvious signal and it cannot be used: a body pane rebuilds constantly —
789 /// selection, filtering, scroll, a reload from elsewhere — and every rebuild
790 /// destroys and re-creates the open editor, so focus leaves it many times
791 /// during an edit the writer never interrupted. A press on another cell is
792 /// unambiguous and happens exactly once.
793 pub fn on_cell_edit_dismissed(
794 mut self,
795 f: impl Fn(usize, &str, &mut teksilo_core::widget::EventContext) + 'static,
796 ) -> Self {
797 self.on_cell_edit_dismissed = Some(Rc::new(f));
798 self
799 }
800
801 /// Hook fired when the user presses Enter on the focused row.
802 pub fn on_row_activate(
803 mut self,
804 f: impl Fn(usize, &mut teksilo_core::widget::EventContext) + 'static,
805 ) -> Self {
806 self.on_row_activate = Some(Rc::new(f));
807 self
808 }
809
810 /// Enable drag-to-reorder of **rows** (pointer drag + keyboard
811 /// Alt+ArrowUp/Down). Distinct from
812 /// [`Column::reorderable`](crate::Column::reorderable), which reorders
813 /// *columns* and defaults to `true`; this defaults to `false`.
814 ///
815 /// The move is routed through the backing source's `accept_drop`: a
816 /// `ListModel` reorders in place, an external source routes the move to
817 /// its store. Per-hover the source's `can_accept` decides whether the
818 /// drop is allowed — a forbidden position shows no insertion line and
819 /// the drop is refused. A row may also be forbidden from dragging at
820 /// all (the source's `drag` gate). Cross-table / external drops arrive
821 /// at `accept_drop` as `DragSource::Foreign`; a bare `ListModel`
822 /// rejects them, an external source decides.
823 pub fn reorderable(mut self, enabled: bool) -> Self {
824 self.reorderable = enabled;
825 self
826 }
827
828 /// Renamed to [`reorderable`](Self::reorderable), matching `ListView`,
829 /// `GridView`, `TreeView` and `TreeTableView` — this was the only view in
830 /// the family spelling it differently.
831 #[deprecated(since = "0.6.3", note = "renamed to `reorderable`")]
832 pub fn reorderable_rows(self, enabled: bool) -> Self {
833 self.reorderable(enabled)
834 }
835
836 /// Make rows **droppable outside this view** — on a
837 /// [`DropTarget`](crate::DropTarget), another data view, or the OS.
838 ///
839 /// A dragged row (or the whole selection, when the pressed row is part of a
840 /// multi-selection) carries clones of its items in a public
841 /// [`RowDragData<T>`](crate::RowDragData), so a foreign receiver can pull
842 /// them out with `payload.get_typed::<RowDragData<T>>()` /
843 /// `DropTarget::on_drop_typed::<RowDragData<T>>()` — no serialization. This
844 /// also makes rows a drag source even without [`reorderable`](Self::reorderable).
845 ///
846 /// `mode` chooses what happens to the origin rows once a *foreign* target
847 /// accepts them: [`DragTransferMode::Move`] removes them (via the source's
848 /// `on_drag_out`, or [`on_rows_transferred_out`](Self::on_rows_transferred_out)),
849 /// [`DragTransferMode::Copy`] leaves them. A same-view reorder is never a
850 /// transfer, so `mode` never affects it. Requires `T: Clone`.
851 pub fn exportable(mut self, mode: DragTransferMode) -> Self
852 where
853 T: Clone,
854 {
855 self.export.set_exportable(mode);
856 self
857 }
858
859 /// Additionally advertise the dragged rows as MIME data so they can be
860 /// dropped on a [`DropZone`](crate::DropZone) or exported to another
861 /// application / window via the OS. `f` maps the dragged items to
862 /// `(mime_type, bytes)` pairs (e.g. `text/plain`, `text/uri-list`, an
863 /// app-specific `application/x-…`). Implies [`exportable`](Self::exportable)
864 /// (defaulting to [`DragTransferMode::Move`] if not already set). Requires
865 /// `T: Clone`.
866 pub fn export_external(mut self, f: impl Fn(&[T]) -> Vec<(String, Vec<u8>)> + 'static) -> Self
867 where
868 T: Clone,
869 {
870 self.export.set_export_external(f);
871 self
872 }
873
874 /// Override how rows moved out to a foreign target are removed from this
875 /// view. Receives the dragged rows' indices (descending-safe) and the live
876 /// context. Without this, an [`exportable`](Self::exportable)
877 /// [`Move`](DragTransferMode::Move) drag removes them through the source's
878 /// `on_drag_out` (works out of the box for a `ListModel`).
879 pub fn on_rows_transferred_out(
880 mut self,
881 f: impl Fn(&[usize], &mut teksilo_core::widget::EventContext) + 'static,
882 ) -> Self {
883 self.export.set_on_rows_transferred_out(f);
884 self
885 }
886
887 /// Accept exported rows dropped from a **different** view or source without
888 /// writing a custom `ListDataSource`. Pair with
889 /// [`on_rows_received`](Self::on_rows_received), which is handed the dropped
890 /// items and the insertion index. (Same-view reorder is
891 /// [`reorderable`](Self::reorderable); a custom `ListDataSource` can still
892 /// accept foreign drops through its `can_accept`/`accept_drop` instead.)
893 pub fn accept_foreign_rows(mut self, accept: bool) -> Self {
894 self.export.accept_foreign_rows = accept;
895 self
896 }
897
898 /// Handler for rows accepted via [`accept_foreign_rows`](Self::accept_foreign_rows):
899 /// `(items, insertion_index, ctx)`. Insert them into your model at the
900 /// index.
901 pub fn on_rows_received(
902 mut self,
903 f: impl Fn(Vec<T>, usize, &mut teksilo_core::widget::EventContext) + 'static,
904 ) -> Self {
905 self.export.set_on_rows_received(f);
906 self
907 }
908
909 /// Choose single- vs double-click activation for `on_row_activate` (default
910 /// [`ActivateOn::DoubleClick`](crate::ActivateOn)). Enter/Space activates in
911 /// either mode.
912 pub fn activate_on(mut self, mode: crate::data_views::ActivateOn) -> Self {
913 self.activate_on = mode;
914 self
915 }
916
917 /// Choose the row-selection granularity (None / Single / Multi).
918 /// See [`TableSelectionMode`].
919 pub fn selection_mode(mut self, mode: TableSelectionMode) -> Self {
920 self.selection_mode = mode;
921 self
922 }
923
924 /// Set the index-based row selection model (positions). For identity-based
925 /// selection that survives reorder / filter / window-slide, build the view
926 /// with [`from_source_keyed`](Self::from_source_keyed) instead.
927 pub fn selection(mut self, sel: SelectionModel) -> Self {
928 self.row_selection = Some(RowSelection::from_index(sel));
929 self
930 }
931
932 /// Install an independent cell-selection model on top of row selection.
933 /// See [`CellSelectionModel`].
934 pub fn cell_selection(mut self, sel: CellSelectionModel) -> Self {
935 self.cell_selection = Some(sel);
936 self
937 }
938
939 /// Paint every other row with a tinted background. Default: off.
940 pub fn alternating_rows(mut self, enabled: bool) -> Self {
941 self.alternating_rows = enabled;
942 self
943 }
944
945 /// Draw horizontal and/or vertical grid lines between cells.
946 /// See [`GridLines`].
947 pub fn grid_lines(mut self, kind: GridLines) -> Self {
948 self.grid_lines = kind;
949 self
950 }
951
952 /// Provide an accessible label for the table (`aria-label`). Required
953 /// when the page hosts more than one table so screen readers can
954 /// distinguish them.
955 pub fn a11y_label(mut self, label: impl Into<LocalizedString>) -> Self {
956 self.a11y_label = Some(label.into());
957 self
958 }
959
960 /// Show or hide the built-in vertical scroll bar. Default: visible. Set to
961 /// `false` when an external scroll bar is wired to [`scroll_y_signal`](Self::scroll_y_signal).
962 pub fn show_internal_scrollbars(mut self, show: bool) -> Self {
963 self.show_internal_scrollbars = show;
964 self
965 }
966
967 /// Widget shown when the source is empty.
968 pub fn empty_view(mut self, f: impl Fn() -> Box<dyn Widget> + 'static) -> Self {
969 self.empty_view = Some(Rc::new(f));
970 self
971 }
972
973 // ── Public reactive signals ────────────────────────────────────────
974
975 /// Current vertical scroll offset in logical pixels.
976 pub fn scroll_y_signal(&self) -> &Signal<f32> {
977 &self.scroll_y
978 }
979
980 /// Maximum vertical scroll offset — `total_content_height − viewport_height`.
981 pub fn max_scroll_y_signal(&self) -> &Signal<f32> {
982 &self.max_scroll_y
983 }
984
985 /// Viewport-to-content height ratio, used by external scroll bar thumbs.
986 pub fn viewport_ratio_y_signal(&self) -> &Signal<f32> {
987 &self.viewport_ratio_y
988 }
989
990 /// Current horizontal scroll offset of the Middle (unpinned) pane, in
991 /// logical pixels. Leading/Trailing-pinned columns are unaffected —
992 /// see [`Column::pinned`].
993 pub fn scroll_x_signal(&self) -> &Signal<f32> {
994 &self.scroll_x
995 }
996
997 /// Maximum horizontal scroll offset — `middle_content_width −
998 /// middle_viewport_width`.
999 pub fn max_scroll_x_signal(&self) -> &Signal<f32> {
1000 &self.max_scroll_x
1001 }
1002
1003 /// Middle-pane viewport-to-content width ratio, used by external
1004 /// horizontal scroll bar thumbs.
1005 pub fn viewport_ratio_x_signal(&self) -> &Signal<f32> {
1006 &self.viewport_ratio_x
1007 }
1008
1009 /// Active sort: `Some((col_id, dir))` or `None` when unsorted.
1010 /// Mutated by header clicks (cycle: None → Asc → Desc → None) and by
1011 /// [`set_sort`](Self::set_sort) / [`clear_sort`](Self::clear_sort).
1012 /// Bind a [`SortFilterListModel`](teksilo_data::SortFilterListModel) to
1013 /// drive a re-sort of the underlying data:
1014 ///
1015 /// ```ignore
1016 /// let proxy = SortFilterListModel::new(model)
1017 /// .with_comparator("name", |a, b| a.name.cmp(&b.name));
1018 /// proxy.sort_signal(table.sort_signal().clone());
1019 /// ```
1020 pub fn sort_signal(&self) -> &Signal<Option<(String, SortDirection)>> {
1021 &self.sort_signal
1022 }
1023
1024 /// Map of column id → user-overridden width. A column id appears in
1025 /// this map only after the user resizes that column; missing keys
1026 /// mean "use the declared width policy".
1027 pub fn column_widths_signal(&self) -> &Signal<HashMap<String, f32>> {
1028 &self.column_widths_signal
1029 }
1030
1031 /// Column ids in display order. Updated when the user drags a
1032 /// header to reorder, or imperatively via
1033 /// [`set_column_order`](Self::set_column_order). When empty, the
1034 /// declared order applies. Pinned-side groups (Leading / None /
1035 /// Trailing) are *always* honored — the entries inside this signal
1036 /// only re-sort within each group.
1037 pub fn column_order_signal(&self) -> &Signal<Vec<String>> {
1038 &self.column_order_signal
1039 }
1040
1041 /// Per-id pinning override map. A key here pins the column to that
1042 /// side; missing keys fall back to the declared `Column::pinned`.
1043 /// Updated when the user drags a column across a pane boundary.
1044 pub fn column_pinning_signal(&self) -> &Signal<HashMap<String, PinnedSide>> {
1045 &self.column_pinning_signal
1046 }
1047
1048 /// Currently keyboard-focused cell, as `(row_index, display_col)`,
1049 /// or `None` when no cell is focused. Mutated by the keyboard
1050 /// handler (Arrow keys / Tab / Home / End / PgUp / PgDn /
1051 /// Ctrl-Home / Ctrl-End / Escape) and by direct
1052 /// [`set_focused_cell`](Self::set_focused_cell) /
1053 /// [`clear_focused_cell`](Self::clear_focused_cell) calls.
1054 pub fn focused_cell_signal(&self) -> &Signal<Option<(usize, usize)>> {
1055 &self.focused_cell
1056 }
1057
1058 /// Move the focused cell. Out-of-range values are silently clamped
1059 /// when the next layout runs.
1060 pub fn set_focused_cell(&self, row: usize, col: usize) {
1061 self.focused_cell.set(Some((row, col)));
1062 }
1063
1064 /// Remove keyboard focus from any cell (equivalent to pressing Escape).
1065 pub fn clear_focused_cell(&self) {
1066 self.focused_cell.set(None);
1067 }
1068
1069 /// Cell currently in edit mode, or `None` when no editor is open.
1070 /// Cell delegates inspect this via `CellContext::is_editing` and
1071 /// swap in an editor widget when matched.
1072 pub fn editing_cell_signal(&self) -> &Signal<Option<(usize, usize)>> {
1073 &self.editing_cell
1074 }
1075
1076 /// Begin editing the cell `(row, col_id)`. Silently no-ops if `col_id`
1077 /// isn't a currently-displayed column, or if `row` is outside the visible
1078 /// range — an out-of-range target would otherwise strand `editing_cell` on
1079 /// a row nothing can match.
1080 ///
1081 /// Callable **before the view is mounted**, which is the only point at
1082 /// which a consumer can seed a freshly constructed view with an edit
1083 /// target it already holds. `display_indices` is a cache `build()` fills,
1084 /// so a pre-mount call finds it empty; the order is recomputed on demand
1085 /// in that case rather than resolving against nothing and no-opping for a
1086 /// third, undocumented reason.
1087 pub fn begin_edit(&self, row: usize, col_id: &str) {
1088 let cached = self.display_indices.borrow();
1089 let recomputed;
1090 let display: &[usize] = if cached.is_empty() {
1091 recomputed = self.display_order();
1092 &recomputed
1093 } else {
1094 &cached
1095 };
1096 if let Some(target) =
1097 imperative::resolve_edit_target(row, col_id, &self.columns, display, (self.len_fn)())
1098 {
1099 drop(cached);
1100 self.editing_cell.set(Some(target));
1101 }
1102 }
1103
1104 /// Close the active cell editor without committing (the field's `on_blur` still fires).
1105 pub fn end_edit(&self) {
1106 self.editing_cell.set(None);
1107 }
1108
1109 /// Per-column filter text. Updated by filter affordances in
1110 /// header cells and by
1111 /// [`set_filter`](Self::set_filter) / [`clear_filters`](Self::clear_filters).
1112 /// Bind a `SortFilterListModel<T>` to drive the upstream data:
1113 ///
1114 /// ```ignore
1115 /// let proxy = SortFilterListModel::new(model)
1116 /// .with_predicate("name", |t| {
1117 /// let needle = t.to_string();
1118 /// Box::new(move |r: &Row| r.name.contains(&needle))
1119 /// });
1120 /// proxy.filters_signal(table.filters_signal().clone());
1121 /// ```
1122 pub fn filters_signal(&self) -> &Signal<HashMap<String, String>> {
1123 &self.filters_signal
1124 }
1125
1126 /// Set or clear the filter text for a single column. An empty `text` removes
1127 /// the entry for `col_id` (same as clearing the filter for that column).
1128 pub fn set_filter(&self, col_id: &str, text: &str) {
1129 imperative::set_filter(&self.filters_signal, col_id, text);
1130 }
1131
1132 /// Remove all active column filters.
1133 pub fn clear_filters(&self) {
1134 imperative::set_if_changed(&self.filters_signal, HashMap::new());
1135 }
1136
1137 // ── Imperative API ─────────────────────────────────────────────────
1138
1139 /// Scroll so that `row` is aligned to the top of the viewport. A no-op
1140 /// before the first layout pass.
1141 pub fn scroll_to_row(&self, row: usize) {
1142 imperative::scroll_to_row(row, &self.row_metrics, &self.scroll_y, &self.max_scroll_y);
1143 }
1144
1145 /// Set the active sort imperatively. Equivalent to writing to
1146 /// [`sort_signal`](Self::sort_signal) directly, except that an unchanged
1147 /// value neither writes nor notifies — see
1148 /// [`set_column_widths`](Self::set_column_widths).
1149 pub fn set_sort(&self, col_id: Option<&str>, dir: SortDirection) {
1150 let next = col_id.map(|c| (c.to_string(), dir));
1151 imperative::set_if_changed(&self.sort_signal, next);
1152 }
1153
1154 /// Clear the active sort.
1155 pub fn clear_sort(&self) {
1156 imperative::set_if_changed(&self.sort_signal, None);
1157 }
1158
1159 /// Set or remove a single column's user-resized width override.
1160 /// A non-positive `width` removes the entry (the column reverts to
1161 /// its declared width policy).
1162 pub fn set_column_width(&self, col_id: &str, width: f32) {
1163 imperative::set_column_width(&self.column_widths_signal, col_id, width);
1164 }
1165
1166 /// Replace the full width-override map (typically used to restore
1167 /// a persisted layout).
1168 ///
1169 /// A no-op when the map is unchanged, so the documented
1170 /// settings-round-trip wiring (see docs/table-view.md, "Persistence")
1171 /// terminates instead of recursing: `Signal::set` has no equality check of
1172 /// its own, and a live resize writes a width on every pointer move.
1173 pub fn set_column_widths(&self, widths: HashMap<String, f32>) {
1174 imperative::set_column_widths(&self.column_widths_signal, widths);
1175 }
1176
1177 /// Replace the column-order list. Ids not declared on this table
1178 /// are silently dropped on the next layout pass.
1179 pub fn set_column_order(&self, order: Vec<String>) {
1180 imperative::set_if_changed(&self.column_order_signal, order);
1181 }
1182
1183 /// Pin or unpin a single column.
1184 pub fn set_column_pinning(&self, col_id: &str, side: PinnedSide) {
1185 imperative::set_column_pinning(&self.column_pinning_signal, col_id, side);
1186 }
1187
1188 /// Effective pinning for a column — `column_pinning_signal` wins
1189 /// over the declared `Column::pinned`.
1190 fn effective_pinning(&self, col: &Column<T>) -> PinnedSide {
1191 self.column_pinning_signal
1192 .get()
1193 .get(&col.id)
1194 .copied()
1195 .unwrap_or(col.pinned)
1196 }
1197
1198 /// Compute the visible column display order: a flat list of indices
1199 /// into `self.columns`. Columns are partitioned by effective
1200 /// pinning (Leading first, then None, then Trailing); within each
1201 /// pane they appear in `column_order_signal` order, with any
1202 /// columns missing from the signal appended in declaration order.
1203 fn display_order(&self) -> Vec<usize> {
1204 let order_signal = self.column_order_signal.get();
1205 let mut order_map: HashMap<&str, usize> = HashMap::new();
1206 for (i, id) in order_signal.iter().enumerate() {
1207 order_map.insert(id.as_str(), i);
1208 }
1209 let mut leading: Vec<usize> = Vec::new();
1210 let mut middle: Vec<usize> = Vec::new();
1211 let mut trailing: Vec<usize> = Vec::new();
1212 for (i, col) in self.columns.iter().enumerate() {
1213 match self.effective_pinning(col) {
1214 PinnedSide::Leading => leading.push(i),
1215 PinnedSide::None => middle.push(i),
1216 PinnedSide::Trailing => trailing.push(i),
1217 }
1218 }
1219 // Sort key: explicit `column_order_signal` positions win (low
1220 // values); columns missing from the signal fall back to their
1221 // declaration index, offset by a huge constant so they always
1222 // sort after any explicitly-ordered column.
1223 const FALLBACK_BASE: usize = usize::MAX / 2;
1224 let sort_pane = |bucket: &mut Vec<usize>, cols: &[Column<T>]| {
1225 bucket.sort_by_key(|&i| {
1226 order_map
1227 .get(cols[i].id.as_str())
1228 .copied()
1229 .unwrap_or(FALLBACK_BASE + i)
1230 });
1231 };
1232 sort_pane(&mut leading, &self.columns);
1233 sort_pane(&mut middle, &self.columns);
1234 sort_pane(&mut trailing, &self.columns);
1235 let mut out = Vec::with_capacity(leading.len() + middle.len() + trailing.len());
1236 out.extend(leading);
1237 let leading_count = out.len();
1238 out.extend(middle);
1239 let middle_end = out.len();
1240 out.extend(trailing);
1241 // Stash the boundaries so paint / drop-zone math can read them.
1242 *self.pane_boundaries.borrow_mut() = PaneBoundaries::new(leading_count, middle_end);
1243 out
1244 }
1245
1246 /// Scroll the minimum distance needed to make `row` visible. A no-op
1247 /// before the first layout pass, when the viewport height is not yet known.
1248 pub fn ensure_row_visible(&self, row: usize) {
1249 imperative::ensure_row_visible(
1250 row,
1251 &self.row_metrics,
1252 &self.scroll_y,
1253 &self.max_scroll_y,
1254 self.viewport_height.get(),
1255 self.laid_out.get(),
1256 );
1257 }
1258
1259 // ── Internals ──────────────────────────────────────────────────────
1260
1261 /// The configured row height (override) or the table style's 28 px
1262 /// fallback. In the non-uniform modes this is the seed estimate;
1263 /// real geometry lives in `row_metrics`.
1264 fn effective_row_height(&self) -> f32 {
1265 self.row_height.unwrap_or(cp::ROW_HEIGHT)
1266 }
1267
1268 fn effective_header_height(&self) -> f32 {
1269 if !self.show_header {
1270 0.0
1271 } else {
1272 self.header_height.unwrap_or(cp::HEADER_HEIGHT)
1273 }
1274 }
1275
1276 fn total_content_height(&self) -> f32 {
1277 self.row_metrics.borrow_mut().total_height((self.len_fn)())
1278 }
1279
1280 fn visible_range(&self) -> (usize, usize) {
1281 self.row_metrics.borrow_mut().visible_range(
1282 self.scroll_y.get(),
1283 self.viewport_height.get(),
1284 (self.len_fn)(),
1285 BUFFER_ROWS,
1286 )
1287 }
1288
1289 fn clamp_scroll(&self) {
1290 let max = self.max_scroll_y.get();
1291 let current = self.scroll_y.get();
1292 let clamped = current.clamp(0.0, max);
1293 if (clamped - current).abs() > 0.001 {
1294 self.scroll_y.set(clamped);
1295 }
1296 }
1297}
1298
1299impl<T: 'static> std::fmt::Debug for TableView<T> {
1300 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1301 f.debug_struct("TableView")
1302 .field("rows", &(self.len_fn)())
1303 .field("columns", &self.columns.len())
1304 .field("scroll_y", &self.scroll_y.get())
1305 .field("selection_mode", &self.selection_mode)
1306 .field("scroll_bar_style", &self.scroll_bar_style)
1307 .finish()
1308 }
1309}
1310
1311impl<T: 'static> Widget for TableView<T> {
1312 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
1313 let self_id = ctx.self_id();
1314 ctx.enabled_when(self_id, self.enabled.clone());
1315
1316 let row_h = self.effective_row_height();
1317 let header_h = self.effective_header_height();
1318
1319 // Version signal — bumps drive a rebuild.
1320 let version = ctx.signal(0_u64);
1321 version.bind_to(ctx.self_id(), ctx.binding_registry(), BindingLevel::Rebuild);
1322
1323 // Scroll-y at Relayout: place_children re-runs without rebuild.
1324 self.scroll_y.bind_to(
1325 ctx.self_id(),
1326 ctx.binding_registry(),
1327 BindingLevel::Relayout,
1328 );
1329 ctx.register_animated_signal(&self.scroll_y);
1330
1331 // Scroll-x mirrors scroll-y: Relayout re-places the header + body
1332 // bands (and any pane-aware root decorations) without a rebuild.
1333 self.scroll_x.bind_to(
1334 ctx.self_id(),
1335 ctx.binding_registry(),
1336 BindingLevel::Relayout,
1337 );
1338 ctx.register_animated_signal(&self.scroll_x);
1339
1340 // Row-drop insertion indicator at RepaintOnly so on_drag_hover /
1341 // on_drag_leave `set(...)` calls dirty paint without a rebuild.
1342 self.drop_feedback.bind_to(
1343 ctx.self_id(),
1344 ctx.binding_registry(),
1345 BindingLevel::RepaintOnly,
1346 );
1347
1348 // Pane → root total refresh (auto-measure mode): re-place this
1349 // root when the body pane's measurements changed the content
1350 // total, so `max_scroll_y` / the thumb ratio pick up the
1351 // corrected value.
1352 self.pane_total_refresh.bind_to(
1353 ctx.self_id(),
1354 ctx.binding_registry(),
1355 BindingLevel::Relayout,
1356 );
1357
1358 // Column width overrides: any change re-runs place_children
1359 // (which calls ColumnSolver with the latest map). No rebuild
1360 // needed — widths flow through `column_widths` Rc into rows.
1361 self.column_widths_signal.bind_to(
1362 ctx.self_id(),
1363 ctx.binding_registry(),
1364 BindingLevel::Relayout,
1365 );
1366
1367 // `OnRelease` resize guide line — paint-only, nothing moves until the
1368 // button comes up.
1369 self.resize_preview_x.bind_to(
1370 ctx.self_id(),
1371 ctx.binding_registry(),
1372 BindingLevel::RepaintOnly,
1373 );
1374
1375 // A resize drag that loses the window never gets its PointerUp: the
1376 // user Alt-Tabs (or a native dialog steals focus) with the button
1377 // down, releases it over another window, and the OS delivers the Up
1378 // nowhere. Abandon the gesture on deactivation, or the state outlives
1379 // it and the next bare PointerMove drags the column with no button
1380 // held. Nothing is committed — an interrupted drag leaves the column
1381 // wherever the last delivered move put it, which is what the user last
1382 // saw.
1383 {
1384 let resize_state = self.resize_state.clone();
1385 let resize_target = self.resize_target.clone();
1386 let resize_preview_x = self.resize_preview_x.clone();
1387 ctx.effect(&ctx.window_active_signal(), move |active| {
1388 if !*active && resize_state.borrow().is_some() {
1389 *resize_state.borrow_mut() = None;
1390 resize_target.set(None);
1391 resize_preview_x.set(None);
1392 }
1393 });
1394 }
1395
1396 // Column order + pinning: changes require a rebuild because the
1397 // header cells and row cells must be re-emitted in the new order
1398 // (each cell captures its display-position-based 1-based index).
1399 let v_for_order = version.clone();
1400 let order_ver = Rc::new(Cell::new(0_u64));
1401 ctx.effect(&self.column_order_signal, move |_| {
1402 let next = order_ver.get() + 1;
1403 order_ver.set(next);
1404 v_for_order.set(next);
1405 });
1406 let v_for_pin = version.clone();
1407 let pin_ver = Rc::new(Cell::new(0_u64));
1408 ctx.effect(&self.column_pinning_signal, move |_| {
1409 let next = pin_ver.get() + 1;
1410 pin_ver.set(next);
1411 v_for_pin.set(next);
1412 });
1413 let v_for_edit = version.clone();
1414 let edit_ver = Rc::new(Cell::new(0_u64));
1415 ctx.effect(&self.editing_cell, move |_| {
1416 let next = edit_ver.get() + 1;
1417 edit_ver.set(next);
1418 v_for_edit.set(next);
1419 });
1420 let v_for_filter = version.clone();
1421 let filter_ver = Rc::new(Cell::new(0_u64));
1422 ctx.effect(&self.filters_signal, move |_| {
1423 let next = filter_ver.get() + 1;
1424 filter_ver.set(next);
1425 v_for_filter.set(next);
1426 });
1427
1428 // Sort signal: a change requires a rebuild because each header
1429 // cell's chevron child is added/removed conditionally and the
1430 // AccessKit `set_sort_direction` is captured at build time.
1431 let v_for_sort = version.clone();
1432 let sort_ver = Rc::new(Cell::new(0_u64));
1433 ctx.effect(&self.sort_signal, move |_| {
1434 let next = sort_ver.get() + 1;
1435 sort_ver.set(next);
1436 v_for_sort.set(next);
1437 });
1438
1439 // Observe model changes -> bump version.
1440 let v_for_data = version.clone();
1441 let data_ver = Rc::new(Cell::new(0_u64));
1442 let upstream = (self.observe_fn)(Box::new({
1443 let dv = data_ver.clone();
1444 let sel_for_adjust = self.row_selection.clone();
1445 let cell_sel_for_adjust = self.cell_selection.clone();
1446 let metrics_for_data = self.row_metrics.clone();
1447 let len_for_data = self.len_fn.clone();
1448 let first_changed = self.first_changed_fn.clone();
1449 move |change| {
1450 // Keep row metrics in step with the data: rows before
1451 // the first changed index keep their heights, the rest
1452 // re-derive. A `SortFilterListModel` source collapses
1453 // everything to `Reset` — its real divergence comes
1454 // through the side-channel, which is what lets an
1455 // append keep the measured prefix.
1456 let divergence = match change {
1457 DataChange::ItemsInserted { range } | DataChange::ItemsRemoved { range } => {
1458 Some(range.start)
1459 }
1460 DataChange::ItemUpdated { index } => Some(*index),
1461 DataChange::ItemsMoved { from, to, .. } => Some((*from).min(*to)),
1462 DataChange::WindowLoaded { range } => Some(range.start),
1463 DataChange::Reset => (first_changed)(),
1464 };
1465 metrics_for_data
1466 .borrow_mut()
1467 .apply_divergence(divergence, (len_for_data)());
1468 // Keep row selection in step: index-shift (index model) or
1469 // prune orphaned keys (keyed model). Cell selection (always
1470 // index-based) is adjusted separately below.
1471 if let Some(ref rs) = sel_for_adjust {
1472 rs.on_data_change(change);
1473 }
1474 if let Some(ref s) = cell_sel_for_adjust {
1475 match change {
1476 DataChange::ItemsInserted { range } => {
1477 s.adjust_for_row_insert(range.start, range.end - range.start);
1478 }
1479 DataChange::ItemsRemoved { range } => {
1480 s.adjust_for_row_remove(range.start, range.end - range.start);
1481 }
1482 DataChange::ItemsMoved { from, to, count } => {
1483 s.adjust_for_row_move(*from, *to, *count);
1484 }
1485 DataChange::Reset => s.clear(),
1486 _ => {}
1487 }
1488 }
1489 let next = dv.get() + 1;
1490 dv.set(next);
1491 v_for_data.set(next);
1492 }
1493 }));
1494 ctx.own_handle(upstream);
1495
1496 // Observe selection changes -> bump version (rebuild updates the
1497 // `is_selected` arg passed to cell delegates).
1498 if let Some(ref rs) = self.row_selection {
1499 let v_for_sel = version.clone();
1500 let sel_ver = Rc::new(Cell::new(0_u64));
1501 let handle = rs.observe_for_rebuild(move || {
1502 let next = sel_ver.get() + 1;
1503 sel_ver.set(next);
1504 v_for_sel.set(next);
1505 });
1506 ctx.own_handle(handle);
1507 }
1508 if let Some(ref cs) = self.cell_selection {
1509 let v_for_csel = version.clone();
1510 let csel_ver = Rc::new(Cell::new(0_u64));
1511 ctx.effect(&cs.selection_signal(), move |_| {
1512 let next = csel_ver.get() + 1;
1513 csel_ver.set(next);
1514 v_for_csel.set(next);
1515 });
1516 }
1517
1518 // Observe scroll position — only rebuild when visible range exits
1519 // the buffered window. The Relayout binding above handles
1520 // intra-buffer scrolls without a rebuild.
1521 let vp_h = self.viewport_height.clone();
1522 let len_for_scroll = self.len_fn.clone();
1523 let (built_start, built_end) = self.visible_range();
1524 let prev_built_start = Rc::new(Cell::new(built_start));
1525 let prev_built_end = Rc::new(Cell::new(built_end));
1526 let v_for_scroll = version.clone();
1527 let scroll_ver = Rc::new(Cell::new(0_u64));
1528 let scroll_handle = self.scroll_y.observe({
1529 let pbs = prev_built_start.clone();
1530 let pbe = prev_built_end.clone();
1531 let sv = scroll_ver.clone();
1532 let metrics = self.row_metrics.clone();
1533 move |y| {
1534 let count = (len_for_scroll)();
1535 let (visible_start, visible_end) =
1536 metrics.borrow_mut().visible_range(*y, vp_h.get(), count, 0);
1537 if visible_start < pbs.get() || visible_end > pbe.get() {
1538 let new_start = visible_start.saturating_sub(BUFFER_ROWS);
1539 let new_end = (visible_end + BUFFER_ROWS).min(count);
1540 pbs.set(new_start);
1541 pbe.set(new_end);
1542 let next = sv.get() + 1;
1543 sv.set(next);
1544 v_for_scroll.set(next);
1545 }
1546 }
1547 });
1548 ctx.own_handle(scroll_handle);
1549
1550 // Compute display order eagerly — the keyboard handler needs
1551 // the column count, and the header / body builds below also
1552 // need it. We re-write `self.display_indices` here; later
1553 // build steps read it.
1554 let display_indices_now = self.display_order();
1555
1556 // Remap any `(row, display_pos)` pairs the *previous* order left in
1557 // `focused_cell` / `editing_cell` / `cell_selection` onto their
1558 // column's position under the order just computed, before it
1559 // overwrites `self.display_indices` below. A column reorder drag or
1560 // a pin toggle only bumps `version` (see the `column_order_signal` /
1561 // `column_pinning_signal` effects above) — display position is
1562 // recomputed here on every rebuild regardless of cause, so this map
1563 // is the identity (a no-op) unless THIS rebuild's cause was an
1564 // order/pinning change.
1565 {
1566 let old_display = self.display_indices.borrow();
1567 if !old_display.is_empty() {
1568 let old_to_new: Vec<Option<usize>> = old_display
1569 .iter()
1570 .map(|&decl_idx| {
1571 let id = &self.columns[decl_idx].id;
1572 display_indices_now
1573 .iter()
1574 .position(|&new_decl_idx| self.columns[new_decl_idx].id == *id)
1575 })
1576 .collect();
1577 drop(old_display);
1578 imperative::remap_cell_state(
1579 &self.focused_cell,
1580 &self.editing_cell,
1581 self.cell_selection.as_ref(),
1582 &old_to_new,
1583 );
1584 }
1585 }
1586 *self.display_indices.borrow_mut() = display_indices_now.clone();
1587
1588 // Self handlers: scroll wheel + keyboard + clip + focusable.
1589 let scroll_y_for_wheel = self.scroll_y.clone();
1590 let max_scroll_for_wheel = self.max_scroll_y.clone();
1591 let scroll_x_for_wheel = self.scroll_x.clone();
1592 let max_scroll_x_for_wheel = self.max_scroll_x.clone();
1593 let line_height = row_h;
1594 let overscroll_behavior = self.overscroll_behavior;
1595 let smooth_scrolling = self.smooth_scrolling;
1596 let smooth_scroll_duration = self.smooth_scroll_duration;
1597
1598 // Bind focused_cell at RepaintOnly — its update redraws the
1599 // focus ring without rebuilding the row tree. Also at
1600 // AccessibilityOnly (orthogonal — see `BindingLevel`) so a
1601 // keyboard focus move re-walks the AT tree and re-resolves
1602 // `active_descendant` in `accessibility()` below, even though
1603 // nothing about the cell's own node changed.
1604 self.focused_cell.bind_to(
1605 ctx.self_id(),
1606 ctx.binding_registry(),
1607 BindingLevel::RepaintOnly,
1608 );
1609 self.focused_cell.bind_to(
1610 ctx.self_id(),
1611 ctx.binding_registry(),
1612 BindingLevel::AccessibilityOnly,
1613 );
1614
1615 // Focus-aware selection + modality-gated focus ring. `begin_view_focus`
1616 // keys the scope signal on this root id directly — the same id the body
1617 // pane uses for its row scope (`drag_anchor = ctx.self_id()`), and
1618 // independent of the arena focusable flag (not yet wired here). A plain
1619 // `view_focus_active()` here would find no focusable ancestor and fall
1620 // back to the constant-`true` "outside any scope" signal — `true`
1621 // whenever ANY widget holds focus, lighting every table's ring at once.
1622 // The signal is `true` whenever the table or any descendant holds focus,
1623 // so the selection band dims to `SelectedInactive` on focus-out. Pop
1624 // straight back; the body pane re-pushes the same cached signal.
1625 // `focus_visible` gates the cell ring to keyboard navigation. Both bound
1626 // `RepaintOnly`: a focus/modality change redraws without a rebuild.
1627 self.view_focused = ctx.begin_view_focus();
1628 ctx.end_view_focus();
1629 self.focus_visible = ctx.focus_visible();
1630 self.view_focused.bind_to(
1631 ctx.self_id(),
1632 ctx.binding_registry(),
1633 BindingLevel::RepaintOnly,
1634 );
1635 self.focus_visible.bind_to(
1636 ctx.self_id(),
1637 ctx.binding_registry(),
1638 BindingLevel::RepaintOnly,
1639 );
1640
1641 // Build the navigator + key handler. The keyboard module is
1642 // generic over RowNavigator so TreeTableView can plug in its own
1643 // tree-aware navigator.
1644 let navigator: Rc<dyn row_navigator::RowNavigator> =
1645 Rc::new(row_navigator::FlatNavigator::new(self.len_fn.clone()));
1646 // display_col_to_id resolves a display position back to its
1647 // column id, so the keyboard module doesn't need a `Column<T>`
1648 // reference. Snapshotted at build; rebuilds re-issue this.
1649 let column_ids_in_display_order: Vec<String> = display_indices_now
1650 .iter()
1651 .map(|&i| self.columns[i].id.clone())
1652 .collect();
1653 let display_col_to_id: Rc<dyn Fn(usize) -> Option<String>> = {
1654 let ids = column_ids_in_display_order;
1655 Rc::new(move |pos| ids.get(pos).cloned())
1656 };
1657 // The effective trigger set per display column: the view's, overridden
1658 // by the column's own, and `NONE` for a non-editable one. Resolved here
1659 // so the keyboard handler never has to reach a `Column<T>`.
1660 let display_col_triggers: Rc<dyn Fn(usize) -> EditTriggers> = {
1661 let view_triggers = self.edit_triggers;
1662 let per_display_column: Vec<EditTriggers> = display_indices_now
1663 .iter()
1664 .map(|&i| self.columns[i].effective_edit_triggers(view_triggers))
1665 .collect();
1666 Rc::new(move |pos| {
1667 per_display_column
1668 .get(pos)
1669 .copied()
1670 .unwrap_or(EditTriggers::NONE)
1671 })
1672 };
1673
1674 // Type-ahead label resolver (row -> Some(text)) built from the user's
1675 // `Fn(&T) -> String` + the side-effect source read: the closure only
1676 // fires for a resident row, so unloaded (lazy) rows resolve to `None`
1677 // and the search skips them.
1678 let type_ahead_label: Option<Rc<dyn Fn(usize) -> Option<String>>> =
1679 self.type_ahead_label.clone().map(|user| {
1680 let with_item = self.with_item_fn.clone();
1681 Rc::new(move |i: usize| {
1682 let out = std::cell::RefCell::new(None);
1683 (with_item)(i, &|item| {
1684 *out.borrow_mut() = Some(user(item));
1685 });
1686 out.into_inner()
1687 }) as Rc<dyn Fn(usize) -> Option<String>>
1688 });
1689
1690 let key_cfg = keyboard::KeyHandlerConfig {
1691 navigator,
1692 col_count: display_indices_now.len().max(1),
1693 // Flat table: no tree column exists. `FlatNavigator` reports no
1694 // children and never expands, so this value is inert — it only has
1695 // to be a position the cursor can actually occupy.
1696 tree_column_display_pos: 0,
1697 focused_cell: self.focused_cell.clone(),
1698 selection_mode: self.selection_mode,
1699 selection: self.row_selection.clone(),
1700 cell_selection: self.cell_selection.clone(),
1701 scroll_y: self.scroll_y.clone(),
1702 max_scroll_y: self.max_scroll_y.clone(),
1703 viewport_height: self.viewport_height.clone(),
1704 body_bounds: self.body_bounds.clone(),
1705 row_metrics: self.row_metrics.clone(),
1706 tab_traversal: self.tab_traversal,
1707 editing_cell: self.editing_cell.clone(),
1708 display_col_to_id,
1709 display_col_triggers,
1710 on_cell_edit_request: self.on_cell_edit_request.clone(),
1711 on_row_activate: self.on_row_activate.clone(),
1712 type_ahead: self.type_ahead.clone(),
1713 type_ahead_label,
1714 type_ahead_timeout: self.type_ahead_timeout,
1715 column_widths: self.column_widths.clone(),
1716 pane_boundaries: *self.pane_boundaries.borrow(),
1717 scroll_x: self.scroll_x.clone(),
1718 max_scroll_x: self.max_scroll_x.clone(),
1719 middle_viewport_width: self.middle_viewport_width.clone(),
1720 };
1721
1722 // Row DnD is owned by the backing source. The view computes the
1723 // geometric (target_row, position) and asks the source: `can_accept`
1724 // on hover gates the insertion line (forbidden → no affordance),
1725 // `accept_drop` on release commits the move (in-place for a
1726 // `ListModel`, routed for an external source). Same-view reorders and
1727 // foreign / cross-table drops both flow through `accept_drop` — the
1728 // erased closures recover SameView-vs-Foreign from the payload.
1729 let view_id = self.model_id;
1730 let can_accept_hover = self.dnd.can_accept_fn.clone();
1731 let scroll_for_hover = self.scroll_y.clone();
1732 let metrics_for_hover = self.row_metrics.clone();
1733 let len_for_hover = self.len_fn.clone();
1734 let header_h_for_hover = header_h;
1735 let band_width_for_hover = self.header_strip_width.clone();
1736 let feedback_for_hover = self.drop_feedback.clone();
1737 let export_for_hover = self.export.clone();
1738
1739 let accept_drop_for_drop = self.dnd.accept_drop_fn.clone();
1740 let scroll_y_for_drop = self.scroll_y.clone();
1741 let header_h_for_drop = header_h;
1742 let metrics_for_drop = self.row_metrics.clone();
1743 let len_fn_for_drop = self.len_fn.clone();
1744 let feedback_for_drop = self.drop_feedback.clone();
1745 let export_for_drop = self.export.clone();
1746 let reorderable_for_drop = self.reorderable;
1747
1748 let feedback_for_leave = self.drop_feedback.clone();
1749 let scroll_for_tick = self.scroll_y.clone();
1750 let max_scroll_for_tick = self.max_scroll_y.clone();
1751 let viewport_for_tick = self.viewport_height.clone();
1752 let header_h_for_tick = header_h;
1753
1754 // Alt+Arrow reorder wraps the shared key handler: the move is a
1755 // synthetic same-view `RowDragData` through the source's
1756 // `accept_drop`, so it travels exactly the pointer-drop path. Every
1757 // other key falls through to the shared navigator (cell/row
1758 // movement, edit, etc.).
1759 let mut shared_key = keyboard::build_key_handler(key_cfg);
1760 let reorderable_kbd = self.reorderable;
1761 let accept_drop_kbd = self.dnd.accept_drop_fn.clone();
1762 let stash_kbd = self.dnd.stash_drag_keys_fn.clone();
1763 let focused_kbd = self.focused_cell.clone();
1764 let sel_kbd = self.row_selection.clone();
1765 let len_kbd = self.len_fn.clone();
1766 let key_handler = move |event: &teksilo_core::event::WidgetEvent,
1767 ctx: &mut teksilo_core::widget::EventContext|
1768 -> teksilo_core::event::EventResponse {
1769 use teksilo_core::event::{EventResponse, Key, WidgetEvent};
1770 if reorderable_kbd
1771 && let WidgetEvent::KeyDown { key, modifiers, .. } = event
1772 && modifiers.alt()
1773 {
1774 let count = (len_kbd)();
1775 if count > 0 {
1776 let cur = focused_kbd.get().map(|(r, _)| r).or_else(|| {
1777 sel_kbd
1778 .as_ref()
1779 .and_then(|s| s.selected_indices().first().copied())
1780 });
1781 if let Some(idx) = cur {
1782 let mv = match key {
1783 Key::ArrowUp if idx > 0 => {
1784 Some((idx - 1, DropPosition::Before, idx - 1))
1785 }
1786 Key::ArrowDown if idx + 1 < count => {
1787 Some((idx + 1, DropPosition::After, idx + 1))
1788 }
1789 _ => None,
1790 };
1791 if let Some((target, position, dest)) = mv {
1792 // Synthetic same-view payloads must stash the
1793 // dragged row's key at construction — the accept
1794 // path resolves identity from the stash, never
1795 // from `rows`.
1796 (stash_kbd)(&[idx]);
1797 let payload =
1798 teksilo_core::drag_payload::DragPayload::typed(RowDragData::<T> {
1799 source: view_id,
1800 rows: vec![idx],
1801 items: None,
1802 });
1803 if (accept_drop_kbd)(&payload, target, position, view_id) {
1804 if let Some(ref s) = sel_kbd {
1805 s.select(dest);
1806 }
1807 let col = focused_kbd.get().map(|(_, c)| c).unwrap_or(0);
1808 focused_kbd.set(Some((dest, col)));
1809 }
1810 return EventResponse::Handled;
1811 }
1812 }
1813 }
1814 }
1815 shared_key(event, ctx)
1816 };
1817
1818 let mut handlers = HandlerSet::new()
1819 .on_scroll(move |event, _ctx| match event {
1820 teksilo_core::event::WidgetEvent::Scroll { delta, modifiers } => {
1821 let (raw_dx, raw_dy) = match delta {
1822 teksilo_core::event::ScrollDelta::Lines { x, y } => {
1823 (x * line_height, y * line_height)
1824 }
1825 teksilo_core::event::ScrollDelta::Pixels { x, y } => (*x, *y),
1826 };
1827 // Shift+wheel remaps a vertical-only wheel to horizontal
1828 // scroll (the `TabBar` precedent) — a genuine two-axis
1829 // trackpad delta (both native `dx` and `dy` nonzero)
1830 // passes through unremapped either way.
1831 let (dx, dy) = if modifiers.shift() && raw_dx.abs() < f32::EPSILON {
1832 (raw_dy, 0.0)
1833 } else {
1834 (raw_dx, raw_dy)
1835 };
1836
1837 let mut moved_any = false;
1838 if dy.abs() > 0.0 {
1839 let current = scroll_y_for_wheel.get();
1840 let max = max_scroll_for_wheel.get();
1841 // Base off the animation target (not the rendered
1842 // offset) so a mid-fling boundary correctly chains
1843 // and successive notches accumulate instead of
1844 // restarting from the partway-animated position.
1845 let base = scroll_y_for_wheel.animation_target().unwrap_or(current);
1846 let (new_y, moved) =
1847 crate::common::scroll::scroll_clamp_axis(base, dy, max);
1848 if moved {
1849 if smooth_scrolling {
1850 scroll_y_for_wheel.animate_to(
1851 new_y,
1852 smooth_scroll_duration,
1853 Easing::EaseOut,
1854 );
1855 } else {
1856 scroll_y_for_wheel.set(new_y);
1857 }
1858 }
1859 moved_any |= moved;
1860 }
1861 if dx.abs() > 0.0 {
1862 let current = scroll_x_for_wheel.get();
1863 let max = max_scroll_x_for_wheel.get();
1864 let base = scroll_x_for_wheel.animation_target().unwrap_or(current);
1865 let (new_x, moved) =
1866 crate::common::scroll::scroll_clamp_axis(base, dx, max);
1867 if moved {
1868 if smooth_scrolling {
1869 scroll_x_for_wheel.animate_to(
1870 new_x,
1871 smooth_scroll_duration,
1872 Easing::EaseOut,
1873 );
1874 } else {
1875 scroll_x_for_wheel.set(new_x);
1876 }
1877 }
1878 moved_any |= moved;
1879 }
1880 // Chain to an ancestor scrollable when fully clamped on
1881 // every axis touched (unless Contain), otherwise consume.
1882 crate::common::scroll::scroll_response(
1883 moved_any,
1884 overscroll_behavior == OverscrollBehavior::Contain,
1885 )
1886 }
1887 _ => teksilo_core::event::EventResponse::Ignored,
1888 })
1889 .clips_children(true)
1890 .focusable(true);
1891
1892 handlers = handlers.on_key(key_handler);
1893
1894 // Row-level drop target: registered only when this table can
1895 // reorder its own rows or accept foreign ones (mirrors ListView).
1896 // Column reorder lives entirely on the header strip
1897 // (`attach_header_reorder_handlers`) and is untouched by this gate.
1898 if self.export.is_drop_target(self.reorderable) {
1899 handlers = handlers
1900 .on_drag_hover(move |payload, position, _ctx| {
1901 // Column reorder is handled by the header strip; only
1902 // row-level drops (same-view `RowDragData` or a foreign
1903 // payload the source accepts) get an insertion line here.
1904 if payload.has_typed::<ColumnReorderDragData>() {
1905 feedback_for_hover.set(None);
1906 return teksilo_core::DropFeedback::NoFeedback;
1907 }
1908 let body_y = position.y - header_h_for_hover;
1909 let scroll = scroll_for_hover.get();
1910 let content_y = body_y + scroll;
1911 let len = (len_for_hover)();
1912 let (ins, line_y) = {
1913 let mut m = metrics_for_hover.borrow_mut();
1914 m.resize(len);
1915 let ins = m.insertion_index(content_y);
1916 (ins, m.row_top(ins) - scroll)
1917 };
1918 let width = band_width_for_hover.get();
1919 // Source-owned validation: paint the line only when the
1920 // source does not reject the hovered position. A foreign
1921 // exported row is allowed when `accept_foreign_rows` is on
1922 // even though a bare `ListModel`'s `can_accept` rejects
1923 // the `Foreign` branch.
1924 let allowed = flat_insertion_target(ins, len).is_some_and(|(target, pos)| {
1925 !matches!(
1926 (can_accept_hover)(payload, target, pos, view_id),
1927 DropResponse::Reject
1928 ) || export_for_hover.accepts_foreign_export(payload, view_id)
1929 });
1930 if allowed {
1931 feedback_for_hover.set(Some((line_y, width)));
1932 teksilo_core::DropFeedback::InsertionLine { y: line_y, width }
1933 } else {
1934 feedback_for_hover.set(None);
1935 teksilo_core::DropFeedback::NoFeedback
1936 }
1937 })
1938 .on_drop(move |mut payload, position, ctx| {
1939 feedback_for_drop.set(None);
1940 if payload.has_typed::<ColumnReorderDragData>() {
1941 return false;
1942 }
1943 let body_y = position.y - header_h_for_drop;
1944 let scroll = scroll_y_for_drop.get();
1945 let content_y = body_y + scroll;
1946 let len = (len_fn_for_drop)();
1947 let ins = {
1948 let mut m = metrics_for_drop.borrow_mut();
1949 m.resize(len);
1950 m.insertion_index(content_y)
1951 };
1952 let is_same_view = payload
1953 .get_typed::<RowDragData<T>>()
1954 .is_some_and(|rd| rd.source == view_id);
1955 // Route the drop to the source's accept_drop first. A
1956 // same-view reorder only happens when the table is
1957 // `reorderable`; a foreign payload is the source's
1958 // call (a bare ListModel rejects it).
1959 if (reorderable_for_drop || !is_same_view)
1960 && let Some((target, position_kind)) = flat_insertion_target(ins, len)
1961 && (accept_drop_for_drop)(&payload, target, position_kind, view_id)
1962 {
1963 // Only suppress our OWN move-out for a genuine
1964 // same-view drop.
1965 if is_same_view {
1966 export_for_drop.note_self_reorder();
1967 }
1968 return true;
1969 }
1970 // Otherwise, the shared foreign-receive sugar
1971 // (peek-before-take).
1972 export_for_drop.foreign_receive(&mut payload, view_id, ins, ctx)
1973 })
1974 .on_drag_leave(move |_ctx| {
1975 feedback_for_leave.set(None);
1976 })
1977 .on_drag_tick(move |pos, _ctx| {
1978 // Auto-scroll when the pointer lingers within 32 px of the
1979 // body band's top/bottom edge during a drag (body-relative
1980 // so the header doesn't count as the top edge).
1981 const EDGE: f32 = 32.0;
1982 const MAX_VELOCITY: f32 = 12.0;
1983 let body_h = (viewport_for_tick.get() - header_h_for_tick).max(0.0);
1984 let y = pos.y - header_h_for_tick;
1985 let above = (EDGE - y).max(0.0);
1986 let below = (y - (body_h - EDGE)).max(0.0);
1987 let delta = if above > 0.0 {
1988 -(above / EDGE) * MAX_VELOCITY
1989 } else if below > 0.0 {
1990 (below / EDGE) * MAX_VELOCITY
1991 } else {
1992 0.0
1993 };
1994 if delta.abs() > 0.01 {
1995 let max = max_scroll_for_tick.get();
1996 let new_y = (scroll_for_tick.get() + delta).clamp(0.0, max);
1997 scroll_for_tick.set(new_y);
1998 }
1999 });
2000 }
2001
2002 // Export completion (move-out): fires on the drag source — this
2003 // table's root id, the stable id `start_drag` was given.
2004 handlers = self.export.install_completion(handlers);
2005
2006 ctx.apply_self_handlers(handlers);
2007
2008 // ── Build children ────────────────────────────────────────────
2009 self.header_row_id = None;
2010 self.body_pane_id = None;
2011 self.scrollbar_id = None;
2012 self.h_scrollbar_id = None;
2013 self.empty_id = None;
2014
2015 // Display order was already computed above (before the
2016 // keyboard handler was wired); pull it back into a local for
2017 // the header / body loops.
2018 let display_indices = display_indices_now;
2019
2020 // Header strip: build first so it sits above the body in the
2021 // child order (place_children iterates in this order).
2022 if self.show_header {
2023 // A rebuild destroys (and re-creates) every header cell, which
2024 // drops the pointer capture an in-flight resize depends on. Clear
2025 // the shared drag state with it: a `ResizeState` that outlived its
2026 // anchor would otherwise let the next bare PointerMove over the
2027 // same column resize it with no button held.
2028 *self.resize_state.borrow_mut() = None;
2029 self.resize_target.set(None);
2030 self.resize_preview_x.set(None);
2031
2032 let boundaries = *self.pane_boundaries.borrow();
2033 let resize_columns: header::ColumnResizeTable = Rc::new(
2034 display_indices
2035 .iter()
2036 .map(|&i| {
2037 let c = &self.columns[i];
2038 header::ColumnResizeInfo {
2039 id: c.id.clone(),
2040 min_width: c.min_width.unwrap_or(cp::MIN_COLUMN_WIDTH_DEFAULT),
2041 max_width: c.max_width,
2042 resizable: c.resizable,
2043 }
2044 })
2045 .collect(),
2046 );
2047 let mut cell_ids: Vec<WidgetId> = Vec::with_capacity(display_indices.len());
2048 let active_sort = self.sort_signal.get();
2049 for (display_pos, &col_idx) in display_indices.iter().enumerate() {
2050 let col = &self.columns[col_idx];
2051 let current_sort = active_sort
2052 .as_ref()
2053 .and_then(|(id, dir)| if id == &col.id { Some(*dir) } else { None });
2054 // Filter zone width: indicator glyph + a small horizontal
2055 // padding for tap tolerance. Mirrors the layout of the
2056 // HStack inside HeaderCell::build.
2057 let filter_zone_width = cp::FILTER_INDICATOR_SIZE + cp::CELL_PADDING_HORIZONTAL;
2058 let cell = header::HeaderCell::new(header::HeaderCellSpec {
2059 col_id: col.id.clone(),
2060 label: col.header_label.resolve_now(),
2061 col_index_1based: display_pos + 1,
2062 sortable: col.sortable,
2063 reorderable: col.reorderable,
2064 filterable: col.filterable,
2065 resize_grip: cp::RESIZE_HANDLE_WIDTH,
2066 filter_zone_width,
2067 current_sort,
2068 width_index: display_pos,
2069 pane_boundaries: boundaries,
2070 resize_columns: resize_columns.clone(),
2071 resize_policy: self.column_resize_policy,
2072 resize_state: self.resize_state.clone(),
2073 resize_target: self.resize_target.clone(),
2074 resize_preview_x: self.resize_preview_x.clone(),
2075 table_id: self.table_id,
2076 sort_signal: self.sort_signal.clone(),
2077 column_widths_signal: self.column_widths_signal.clone(),
2078 column_widths: self.column_widths.clone(),
2079 filters_signal: self.filters_signal.clone(),
2080 });
2081 cell_ids.push(ctx.add(cell));
2082 }
2083 let header_row = header::HeaderRow::new(
2084 cell_ids,
2085 self.column_widths.clone(),
2086 cp::GRID_LINE_THICKNESS,
2087 *self.pane_boundaries.borrow(),
2088 self.scroll_x.clone(),
2089 );
2090 // Wire reorder drag-target handlers on the header strip.
2091 let header_row_id = ctx.add(header_row);
2092 header::attach_header_reorder_handlers(
2093 ctx,
2094 header_row_id,
2095 self.table_id,
2096 self.column_widths.clone(),
2097 self.display_indices.clone(),
2098 self.pane_boundaries.clone(),
2099 self.column_order_signal.clone(),
2100 self.column_pinning_signal.clone(),
2101 self.columns.iter().map(|c| c.id.clone()).collect(),
2102 self.header_strip_width.clone(),
2103 self.scroll_x.clone(),
2104 );
2105 self.header_row_id = Some(header_row_id);
2106 }
2107
2108 let row_count = (self.len_fn)();
2109
2110 // Lazy: nudge the source to load the realized window, and fetch the
2111 // next page as the viewport nears the end (append-only sources). A
2112 // fully-resident source leaves these inert.
2113 let (vis_start, vis_end) = self.visible_range();
2114 (self.dnd.request_window_fn)(vis_start..vis_end);
2115 if (self.dnd.can_fetch_more_fn)() && vis_end + BUFFER_ROWS >= row_count {
2116 (self.dnd.fetch_more_fn)();
2117 }
2118
2119 if row_count == 0 {
2120 // Empty state.
2121 if let Some(ref f) = self.empty_view {
2122 let id = ctx.add_boxed(f());
2123 self.empty_id = Some(id);
2124 }
2125 } else {
2126 // Hoist the row pane into its own widget so that
2127 // scroll-buffer-exit rebuilds (which happen mid-thumb-drag
2128 // when the user scrolls past the buffered range) target a
2129 // sibling of the scrollbar rather than the scrollbar's
2130 // ancestor. Rebuilding the ancestor would be deferred by
2131 // the framework (to preserve the captured drag), leaving
2132 // the body empty until the user released the thumb.
2133 let pane = body_pane::BodyPane::<T> {
2134 len_fn: self.len_fn.clone(),
2135 with_item_fn: self.with_item_fn.clone(),
2136 drag_fn: self.dnd.drag_fn.clone(),
2137 row_state_fn: self.dnd.row_state_fn.clone(),
2138 columns: self.columns.clone(),
2139 display_indices: self.display_indices.clone(),
2140 column_widths: self.column_widths.clone(),
2141 pane_boundaries: *self.pane_boundaries.borrow(),
2142 scroll_x: self.scroll_x.clone(),
2143 row_metrics: self.row_metrics.clone(),
2144 selection_mode: self.selection_mode,
2145 selection: self.row_selection.clone(),
2146 cell_selection: self.cell_selection.clone(),
2147 scroll_y: self.scroll_y.clone(),
2148 viewport_height: self.viewport_height.clone(),
2149 editing_cell: self.editing_cell.clone(),
2150 focused_cell: self.focused_cell.clone(),
2151 reorderable: self.reorderable,
2152 export: self.export.clone(),
2153 snapshot_out_fn: self.dnd.snapshot_out_fn.clone(),
2154 anchor_fn: self.anchor_fn.clone(),
2155 editing_anchor: self.editing_anchor.clone(),
2156 view_id: self.model_id,
2157 drag_anchor: ctx.self_id(),
2158 on_row_activate: self.on_row_activate.clone(),
2159 activate_on: self.activate_on,
2160 edit_triggers: self.edit_triggers,
2161 on_cell_edit_request: self.on_cell_edit_request.clone(),
2162 on_cell_edit_dismissed: self.on_cell_edit_dismissed.clone(),
2163 version: self.pane_version.clone(),
2164 prev_built_start: self.pane_built_start.clone(),
2165 prev_built_end: self.pane_built_end.clone(),
2166 total_refresh: self.pane_total_refresh.clone(),
2167 row_entries: Vec::new(),
2168 cell_map: self.cell_map.clone(),
2169 };
2170 self.body_pane_id = Some(ctx.add(pane));
2171 // An open cell editor also ends on a press that lands on no cell at
2172 // all — the empty band under the last row. Mounted here rather than
2173 // on the pane because the pane is not the hit target there.
2174 if let Some(handlers) = body_pane::root_edit_dismiss_handler(
2175 &self.on_cell_edit_dismissed,
2176 &self.editing_cell,
2177 &Rc::new(
2178 display_indices
2179 .iter()
2180 .map(|&i| self.columns[i].id.clone())
2181 .collect::<Vec<_>>(),
2182 ),
2183 ) {
2184 ctx.apply_self_handlers(handlers);
2185 }
2186 }
2187
2188 // Scrollbar (single internal vertical bar).
2189 if self.show_internal_scrollbars {
2190 let sb = ScrollBar::new(
2191 ScrollBarOrientation::Vertical,
2192 self.scroll_y.clone(),
2193 self.max_scroll_y.clone(),
2194 self.viewport_ratio_y.clone(),
2195 )
2196 .visual(match self.scroll_bar_style {
2197 ScrollBarMode::Permanent => ScrollBarVisual::Permanent,
2198 ScrollBarMode::Overlay => ScrollBarVisual::Overlay,
2199 ScrollBarMode::Thin => ScrollBarVisual::Thin,
2200 });
2201 self.scrollbar_id = Some(ctx.add(sb));
2202
2203 // Horizontal bar — the Middle pane only. Visibility (max_scroll_x
2204 // > 0) and geometry (band_left + pinned-pane offsets) are decided
2205 // in `place_children`, same as the vertical bar's `needs_scrollbar`
2206 // gate; here we just build it unconditionally so it exists to be
2207 // placed (zero-sized and skipped when not needed).
2208 let hsb = ScrollBar::new(
2209 ScrollBarOrientation::Horizontal,
2210 self.scroll_x.clone(),
2211 self.max_scroll_x.clone(),
2212 self.viewport_ratio_x.clone(),
2213 )
2214 .visual(match self.scroll_bar_style {
2215 ScrollBarMode::Permanent => ScrollBarVisual::Permanent,
2216 ScrollBarMode::Overlay => ScrollBarVisual::Overlay,
2217 ScrollBarMode::Thin => ScrollBarVisual::Thin,
2218 });
2219 self.h_scrollbar_id = Some(ctx.add(hsb));
2220 }
2221
2222 // Z-order: body rows first, then empty/scrollbar, then header
2223 // last. The header band overlaps the top of the body region
2224 // when `scroll_y > 0` (rows positioned at `body_origin_y +
2225 // row_idx * row_h - scroll_y` can extend above
2226 // `body_origin_y` on overscroll). Painting the header last
2227 // means it sits on top of any row that bleeds into the
2228 // header band — without this fix, scrolled-out rows would
2229 // visibly draw over the header label.
2230 let mut children: Vec<WidgetId> = Vec::new();
2231 if let Some(id) = self.body_pane_id {
2232 children.push(id);
2233 }
2234 if let Some(id) = self.empty_id {
2235 children.push(id);
2236 }
2237 if let Some(id) = self.scrollbar_id {
2238 children.push(id);
2239 }
2240 if let Some(id) = self.h_scrollbar_id {
2241 children.push(id);
2242 }
2243 if let Some(id) = self.header_row_id {
2244 children.push(id);
2245 }
2246 // Suppress the unused-binding warning on header_h while the
2247 // value is consumed by `place_children` via the same helper.
2248 let _ = header_h;
2249 children
2250 }
2251
2252 fn layout_response(
2253 &self,
2254 proposal: SizeProposal,
2255 _ctx: &LayoutContext,
2256 ) -> teksilo_core::widget::LayoutResponse {
2257 // Only an allocation may seed the cached viewport (`common::viewport`);
2258 // the body pane shares this very cell, so a measurement's fallback
2259 // would desync its realization window.
2260 let size = crate::common::viewport::viewport_size(
2261 proposal,
2262 &self.viewport_height,
2263 Size::new(400.0, 300.0),
2264 );
2265 if proposal.height.is_some() {
2266 // Viewport-relative imperatives are meaningful from here on — but
2267 // only once a real height has landed, for the reason `laid_out`
2268 // exists at all.
2269 self.laid_out.set(true);
2270 }
2271 size.into()
2272 }
2273
2274 fn place_children(
2275 &self,
2276 bounds: Rect,
2277 _proposal: SizeProposal,
2278 children: &mut [WidgetPlacement],
2279 ctx: &LayoutContext,
2280 ) {
2281 if children.is_empty() {
2282 return;
2283 }
2284 let rtl = ctx.is_rtl();
2285 let header_h = self.effective_header_height();
2286 // Provisional — the vertical scrollbar's own need is decided
2287 // against this (a possible tiny inaccuracy if reserving room for
2288 // the horizontal bar below would itself flip that decision; not
2289 // worth a fixed-point iteration for a dual-scrollbar corner case).
2290 let body_height_provisional = (bounds.height - header_h).max(0.0);
2291
2292 // Parent-before-child layout order means this runs before the
2293 // body pane's measure pass — in auto-measure mode the scrollbar
2294 // totals settle one frame after a measurement change.
2295 let total_height = self.total_content_height();
2296 let needs_v_scrollbar =
2297 self.show_internal_scrollbars && total_height > body_height_provisional + 0.5;
2298 // Permanent reserves a column for the bar; Overlay / Thin float
2299 // over the content, so rows span the full width.
2300 let reserves_v_bar = needs_v_scrollbar && self.scroll_bar_style == ScrollBarMode::Permanent;
2301 let body_width = if reserves_v_bar {
2302 (bounds.width - SCROLLBAR_THICKNESS).max(0.0)
2303 } else {
2304 bounds.width
2305 };
2306 // Under RTL the vertical scrollbar moves to the physical left
2307 // (matching `ScrollArea`), so the body/header band shifts right
2308 // by its thickness. `band_left` is the shared origin for the
2309 // body pane, empty state, and header; `scrollbar_x` is the
2310 // scrollbar's own physical x. The paint pass derives the same
2311 // content region from these conventions so the two never drift.
2312 let band_left = if rtl && reserves_v_bar {
2313 bounds.x + SCROLLBAR_THICKNESS
2314 } else {
2315 bounds.x
2316 };
2317 let scrollbar_x = if rtl {
2318 bounds.x
2319 } else {
2320 bounds.x + bounds.width - SCROLLBAR_THICKNESS
2321 };
2322 // The header strip spans the band; snapshot its width for the
2323 // reorder-drop handler's RTL mirror.
2324 self.header_strip_width.set(body_width);
2325
2326 // Resolve column widths in display order, honoring any
2327 // user-resize overrides from `column_widths_signal`.
2328 let overrides = self.column_widths_signal.get();
2329 let display = self.display_indices.borrow().clone();
2330 let widths = layout::ColumnSolver::resolve_in_order(
2331 &self.columns,
2332 &display,
2333 body_width,
2334 cp::MIN_COLUMN_WIDTH_DEFAULT,
2335 &overrides,
2336 );
2337
2338 // Pane geometry: the Middle pane's viewport (`body_width` minus the
2339 // pinned panes) and the horizontal scroll headroom it implies.
2340 let boundaries = *self.pane_boundaries.borrow();
2341 let (leading_w, middle_content_w, trailing_w) = layout::pane_widths(&widths, boundaries);
2342 let middle_viewport_w = (body_width - leading_w - trailing_w).max(0.0);
2343 let max_x = (middle_content_w - middle_viewport_w).max(0.0);
2344 self.max_scroll_x.set(max_x);
2345 self.middle_viewport_width.set(middle_viewport_w);
2346 let x_ratio = if middle_content_w > 0.0 {
2347 (middle_viewport_w / middle_content_w).clamp(0.0, 1.0)
2348 } else {
2349 1.0
2350 };
2351 self.viewport_ratio_x.set(x_ratio);
2352 // Clamp scroll_x — a pane shrink (window narrowed, a column grew)
2353 // must not leave scroll_x stranded past the new max (mirrors
2354 // `clamp_scroll` for scroll_y).
2355 {
2356 let current = self.scroll_x.get();
2357 let clamped = current.clamp(0.0, max_x);
2358 if (clamped - current).abs() > 0.001 {
2359 self.scroll_x.set(clamped);
2360 }
2361 }
2362
2363 *self.column_widths.borrow_mut() = widths;
2364
2365 let needs_h_scrollbar = self.show_internal_scrollbars && max_x > 0.5;
2366 let reserves_h_bar = needs_h_scrollbar && self.scroll_bar_style == ScrollBarMode::Permanent;
2367 let body_height = if reserves_h_bar {
2368 (body_height_provisional - SCROLLBAR_THICKNESS).max(0.0)
2369 } else {
2370 body_height_provisional
2371 };
2372
2373 // Vertical scrollbar totals, against the FINAL body_height (after
2374 // any horizontal-bar reservation) so the range stays accurate when
2375 // both bars show at once.
2376 let max_y = (total_height - body_height).max(0.0);
2377 self.max_scroll_y.set(max_y);
2378 let y_ratio = if total_height > 0.0 {
2379 (body_height / total_height).clamp(0.0, 1.0)
2380 } else {
2381 1.0
2382 };
2383 self.viewport_ratio_y.set(y_ratio);
2384 self.clamp_scroll();
2385
2386 let body_origin_y = bounds.y + header_h;
2387 // Cache the row-area rect for the keyboard handler's outer-scroll chase.
2388 self.body_bounds
2389 .set(Rect::new(band_left, body_origin_y, body_width, body_height));
2390
2391 let mut next = 0;
2392
2393 // BodyPane fills the body region. It positions its rows
2394 // internally using its own scroll signal and clips them to
2395 // its own bounds.
2396 if self.body_pane_id.is_some() {
2397 if let Some(child) = children.get_mut(next) {
2398 child.origin = Point::new(band_left, body_origin_y);
2399 child.size = Size::new(body_width, body_height);
2400 }
2401 next += 1;
2402 }
2403
2404 // Empty-state child fills the body region (below the header).
2405 if self.empty_id.is_some() {
2406 if let Some(child) = children.get_mut(next) {
2407 child.origin = Point::new(band_left, body_origin_y);
2408 child.size = Size::new(body_width, body_height);
2409 }
2410 next += 1;
2411 }
2412
2413 // Scrollbar — alongside the body, below the header. Physical
2414 // left under RTL, physical right under LTR.
2415 if self.scrollbar_id.is_some() {
2416 if let Some(child) = children.get_mut(next) {
2417 if needs_v_scrollbar {
2418 child.origin = Point::new(scrollbar_x, body_origin_y);
2419 child.size = Size::new(SCROLLBAR_THICKNESS, body_height);
2420 } else {
2421 child.origin = bounds.origin();
2422 child.size = Size::ZERO;
2423 }
2424 }
2425 next += 1;
2426 }
2427
2428 // Horizontal scrollbar — the Middle pane's own band, below the
2429 // body, never overlapping a pinned pane.
2430 if self.h_scrollbar_id.is_some() {
2431 if let Some(child) = children.get_mut(next) {
2432 if needs_h_scrollbar {
2433 let h_x = if rtl {
2434 band_left + trailing_w
2435 } else {
2436 band_left + leading_w
2437 };
2438 child.origin = Point::new(h_x, body_origin_y + body_height);
2439 child.size = Size::new(middle_viewport_w, SCROLLBAR_THICKNESS);
2440 } else {
2441 child.origin = bounds.origin();
2442 child.size = Size::ZERO;
2443 }
2444 }
2445 next += 1;
2446 }
2447
2448 // Header strip last — placed at top y but emitted last so paint
2449 // z-order draws it above any overscrolled body rows.
2450 if self.header_row_id.is_some()
2451 && let Some(child) = children.get_mut(next)
2452 {
2453 child.origin = Point::new(band_left, bounds.y);
2454 child.size = Size::new(body_width, header_h);
2455 }
2456 }
2457
2458 fn paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
2459 let header_h = self.effective_header_height();
2460 let colors = &ctx.theme.colors;
2461
2462 let scroll_y = self.scroll_y.get();
2463 let body_origin_y = bounds.y + header_h;
2464 let body_height = (bounds.height - header_h).max(0.0);
2465 let widths = self.column_widths.borrow();
2466 let body_width = widths.iter().sum::<f32>();
2467 let body_width_for_paint = if body_width > 0.0 {
2468 body_width.min(bounds.width)
2469 } else {
2470 bounds.width
2471 };
2472 // Physical left edge of the column content. Under RTL the band is
2473 // right-aligned within `bounds` (the scrollbar took the left), so
2474 // content runs from `bounds.right() - body_width` leftward —
2475 // exactly where `place_children` reverse-placed the cells.
2476 let rtl = ctx.layout_direction == teksilo_core::environment::LayoutDirection::RightToLeft;
2477 let content_left = if rtl {
2478 bounds.x + bounds.width - body_width_for_paint
2479 } else {
2480 bounds.x
2481 };
2482
2483 // Visible row window for the paint passes — offset-table-driven
2484 // so variable heights paint correctly. One metrics borrow per
2485 // pass; nothing inside re-enters the metrics.
2486 let row_count = (self.len_fn)();
2487 let (first_visible, last_visible) =
2488 self.row_metrics
2489 .borrow_mut()
2490 .visible_range(scroll_y, body_height, row_count, 0);
2491
2492 // Clip the root-painted row decorations (alt-row stripes,
2493 // selection bands, grid lines, focus ring) to the body band.
2494 // `clips_children` only clips child WIDGETS — this widget's own
2495 // paint would otherwise bleed past the table's bottom edge for
2496 // the partially visible last row (its stripe/grid-line rect
2497 // spans the full row height).
2498 canvas.set_clip(Rect::new(
2499 content_left,
2500 body_origin_y,
2501 body_width_for_paint,
2502 body_height,
2503 ));
2504
2505 // Alt-row backgrounds — paint odd visible rows. Parity keys on
2506 // the row index, not on y, so stripes stay stable under
2507 // variable heights.
2508 if self.alternating_rows {
2509 let mut m = self.row_metrics.borrow_mut();
2510 for row_idx in first_visible..last_visible {
2511 if row_idx % 2 == 1 {
2512 let y = body_origin_y + m.row_top(row_idx) - scroll_y;
2513 let h = m.row_height(row_idx);
2514 let rect = Rect::new(content_left, y, body_width_for_paint, h);
2515 canvas.fill_rect(rect, SurfaceRole::AltRow.resolve(colors));
2516 }
2517 }
2518 }
2519
2520 // Selection highlights — row selection modes only.
2521 if let Some(ref sel) = self.row_selection
2522 && matches!(
2523 self.selection_mode,
2524 TableSelectionMode::SingleRow | TableSelectionMode::MultiRow
2525 )
2526 {
2527 // Focus- and window-aware: vivid `Selected` while the table holds
2528 // keyboard focus AND the host window is active; muted
2529 // `SelectedInactive` once focus moves elsewhere or the window goes
2530 // inactive (the same desaturation serves both states).
2531 let bg = if self.view_focused.get() && ctx.window_active {
2532 SurfaceRole::Selected.resolve(colors)
2533 } else {
2534 SurfaceRole::SelectedInactive.resolve(colors)
2535 };
2536 let mut m = self.row_metrics.borrow_mut();
2537 for row_idx in sel.selected_indices() {
2538 let y = body_origin_y + m.row_top(row_idx) - scroll_y;
2539 let h = m.row_height(row_idx);
2540 if y + h < body_origin_y || y > body_origin_y + body_height {
2541 continue;
2542 }
2543 let rect = Rect::new(content_left, y, body_width_for_paint, h);
2544 canvas.fill_rect(rect, bg);
2545 }
2546 }
2547
2548 // Grid lines.
2549 let line_color = BorderRole::Divider.resolve(colors);
2550 let line_w = cp::GRID_LINE_THICKNESS.max(1.0);
2551
2552 if matches!(self.grid_lines, GridLines::Horizontal | GridLines::Both) {
2553 let mut m = self.row_metrics.borrow_mut();
2554 for row_idx in first_visible..last_visible {
2555 let bottom = m.row_top(row_idx) + m.row_height(row_idx);
2556 let y = body_origin_y + bottom - scroll_y - line_w;
2557 let rect = Rect::new(content_left, y, body_width_for_paint, line_w);
2558 canvas.fill_rect(rect, line_color);
2559 }
2560 }
2561
2562 // Pane geometry for the two column-position-dependent decorations
2563 // below (vertical grid lines, the cell focus ring): both must clip
2564 // to the target column's OWN pane, or a scrolled Middle-pane
2565 // decoration could paint over a pinned Leading/Trailing column
2566 // within the same row band (the outer body clip above only bounds
2567 // the row's outer edges, not the seam between panes).
2568 let boundaries = *self.pane_boundaries.borrow();
2569 let scroll_x = self.scroll_x.get();
2570 let content_bounds = Rect::new(
2571 content_left,
2572 body_origin_y,
2573 body_width_for_paint,
2574 body_height,
2575 );
2576 let (leading_rect, middle_rect, trailing_rect) =
2577 layout::band_rects(content_bounds, &widths, boundaries, rtl);
2578
2579 if matches!(self.grid_lines, GridLines::Vertical | GridLines::Both) {
2580 let leading_end = boundaries.leading_count.min(widths.len());
2581 let middle_end = boundaries.middle_end.min(widths.len()).max(leading_end);
2582 draw_pane_dividers(
2583 canvas,
2584 leading_rect,
2585 &widths[..leading_end],
2586 0.0,
2587 rtl,
2588 line_color,
2589 line_w,
2590 );
2591 draw_pane_dividers(
2592 canvas,
2593 middle_rect,
2594 &widths[leading_end..middle_end],
2595 scroll_x,
2596 rtl,
2597 line_color,
2598 line_w,
2599 );
2600 draw_pane_dividers(
2601 canvas,
2602 trailing_rect,
2603 &widths[middle_end..],
2604 0.0,
2605 rtl,
2606 line_color,
2607 line_w,
2608 );
2609 }
2610
2611 // Focus ring on the currently-focused cell — keyboard-only
2612 // (`:focus-visible`) and only while the table itself holds focus, so a
2613 // mouse click never leaves a ring and an unfocused table shows none.
2614 if self.view_focused.get()
2615 && self.focus_visible.get()
2616 && let Some((focus_row, focus_col)) = self.focused_cell.get()
2617 && focus_col < widths.len()
2618 && let Some(x_off) = layout::column_logical_x(
2619 &widths,
2620 boundaries,
2621 scroll_x,
2622 body_width_for_paint,
2623 focus_col,
2624 )
2625 {
2626 let cell_w = widths[focus_col];
2627 let (focus_top, focus_h) = {
2628 let mut m = self.row_metrics.borrow_mut();
2629 (m.row_top(focus_row), m.row_height(focus_row))
2630 };
2631 let y = body_origin_y + focus_top - scroll_y;
2632 if y + focus_h >= body_origin_y && y <= body_origin_y + body_height {
2633 let pane_rect = if focus_col < boundaries.leading_count {
2634 leading_rect
2635 } else if focus_col >= boundaries.middle_end {
2636 trailing_rect
2637 } else {
2638 middle_rect
2639 };
2640 canvas.set_clip(pane_rect);
2641 let inset = cp::FOCUS_RING_INSET;
2642 let stroke = cp::GRID_LINE_THICKNESS.max(1.5);
2643 let ring_color = BorderRole::Focused.resolve(colors);
2644 // `x_off` is the leading-side offset (sum of widths before
2645 // the focused column). Under RTL that offset is measured
2646 // from the right edge of the content band.
2647 let rx = if rtl {
2648 content_left + body_width_for_paint - x_off - cell_w + inset
2649 } else {
2650 content_left + x_off + inset
2651 };
2652 let ry = y + inset;
2653 let rw = (cell_w - inset * 2.0).max(0.0);
2654 let rh = (focus_h - inset * 2.0).max(0.0);
2655 // Top
2656 canvas.fill_rect(Rect::new(rx, ry, rw, stroke), ring_color);
2657 // Bottom
2658 canvas.fill_rect(Rect::new(rx, ry + rh - stroke, rw, stroke), ring_color);
2659 // Left
2660 canvas.fill_rect(Rect::new(rx, ry, stroke, rh), ring_color);
2661 // Right
2662 canvas.fill_rect(Rect::new(rx + rw - stroke, ry, stroke, rh), ring_color);
2663 canvas.clear_clip();
2664 }
2665 }
2666
2667 // Row-drop insertion indicator (source-accepted positions only —
2668 // a forbidden hover clears the signal, so no line shows). `y` is
2669 // stored body-local; the band clip is already active.
2670 if let Some((y, _width)) = self.drop_feedback.get() {
2671 let line_color = BorderRole::Focused.resolve(colors);
2672 let thickness = 2.0_f32;
2673 let line_y = body_origin_y + y - thickness * 0.5;
2674 canvas.fill_rect(
2675 Rect::new(content_left, line_y, body_width_for_paint, thickness),
2676 line_color,
2677 );
2678 }
2679
2680 canvas.clear_clip();
2681
2682 // Container focus ring — the table holds keyboard focus but nothing
2683 // indicates where: no current cell (no cell ring) and no selection (no
2684 // band). Outline the whole view so Tab has a visible landing point
2685 // before the user navigates (mirrors TreeView / ListView).
2686 let nothing_indicated = self.focused_cell.get().is_none()
2687 && self
2688 .row_selection
2689 .as_ref()
2690 .is_none_or(|s| s.selected_indices().is_empty())
2691 && self.cell_selection.as_ref().is_none_or(|s| s.count() == 0);
2692 if self.view_focused.get() && self.focus_visible.get() && nothing_indicated {
2693 let inset = 1.0_f32;
2694 let rect = Rect::new(
2695 bounds.x + inset,
2696 bounds.y + inset,
2697 (bounds.width - inset * 2.0).max(0.0),
2698 (bounds.height - inset * 2.0).max(0.0),
2699 );
2700 canvas.stroke_rect(rect, BorderRole::Focused.resolve(colors), 1.5);
2701 }
2702
2703 // `OnRelease` column-resize guide. Under that policy no column moves
2704 // until the button comes up, so this line is the *only* feedback the
2705 // gesture has — the same full-height rubber band Qt / Excel draw.
2706 if let Some(x) = self.resize_preview_x.get() {
2707 let thickness = cp::GRID_LINE_THICKNESS.max(1.5);
2708 canvas.fill_rect(
2709 Rect::new(x - thickness * 0.5, bounds.y, thickness, bounds.height),
2710 BorderRole::Focused.resolve(colors),
2711 );
2712 }
2713 }
2714
2715 fn accessibility(&self, builder: &mut AccessNodeBuilder) {
2716 builder.set_role(teksilo_core::accesskit::Role::Table);
2717 if let Some(ref label) = self.a11y_label {
2718 builder.set_name(label.resolve_now());
2719 }
2720 // AccessKit's `row_count` includes the header row when present —
2721 // matches ARIA `aria-rowcount` semantics.
2722 let row_count = (self.len_fn)() + if self.show_header { 1 } else { 0 };
2723 let col_count = self.columns.len();
2724 let n = builder.inner_mut();
2725 n.set_row_count(row_count);
2726 n.set_column_count(col_count);
2727
2728 // Roving focus: point active_descendant at the focused cell's own
2729 // AT node so a screen reader follows arrow-key cell navigation
2730 // (only the table root is otherwise focusable — the ring is
2731 // visual-only). `cell_map` is a snapshot of the body pane's last
2732 // realized cells; a focused cell that scrolled out of the
2733 // realized buffer simply isn't in it, so no stale id is emitted.
2734 if let Some(target) = self.focused_cell.get() {
2735 let map = self.cell_map.borrow();
2736 if let Some(&(_, cell_id)) = map.iter().find(|&&(pos, _)| pos == target) {
2737 builder.set_active_descendant(widget_id_to_node_id(cell_id));
2738 }
2739 }
2740 }
2741
2742 fn as_any(&self) -> Option<&dyn std::any::Any> {
2743 Some(self)
2744 }
2745
2746 fn children(&self) -> Vec<WidgetId> {
2747 // Same order as `build()` — body pane first, header last so
2748 // it paints on top of any overscrolled rows.
2749 let mut out: Vec<WidgetId> = Vec::new();
2750 if let Some(id) = self.body_pane_id {
2751 out.push(id);
2752 }
2753 if let Some(id) = self.empty_id {
2754 out.push(id);
2755 }
2756 if let Some(id) = self.scrollbar_id {
2757 out.push(id);
2758 }
2759 if let Some(id) = self.h_scrollbar_id {
2760 out.push(id);
2761 }
2762 if let Some(id) = self.header_row_id {
2763 out.push(id);
2764 }
2765 out
2766 }
2767
2768 fn accessibility_children(&self) -> Option<Vec<WidgetId>> {
2769 // WCAG 1.3.2 (audit G17): read the column-header row FIRST, then the
2770 // body, even though `build()` / `children()` list the body first so it
2771 // paints beneath the header. Same id set as `children()`, reordered.
2772 let out: Vec<WidgetId> = [
2773 self.header_row_id,
2774 self.body_pane_id,
2775 self.empty_id,
2776 self.scrollbar_id,
2777 self.h_scrollbar_id,
2778 ]
2779 .into_iter()
2780 .flatten()
2781 .collect();
2782 if out.is_empty() { None } else { Some(out) }
2783 }
2784
2785 fn clips_children(&self) -> bool {
2786 true
2787 }
2788}
2789
2790/// Draw the internal vertical grid-line dividers for one pane band —
2791/// `slice.len() - 1` lines between adjacent columns, clipped to `rect` so a
2792/// scrolled Middle-pane line can't bleed past its own viewport into a
2793/// pinned neighbour. `scroll` is nonzero only for the Middle pane.
2794///
2795/// Shared by `TableView`/`TreeTableView`'s `paint()`, which are otherwise
2796/// near-identical for this decoration.
2797#[allow(clippy::too_many_arguments)]
2798pub(crate) fn draw_pane_dividers(
2799 canvas: &mut Canvas,
2800 rect: Rect,
2801 slice: &[f32],
2802 scroll: f32,
2803 rtl: bool,
2804 color: teksilo_tokens::Color,
2805 line_w: f32,
2806) {
2807 if slice.len() < 2 || rect.width <= 0.0 {
2808 return;
2809 }
2810 canvas.set_clip(rect);
2811 if rtl {
2812 let mut x = rect.right() + scroll;
2813 for &w in &slice[..slice.len() - 1] {
2814 x -= w;
2815 canvas.fill_rect(Rect::new(x, rect.y, line_w, rect.height), color);
2816 }
2817 } else {
2818 let mut x = rect.x - scroll;
2819 for &w in &slice[..slice.len() - 1] {
2820 x += w;
2821 canvas.fill_rect(Rect::new(x - line_w, rect.y, line_w, rect.height), color);
2822 }
2823 }
2824 canvas.clear_clip();
2825}
2826
2827// Reorder drag-target plumbing (hover + drop on the header strip) lives in
2828// `header::attach_header_reorder_handlers` — shared with `TreeTableView`,
2829// which builds its header out of the same `HeaderCell`/`HeaderRow` pair.