Skip to main content

teksilo_widgets/
data_views.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! Shared substrate for the data views' source-owned drag-and-drop + lazy
5//! loading.
6//!
7//! Centralizes the vocabulary the four data views (`ListView` / `TreeView` /
8//! `TableView` / `TreeTableView`) share, so DnD validation (`can_accept`) and
9//! the lazy placeholder are wired one way everywhere:
10//!
11//! - [`RowDragData`] — the **public, generic** intra-app drag payload a row (or
12//!   a whole selected set) emits. The receiving source distinguishes its OWN
13//!   reorder (matching [`ViewId`]) from a foreign drop, and translates the
14//!   origin's `rows` → its own key via `key_at`, so the source's `Key` type
15//!   never leaks into the view. When the origin opted into export it also
16//!   carries `items` (clones of the dragged `T`), so a foreign `DropTarget`,
17//!   a different data view, or the OS can consume the drag.
18//! - [`DropIndicator`] — what `paint` renders; `allowed == false` is the
19//!   pre-commit forbidden affordance.
20//! - [`flat_insertion_target`] — maps a flat insertion index to the
21//!   `(target, position)` pair `can_accept` / `accept_drop` expect.
22//! - [`default_placeholder`] — the skeleton for a `Loading` row.
23
24use std::cell::{Cell, RefCell};
25use std::rc::Rc;
26use std::sync::atomic::{AtomicUsize, Ordering};
27
28use teksilo_core::ObserverHandle;
29use teksilo_core::drag_payload::{DragPayload, DropOutcome};
30use teksilo_core::widget::{EventContext, Widget};
31use teksilo_core::widget_builder::HandlerSet;
32use teksilo_data::{
33    DataChange, DropPosition, ItemKey, KeyedSelectionModel, SelectionMode, SelectionModel,
34};
35
36/// How a data-view row/tile is *activated* (opened/committed) by pointer —
37/// distinct from *selection*, which also moves on arrow-key navigation. Mirrors
38/// the platform split other toolkits expose (Qt
39/// `SH_ItemView_ActivateItemOnSingleClick`, GTK `activate-on-single-click`).
40/// Enter/Space always activates regardless of this mode.
41///
42/// Pass to `ListView::activate_on`, `TreeView::activate_on`, etc.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
44pub enum ActivateOn {
45    /// One primary click activates the row (KDE / web / Scrivener convention).
46    /// Selection and activation happen on the same click.
47    SingleClick,
48    /// A double primary click activates the row; the first click only selects
49    /// it (Finder / Explorer / Qt and GTK default). This is the [`Default`].
50    #[default]
51    DoubleClick,
52}
53
54/// Which kind of data view minted a [`ViewId`]. Folded into the id so two
55/// different widget kinds that happen to draw the same value from the shared
56/// process counter can never be mistaken for one another — the reason a bare
57/// `usize` id was a latent cross-widget hazard.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
59pub(crate) enum ViewKind {
60    List,
61    Tree,
62    Table,
63    TreeTable,
64    Grid,
65}
66
67/// Opaque, kind-tagged, process-unique identity of a drag-capable data-view
68/// instance. Used to tell a view's OWN reorder (`SameView`) from a foreign drop
69/// on the receive side. Apps only ever compare two `ViewId`s for equality (e.g.
70/// out of a received [`RowDragData`]); there is no public constructor, and the
71/// value is stable for a view instance's lifetime, so it is safe to compare
72/// even across windows (each mint is globally unique).
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74pub struct ViewId(ViewKind, usize);
75
76impl ViewId {
77    /// Mint a fresh, globally-unique id for a view of the given kind.
78    pub(crate) fn next(kind: ViewKind) -> Self {
79        Self(kind, next_view_id())
80    }
81}
82
83/// What the *origin* view does to its own rows once a drag is accepted by a
84/// **foreign** target (a different `DropTarget` / view / the OS). Purely an
85/// origin-side cleanup choice — the receiver is unaffected. A same-view reorder
86/// is never a transfer, so this never applies to it.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
88pub enum DragTransferMode {
89    /// Leave the origin rows in place (the dragged data is duplicated).
90    Copy,
91    /// Remove the dragged rows from the origin once accepted elsewhere
92    /// (or exported as an OS move). This is the [`Default`].
93    #[default]
94    Move,
95}
96
97/// The public, generic drag payload every data-view row (or selected set)
98/// emits. It occupies the single typed slot of a
99/// [`teksilo_core::drag_payload::DragPayload`] and serves both audiences:
100///
101/// - the origin view's own erased classifier reads [`source`](Self::source) +
102///   [`rows`](Self::rows) to recognise a same-view reorder;
103/// - a **foreign** consumer (another view's custom `ListDataSource`, a
104///   `DropTarget::accept_typed::<RowDragData<T>>()`, or `on_rows_received`)
105///   reads [`items`](Self::items).
106///
107/// `items` is `Some` only when the origin view opted into export via
108/// `.exportable(..)` (which requires `T: Clone`); a plain `.reorderable(true)`
109/// drag carries `items == None` (nothing outside the origin could use it
110/// anyway), so a reorder-only view is never accidentally droppable elsewhere.
111#[derive(Debug)]
112pub struct RowDragData<T: 'static> {
113    /// Identity of the view that started the drag.
114    pub source: ViewId,
115    /// The dragged rows as the origin view's flat visible indices at
116    /// drag-start, ascending. Informational (row count, app callbacks): the
117    /// origin's accept path resolves the dragged rows' **stable keys** at
118    /// drag-start and never re-reads these indices at hover/drop time — they
119    /// go stale the moment the source reflows mid-drag (a spring-load
120    /// auto-expand, a peer write). A foreign consumer should read
121    /// [`items`](Self::items) instead.
122    pub rows: Vec<usize>,
123    /// Clones of the dragged items, `rows`-ordered. `None` for a reorder-only
124    /// (non-exportable) drag.
125    pub items: Option<Vec<T>>,
126}
127
128impl<T: 'static> RowDragData<T> {
129    /// The dragged items, if this is an export drag (`.exportable(..)` was set
130    /// on the origin). `None` for a reorder-only drag.
131    pub fn items(&self) -> Option<&[T]> {
132        self.items.as_deref()
133    }
134
135    /// Consume the payload for its items (avoids cloning on the receive side).
136    pub fn into_items(self) -> Option<Vec<T>> {
137        self.items
138    }
139
140    /// Whether this drag carries exportable items — i.e. the origin opted into
141    /// `.exportable(..)`. A foreign receiver should gate on this (a reorder-only
142    /// payload has the same Rust type but carries nothing usable).
143    pub fn is_export(&self) -> bool {
144        self.items.is_some()
145    }
146
147    /// Number of dragged rows.
148    pub fn len(&self) -> usize {
149        self.rows.len()
150    }
151
152    /// Whether no rows are carried (never true for a real drag).
153    pub fn is_empty(&self) -> bool {
154        self.rows.is_empty()
155    }
156}
157
158/// A drop indicator the data views' `paint` renders. `allowed == false` paints a
159/// muted line where an accepted-drop line would be — the pre-commit "you can't
160/// drop here" affordance.
161#[derive(Debug, Clone, Copy, PartialEq)]
162pub(crate) struct DropIndicator {
163    pub(crate) y: f32,
164    pub(crate) width: f32,
165    pub(crate) allowed: bool,
166}
167
168/// A process-unique id distinguishing data-view instances (for SameView drop
169/// detection when several views share one source).
170pub(crate) fn next_view_id() -> usize {
171    static NEXT: AtomicUsize = AtomicUsize::new(1);
172    NEXT.fetch_add(1, Ordering::Relaxed)
173}
174
175/// Map a flat insertion index (`0..=len`) to the `(target_index, position)` pair
176/// a `ListDataSource::can_accept` / `accept_drop` understands. `None` for an
177/// empty list. Insertion *before* row `i` is `(i, Before)`; insertion past the
178/// end is `(len-1, After)`.
179pub(crate) fn flat_insertion_target(insertion: usize, len: usize) -> Option<(usize, DropPosition)> {
180    if len == 0 {
181        None
182    } else if insertion >= len {
183        Some((len - 1, DropPosition::After))
184    } else {
185        Some((insertion, DropPosition::Before))
186    }
187}
188
189/// The default skeleton for a `Loading` row — a muted inset bar. The row's
190/// placement sizes it to the row's height and width.
191/// One row's tooltip, already resolved from its item and awaiting a
192/// `BuildContext` to attach it with.
193pub(crate) enum ResolvedRowTooltip {
194    Plain(teksilo_i18n::LocalizedString),
195    Rich(crate::tooltip::RichTooltipSource),
196    Composite(Box<dyn Widget>),
197}
198
199/// Per-row tooltip resolvers, shared by every data view that builds rows from
200/// a delegate.
201///
202/// A data view's rows are not authored by the app as widgets it can hang a
203/// `.tooltip(...)` on — they come out of a delegate, and the view owns the
204/// resulting `WidgetId`. So the view takes the *resolvers* instead and does the
205/// attaching itself, against the row it just built. Same shape as
206/// [`TabDelegate`](crate::tab_widget::TabDelegate)'s per-tab tooltip callbacks,
207/// and the same last-setter-wins matrix as the per-widget setters: each `set_*`
208/// clears the other two, so a row can never mature two tips at once.
209///
210/// Placement is [`Side`](crate::tooltip::TooltipPlacement::Side) for every
211/// view here — rows stack vertically, and a `Below` tip would cover the next
212/// row, which is the one the user is most likely reading next.
213///
214/// Cost: the body is resolved and built for each **realized** row, i.e. the
215/// virtualization window (visible + buffer), not the whole model — and again
216/// whenever those rows rebuild. Keep resolvers cheap; defer anything expensive
217/// (a backend read, a subtree walk) to the body's own first paint, which only
218/// happens if the tip is actually shown.
219pub(crate) struct RowTooltips<T: 'static> {
220    plain: Option<Rc<dyn Fn(usize, &T) -> Option<teksilo_i18n::LocalizedString>>>,
221    rich: Option<Rc<dyn Fn(usize, &T) -> Option<crate::tooltip::RichTooltipSource>>>,
222    composite: Option<Rc<dyn Fn(usize, &T) -> Option<Box<dyn Widget>>>>,
223    /// Whether a composite row tip offers dwell-to-sticky promotion.
224    composite_sticky: bool,
225}
226
227impl<T: 'static> Default for RowTooltips<T> {
228    fn default() -> Self {
229        Self {
230            plain: None,
231            rich: None,
232            composite: None,
233            composite_sticky: true,
234        }
235    }
236}
237
238impl<T: 'static> Clone for RowTooltips<T> {
239    fn clone(&self) -> Self {
240        Self {
241            plain: self.plain.clone(),
242            rich: self.rich.clone(),
243            composite: self.composite.clone(),
244            composite_sticky: self.composite_sticky,
245        }
246    }
247}
248
249impl<T: 'static> std::fmt::Debug for RowTooltips<T> {
250    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
251        f.debug_struct("RowTooltips")
252            .field("plain", &self.plain.is_some())
253            .field("rich", &self.rich.is_some())
254            .field("composite", &self.composite.is_some())
255            .finish()
256    }
257}
258
259impl<T: 'static> RowTooltips<T> {
260    /// Whether any resolver is set — lets a view skip the per-row work.
261    pub(crate) fn is_set(&self) -> bool {
262        self.plain.is_some() || self.rich.is_some() || self.composite.is_some()
263    }
264
265    pub(crate) fn set_plain(
266        &mut self,
267        f: impl Fn(usize, &T) -> Option<teksilo_i18n::LocalizedString> + 'static,
268    ) {
269        *self = Self {
270            plain: Some(Rc::new(f)),
271            rich: None,
272            composite: None,
273            composite_sticky: self.composite_sticky,
274        };
275    }
276
277    pub(crate) fn set_rich(
278        &mut self,
279        f: impl Fn(usize, &T) -> Option<crate::tooltip::RichTooltipSource> + 'static,
280    ) {
281        *self = Self {
282            plain: None,
283            rich: Some(Rc::new(f)),
284            composite: None,
285            composite_sticky: self.composite_sticky,
286        };
287    }
288
289    pub(crate) fn set_composite(
290        &mut self,
291        f: impl Fn(usize, &T) -> Option<Box<dyn Widget>> + 'static,
292    ) {
293        *self = Self {
294            plain: None,
295            rich: None,
296            composite: Some(Rc::new(f)),
297            composite_sticky: self.composite_sticky,
298        };
299    }
300
301    /// Whether a composite row tip offers dwell promotion. Off suits a
302    /// read-only card: nothing to reach into, so nothing to pin.
303    pub(crate) fn set_composite_sticky(&mut self, on: bool) {
304        self.composite_sticky = on;
305    }
306
307    /// Resolve this row's tooltip, if any.
308    ///
309    /// Split from [`attach_resolved`](Self::attach_resolved) because a view can
310    /// only reach the item from inside the same borrow that builds the row
311    /// widget, while attaching needs the `BuildContext` and the resulting
312    /// `WidgetId` — which only exist after that borrow ends.
313    pub(crate) fn resolve(&self, index: usize, item: &T) -> Option<ResolvedRowTooltip> {
314        if let Some(f) = &self.composite {
315            f(index, item).map(ResolvedRowTooltip::Composite)
316        } else if let Some(f) = &self.rich {
317            f(index, item).map(ResolvedRowTooltip::Rich)
318        } else if let Some(f) = &self.plain {
319            f(index, item).map(ResolvedRowTooltip::Plain)
320        } else {
321            None
322        }
323    }
324
325    /// Attach a resolved tooltip to the row widget the view just built.
326    pub(crate) fn attach_resolved(
327        &self,
328        ctx: &mut teksilo_core::build_context::BuildContext,
329        row_id: teksilo_core::widget_id::WidgetId,
330        resolved: ResolvedRowTooltip,
331    ) {
332        // Rows stack vertically, so a `Below` tip would cover the next row —
333        // the one the user is most likely reading next.
334        let placement = crate::tooltip::TooltipPlacement::Side;
335        match resolved {
336            ResolvedRowTooltip::Composite(body) => {
337                let delay = ctx.theme().motion.tooltip_delay_heavy;
338                crate::tooltip::attach_composite_tooltip_widget_with_placement(
339                    ctx,
340                    row_id,
341                    crate::tooltip::CompositeTooltipWidget::new()
342                        .content_boxed(body)
343                        .sticky(self.composite_sticky),
344                    delay,
345                    placement,
346                );
347            }
348            ResolvedRowTooltip::Rich(source) => {
349                let delay = ctx.theme().motion.tooltip_delay;
350                crate::tooltip::attach_rich_tooltip_source_with_placement(
351                    ctx, row_id, source, delay, placement,
352                );
353            }
354            ResolvedRowTooltip::Plain(text) => {
355                let delay = ctx.theme().motion.tooltip_delay;
356                crate::tooltip::attach_plain_tooltip_with_placement(
357                    ctx, row_id, text, delay, placement,
358                );
359            }
360        }
361    }
362}
363
364pub(crate) fn default_placeholder() -> Box<dyn Widget> {
365    use crate::primitives::{Padding, RectWidget};
366    Box::new(
367        Padding::uniform(6.0).child(
368            RectWidget::new()
369                .background(teksilo_tokens::SurfaceRole::Hover)
370                .corner_radius(teksilo_tokens::CornerRadius::uniform(4.0)),
371        ),
372    )
373}
374
375/// Index-facing row-selection facade backing the four data views.
376///
377/// An app installs *either* the index-based [`SelectionModel`] (positions) or a
378/// [`KeyedSelectionModel<K>`] (stable identities that survive reorder / filter /
379/// window-slide / multi-view). The views' click / keyboard / rebuild / paint
380/// paths all work in **indices**, so this facade erases the difference: the
381/// keyed variant carries the view's index↔key mapping (`key_at` / `len` /
382/// `contains_key`) and translates internally. The method surface deliberately
383/// mirrors `SelectionModel` so call sites read identically (`rs.select(i)`,
384/// `rs.is_selected(i)`, …).
385#[derive(Clone)]
386pub(crate) struct RowSelection {
387    mode: SelectionMode,
388    is_selected: Rc<dyn Fn(usize) -> bool>,
389    select_fn: Rc<dyn Fn(usize)>,
390    toggle_fn: Rc<dyn Fn(usize)>,
391    extend_fn: Rc<dyn Fn(usize)>,
392    select_all_fn: Rc<dyn Fn(usize)>,
393    selected_indices_fn: Rc<dyn Fn() -> Vec<usize>>,
394    /// Cheap (O(selected count), never O(visible)) emptiness check for the
395    /// container-focus-ring gate — paint runs every frame and only needs to
396    /// know "is anything selected", not the set itself.
397    has_selection_fn: Rc<dyn Fn() -> bool>,
398    clear_fn: Rc<dyn Fn()>,
399    observe_fn: Rc<dyn Fn(Box<dyn Fn()>) -> ObserverHandle>,
400    on_change_fn: Rc<dyn Fn(&DataChange)>,
401    /// Unconditional prune for the version-signal-driven tree views (which
402    /// don't emit a `DataChange`): drop orphaned keys (keyed) or no-op (index).
403    prune_fn: Rc<dyn Fn()>,
404    /// Drop selected indices that no longer fit `0..count`, for the
405    /// version-signal-driven tree views' index-selection path: an index has
406    /// no identity to follow a moved row by (that's `focused_index`'s job,
407    /// via `RowAnchor`), so a structural change can only clamp it — never
408    /// re-land it on the row it used to point at. A no-op for the keyed
409    /// model, which is already fully reconciled by `prune_fn`.
410    prune_range_fn: Rc<dyn Fn(usize)>,
411}
412
413impl RowSelection {
414    /// Back the facade with the index-based [`SelectionModel`]. Index ops pass
415    /// straight through; `on_data_change` index-shifts (insert / remove) or
416    /// clears (reset) the selection, matching the legacy inline behaviour.
417    pub(crate) fn from_index(sel: SelectionModel) -> Self {
418        let (s_is, s_sel, s_tog, s_ext, s_all, s_idx, s_has, s_clr, s_obs, s_chg, s_range) = (
419            sel.clone(),
420            sel.clone(),
421            sel.clone(),
422            sel.clone(),
423            sel.clone(),
424            sel.clone(),
425            sel.clone(),
426            sel.clone(),
427            sel.clone(),
428            sel.clone(),
429            sel.clone(),
430        );
431        Self {
432            mode: sel.mode(),
433            is_selected: Rc::new(move |i| s_is.is_selected(i)),
434            select_fn: Rc::new(move |i| s_sel.select(i)),
435            toggle_fn: Rc::new(move |i| s_tog.toggle(i)),
436            extend_fn: Rc::new(move |i| s_ext.extend_to(i)),
437            select_all_fn: Rc::new(move |count| s_all.select_all(count)),
438            selected_indices_fn: Rc::new(move || s_idx.selected_indices()),
439            has_selection_fn: Rc::new(move || s_has.count() > 0),
440            clear_fn: Rc::new(move || s_clr.clear()),
441            observe_fn: Rc::new(move |cb| s_obs.selection_signal().observe(move |_| cb())),
442            on_change_fn: Rc::new(move |change| match change {
443                DataChange::ItemsInserted { range } => {
444                    s_chg.adjust_for_insert(range.start, range.end - range.start);
445                }
446                DataChange::ItemsRemoved { range } => {
447                    s_chg.adjust_for_remove(range.start, range.end - range.start);
448                }
449                DataChange::ItemsMoved { from, to, count } => {
450                    s_chg.adjust_for_move(*from, *to, *count);
451                }
452                DataChange::Reset => s_chg.clear(),
453                _ => {}
454            }),
455            // The index model has no stable identity to prune against on a
456            // bare version bump — tree structural adjustments stay no-ops here
457            // (the legacy behaviour).
458            prune_fn: Rc::new(|| {}),
459            prune_range_fn: Rc::new(move |count| {
460                let kept: Vec<usize> = s_range
461                    .selected_indices()
462                    .into_iter()
463                    .filter(|&i| i < count)
464                    .collect();
465                if kept.len() != s_range.count() {
466                    s_range.select_indices(kept, false);
467                }
468            }),
469        }
470    }
471
472    /// Back the facade with a [`KeyedSelectionModel<K>`] plus the view's
473    /// index↔key mapping. `key_at(i)` is the key at visible index `i`, `len()`
474    /// the visible count (for Shift-range ordering and `selected_indices`), and
475    /// `contains_key(&k)` whether the *source* still holds the key (for
476    /// prune-on-remove — a collapsed-but-present tree node must NOT be pruned,
477    /// so this is supplied by the view, not derived from the visible window).
478    pub(crate) fn from_keyed<K: ItemKey>(
479        keyed: KeyedSelectionModel<K>,
480        key_at: Rc<dyn Fn(usize) -> Option<K>>,
481        len: Rc<dyn Fn() -> usize>,
482        contains_key: Rc<dyn Fn(&K) -> bool>,
483    ) -> Self {
484        let mode = keyed.mode();
485        Self {
486            mode,
487            is_selected: {
488                let (k, ka) = (keyed.clone(), key_at.clone());
489                Rc::new(move |i| ka(i).map(|key| k.is_selected(&key)).unwrap_or(false))
490            },
491            select_fn: {
492                let (k, ka) = (keyed.clone(), key_at.clone());
493                Rc::new(move |i| {
494                    if let Some(key) = ka(i) {
495                        k.select(key);
496                    }
497                })
498            },
499            toggle_fn: {
500                let (k, ka) = (keyed.clone(), key_at.clone());
501                Rc::new(move |i| {
502                    if let Some(key) = ka(i) {
503                        k.toggle(key);
504                    }
505                })
506            },
507            extend_fn: {
508                // O(visible count) per Shift-click / Shift-arrow gesture:
509                // builds the full visible key order every call rather than
510                // just the `[anchor_index..=target_index]` span
511                // `KeyedSelectionModel::extend_to` actually inserts.
512                //
513                // Narrowing this to the sub-range was considered and
514                // rejected as not cleanly possible without touching
515                // `teksilo-data`: `extend_to`'s "anchor scrolled out of
516                // view / evicted" fallback (single-select `target`) is
517                // detected by NOT finding `anchor` in the `ordered_keys`
518                // slice it's given, and the anchor is a private field with
519                // no public accessor (`KeyedSelectionModel::anchor` isn't
520                // exposed, and there's no `index_of_key` on the view's
521                // key↔index mapping this facade carries either). Without
522                // that, this closure has no way to know the anchor's
523                // current index — or whether it still HAS one — to bound a
524                // sub-range with, and a shadow copy of the anchor tracked
525                // here would drift from `KeyedSelectionModel`'s own
526                // whenever something else drives `select`/`toggle`
527                // (clearing or moving the anchor) — a duplicated-state
528                // correctness risk for a micro-optimization on a
529                // human-triggered, once-per-gesture path (not a hot loop).
530                let (k, ka, l) = (keyed.clone(), key_at.clone(), len.clone());
531                Rc::new(move |i| {
532                    if let Some(target) = ka(i) {
533                        let ordered: Vec<K> = (0..l()).filter_map(|j| ka(j)).collect();
534                        k.extend_to(target, &ordered);
535                    }
536                })
537            },
538            select_all_fn: {
539                let (k, ka) = (keyed.clone(), key_at.clone());
540                Rc::new(move |count| {
541                    let keys: Vec<K> = (0..count).filter_map(|i| ka(i)).collect();
542                    k.select_keys(keys, false);
543                })
544            },
545            selected_indices_fn: {
546                let (k, ka, l) = (keyed.clone(), key_at.clone(), len.clone());
547                Rc::new(move || {
548                    (0..l())
549                        .filter(|&i| ka(i).map(|key| k.is_selected(&key)).unwrap_or(false))
550                        .collect()
551                })
552            },
553            has_selection_fn: {
554                let k = keyed.clone();
555                Rc::new(move || k.count() > 0)
556            },
557            clear_fn: {
558                let k = keyed.clone();
559                Rc::new(move || k.clear())
560            },
561            observe_fn: {
562                let k = keyed.clone();
563                Rc::new(move |cb| k.selection_signal().observe(move |_| cb()))
564            },
565            on_change_fn: {
566                let (k, c) = (keyed.clone(), contains_key.clone());
567                Rc::new(move |change| match change {
568                    // Keys are stable across inserts / moves; only removals and
569                    // resets can orphan a selected key.
570                    DataChange::ItemsRemoved { .. } | DataChange::Reset => {
571                        k.prune_missing(|key| c(key));
572                    }
573                    _ => {}
574                })
575            },
576            prune_fn: {
577                let (k, c) = (keyed, contains_key);
578                Rc::new(move || k.prune_missing(|key| c(key)))
579            },
580            // Keys already survive a version bump via `prune_fn` above —
581            // there is no separate index range to clamp.
582            prune_range_fn: Rc::new(|_count: usize| {}),
583        }
584    }
585
586    pub(crate) fn mode(&self) -> SelectionMode {
587        self.mode
588    }
589    pub(crate) fn is_selected(&self, index: usize) -> bool {
590        (self.is_selected)(index)
591    }
592    pub(crate) fn select(&self, index: usize) {
593        (self.select_fn)(index)
594    }
595    pub(crate) fn toggle(&self, index: usize) {
596        (self.toggle_fn)(index)
597    }
598    pub(crate) fn extend_to(&self, index: usize) {
599        (self.extend_fn)(index)
600    }
601    pub(crate) fn select_all(&self, count: usize) {
602        (self.select_all_fn)(count)
603    }
604    pub(crate) fn selected_indices(&self) -> Vec<usize> {
605        (self.selected_indices_fn)()
606    }
607    /// Whether anything is selected. Prefer this over
608    /// `!selected_indices().is_empty()` when only the emptiness matters (e.g.
609    /// a per-frame paint gate) — it costs O(selected count), never
610    /// O(visible), for both the index and keyed backings.
611    pub(crate) fn has_selection(&self) -> bool {
612        (self.has_selection_fn)()
613    }
614    pub(crate) fn clear(&self) {
615        (self.clear_fn)()
616    }
617    /// Subscribe to selection changes (drives the view's rebuild). Owns the
618    /// returned handle for the subscription's lifetime.
619    pub(crate) fn observe_for_rebuild(&self, cb: impl Fn() + 'static) -> ObserverHandle {
620        (self.observe_fn)(Box::new(cb))
621    }
622    /// React to a source data change (index-shift for the index model, prune
623    /// for the keyed model).
624    pub(crate) fn on_data_change(&self, change: &DataChange) {
625        (self.on_change_fn)(change)
626    }
627    /// Prune orphaned keys (keyed model) — used by the tree views, which drive
628    /// off a version signal rather than a `DataChange`. No-op for the index
629    /// model.
630    pub(crate) fn prune(&self) {
631        (self.prune_fn)()
632    }
633    /// Drop selected indices `>= count` (index model) after a structural
634    /// change with no delta to shift them by — a version-signal-driven tree
635    /// view's only defence against a selection left pointing past the
636    /// shrunk end (it cannot re-land on the row it used to point at; only
637    /// `focused_index`'s `RowAnchor` tracks identity). No-op for the keyed
638    /// model, already fully reconciled by `prune`.
639    pub(crate) fn prune_out_of_range(&self, count: usize) {
640        (self.prune_range_fn)(count)
641    }
642}
643
644/// Resolves a set of the origin view's flat indices to a **removal thunk** at
645/// drag-start. Invoked at completion, the thunk removes exactly those rows from
646/// the source. Resolving eagerly (rather than re-reading flat indices at
647/// completion) keeps a Move correct even if the origin's flat indices reshuffle
648/// mid-drag — e.g. a `TreeView` spring-load auto-expand — since the stable keys
649/// were already captured. The source erasure supplies it.
650pub(crate) type SnapshotOutFn = Rc<dyn Fn(&[usize]) -> Box<dyn Fn()>>;
651
652/// Active drag-drop feedback a tree data view paints itself: a between-rows
653/// insertion line (Before/After) or a highlighted row (an into-container drop).
654///
655/// Shared by `TreeView` and `TreeTableView` so both render the same affordance
656/// for the same source verdict.
657/// A stable handle to a row in a data view.
658///
659/// Per-row event handlers (a chevron toggle, a click, an activation) are built
660/// once and then live as long as the row widget does, so capturing the flat
661/// index they were built at is fragile: expanding a branch above, applying a
662/// filter, or sorting shifts every index below, and the stale handler would act
663/// on whatever row moved into that slot.
664///
665/// A `RowAnchor` closes over the row's **source-owned identity** instead and
666/// resolves the row's *current* position on demand. The key never surfaces in
667/// the anchor's type — it is captured inside the resolver, so views stay
668/// key-agnostic ([`TreeSource`](crate::tree_source::TreeSource) and
669/// [`ListSource`](crate::list_source::ListSource) both erase it).
670///
671/// Sources without identity (a bare `ListModel`, or any source that leaves
672/// `key_at` at its `None` default) get a fixed anchor that always reports the
673/// index it was built with — no worse than capturing the index directly.
674///
675/// A bare `ListModel` has no identity to offer (a `Vec` row *is* its position),
676/// so anchors over one are fixed. `SortFilterListModel` keys rows by their
677/// **source index**, which no sort/filter reprojection renumbers — so anchors
678/// over a projection do track their row across a filter change, which is the
679/// flat fragility in practice. They can still mis-resolve inside the window
680/// between an *upstream* insert/remove and the rebuild it schedules, since that
681/// does renumber source indices; no worse than the captured index they replace.
682/// The tree sources all carry real identity.
683///
684/// **Precondition: keys must be unique.** Resolution falls back to a lookup by
685/// key, which returns the *first* match, so a source handing out duplicate keys
686/// would silently redirect an anchor onto a different row — the very failure
687/// this type exists to prevent.
688#[derive(Clone)]
689pub struct RowAnchor {
690    resolve: Rc<dyn Fn() -> Option<usize>>,
691}
692
693impl RowAnchor {
694    /// Build an identity-backed anchor from a resolver.
695    pub(crate) fn new(resolve: Rc<dyn Fn() -> Option<usize>>) -> Self {
696        Self { resolve }
697    }
698
699    /// An anchor for a source with no identity: always reports `index`.
700    pub(crate) fn fixed(index: usize) -> Self {
701        Self {
702            resolve: Rc::new(move || Some(index)),
703        }
704    }
705
706    /// The row's current flat index, or `None` if it no longer exists in the
707    /// source (it was deleted, or filtered away).
708    pub fn index(&self) -> Option<usize> {
709        (self.resolve)()
710    }
711
712    /// Whether the row still exists.
713    pub fn is_live(&self) -> bool {
714        self.index().is_some()
715    }
716}
717
718impl std::fmt::Debug for RowAnchor {
719    /// Deliberately does NOT resolve: the resolver reads the source's
720    /// interior-mutable state, so a `{:?}` from inside code already holding a
721    /// borrow (a `set_source` closure, a reorder callback, a debugger's
722    /// pretty-printer) would panic on a `RefCell` conflict.
723    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
724        f.write_str("RowAnchor(..)")
725    }
726}
727
728/// Keep an open cell editor pointing at the row it was opened on.
729///
730/// `editing_cell` is a `(row, col)` pair that outlives rebuilds, so rows
731/// appearing or vanishing above an open editor would slide it onto a different
732/// row. The anchor is captured the first time an open editor is seen and
733/// re-resolved on every later rebuild: the row index is rewritten when it moved,
734/// and the editor closes outright when its row is gone — better than silently
735/// editing whoever took the slot.
736///
737/// Called from each body pane's `build`, which is the only place that sees both
738/// an editing change and a data change. It can therefore write `editing_cell`
739/// while that pane is building; the write is idempotent and converges in one
740/// extra pass (the next reconcile finds `cur == row` and writes nothing), which
741/// `an_editing_reconcile_converges_in_one_pass` pins.
742pub(crate) fn reconcile_editing_row(
743    editing_cell: &teksilo_core::signal::Signal<Option<(usize, usize)>>,
744    slot: &Rc<std::cell::RefCell<Option<RowAnchor>>>,
745    anchor_of: &dyn Fn(usize) -> RowAnchor,
746) {
747    let Some((row, col)) = editing_cell.get() else {
748        *slot.borrow_mut() = None;
749        return;
750    };
751    let existing = slot.borrow().clone();
752    match existing {
753        None => *slot.borrow_mut() = Some(anchor_of(row)),
754        Some(anchor) => match anchor.index() {
755            Some(cur) if cur != row => editing_cell.set(Some((cur, col))),
756            Some(_) => {}
757            None => {
758                editing_cell.set(None);
759                *slot.borrow_mut() = None;
760            }
761        },
762    }
763}
764
765/// Tint for the "drop into this container" row highlight. Defined once so the
766/// `DropFeedback` handed to the framework and the widget's own paint cannot
767/// drift into two different colors on the same row.
768pub(crate) fn drop_into_tint() -> teksilo_tokens::Color {
769    teksilo_tokens::Color::from_rgba(0.25, 0.47, 0.85, 0.25)
770}
771
772#[derive(Clone, Copy, PartialEq, Debug)]
773pub(crate) enum DropViz {
774    /// Horizontal insertion line at `y`, spanning `width`, indented by
775    /// `depth` tree levels — the level the dropped row lands at.
776    Line { y: f32, width: f32, depth: usize },
777    /// Highlighted target row `[top, top + height]`, spanning `width`,
778    /// indented by the target's own `depth` — the "drop into this folder"
779    /// affordance.
780    Rect {
781        top: f32,
782        height: f32,
783        width: f32,
784        depth: usize,
785    },
786}
787
788/// The reusable export / foreign-drop machinery shared by all five data views:
789/// the config fields, the drag-start payload build (selection set already
790/// resolved by the caller), the foreign-receive sugar, and the `on_drag_ended`
791/// move-out completion. Each view holds ONE of these instead of duplicating the
792/// logic five ways (the drift that a code review caught). See
793/// [docs/drag-and-drop.md §12](https://github.com/ferntech-eu/teksilo/blob/main/docs/drag-and-drop.md).
794pub(crate) struct RowExport<T: 'static> {
795    /// `Some` once `.exportable(..)` was called; the transfer mode also drives
796    /// the move-out completion.
797    pub(crate) mode: Option<DragTransferMode>,
798    /// Clones `&T` → `T` for the payload (set by `.exportable`/`.export_external`,
799    /// each `where T: Clone`, so the view constructor stays unconstrained).
800    #[allow(clippy::type_complexity)]
801    pub(crate) clone_item_fn: Option<Rc<dyn Fn(&T) -> T>>,
802    /// Builds MIME reps of the dragged items for OS / `DropZone` export.
803    #[allow(clippy::type_complexity)]
804    pub(crate) export_mime_fn: Option<Rc<dyn Fn(&[T]) -> Vec<(String, Vec<u8>)>>>,
805    /// App override for removing rows moved out to a foreign target.
806    #[allow(clippy::type_complexity)]
807    pub(crate) on_rows_transferred_out: Option<Rc<dyn Fn(&[usize], &mut EventContext)>>,
808    /// Accept exported rows from a different view/source (zero-custom-source).
809    pub(crate) accept_foreign_rows: bool,
810    /// Handler for rows accepted via `accept_foreign_rows`.
811    #[allow(clippy::type_complexity)]
812    pub(crate) on_rows_received: Option<Rc<dyn Fn(Vec<T>, usize, &mut EventContext)>>,
813    /// Set by the view's own `on_drop` when it applied a same-view reorder, so
814    /// the completion skips the move-out (already applied). The TabBar pattern.
815    pub(crate) self_reorder_flag: Rc<Cell<bool>>,
816    /// The rows carried by the in-flight drag (for the app move-out callback).
817    dragged_rows: Rc<RefCell<Vec<usize>>>,
818    /// Stable-key removal thunk for the default move-out, resolved at drag-start.
819    #[allow(clippy::type_complexity)]
820    removal: Rc<RefCell<Option<Box<dyn Fn()>>>>,
821}
822
823impl<T: 'static> Clone for RowExport<T> {
824    // Hand-written (not derived) so cloning does NOT require `T: Clone` — every
825    // field is an `Rc` / `Copy`, so a clone shares the same drag stash + flags,
826    // which is exactly what the per-row drag closure needs.
827    fn clone(&self) -> Self {
828        Self {
829            mode: self.mode,
830            clone_item_fn: self.clone_item_fn.clone(),
831            export_mime_fn: self.export_mime_fn.clone(),
832            on_rows_transferred_out: self.on_rows_transferred_out.clone(),
833            accept_foreign_rows: self.accept_foreign_rows,
834            on_rows_received: self.on_rows_received.clone(),
835            self_reorder_flag: self.self_reorder_flag.clone(),
836            dragged_rows: self.dragged_rows.clone(),
837            removal: self.removal.clone(),
838        }
839    }
840}
841
842impl<T: 'static> Default for RowExport<T> {
843    fn default() -> Self {
844        Self {
845            mode: None,
846            clone_item_fn: None,
847            export_mime_fn: None,
848            on_rows_transferred_out: None,
849            accept_foreign_rows: false,
850            on_rows_received: None,
851            self_reorder_flag: Rc::new(Cell::new(false)),
852            dragged_rows: Rc::new(RefCell::new(Vec::new())),
853            removal: Rc::new(RefCell::new(None)),
854        }
855    }
856}
857
858impl<T: 'static> RowExport<T> {
859    /// `.exportable(mode)` — carry item clones; `where T: Clone` at the call.
860    pub(crate) fn set_exportable(&mut self, mode: DragTransferMode)
861    where
862        T: Clone,
863    {
864        self.mode = Some(mode);
865        if self.clone_item_fn.is_none() {
866            self.clone_item_fn = Some(Rc::new(|t: &T| t.clone()));
867        }
868    }
869
870    /// `.export_external(f)` — attach MIME; implies exportable.
871    pub(crate) fn set_export_external(
872        &mut self,
873        f: impl Fn(&[T]) -> Vec<(String, Vec<u8>)> + 'static,
874    ) where
875        T: Clone,
876    {
877        if self.clone_item_fn.is_none() {
878            self.clone_item_fn = Some(Rc::new(|t: &T| t.clone()));
879        }
880        if self.mode.is_none() {
881            self.mode = Some(DragTransferMode::default());
882        }
883        self.export_mime_fn = Some(Rc::new(f));
884    }
885
886    pub(crate) fn set_on_rows_transferred_out(
887        &mut self,
888        f: impl Fn(&[usize], &mut EventContext) + 'static,
889    ) {
890        self.on_rows_transferred_out = Some(Rc::new(f));
891    }
892
893    pub(crate) fn set_on_rows_received(
894        &mut self,
895        f: impl Fn(Vec<T>, usize, &mut EventContext) + 'static,
896    ) {
897        self.on_rows_received = Some(Rc::new(f));
898    }
899
900    /// Rows are a drag source when the view reorders OR exports.
901    pub(crate) fn is_drag_source(&self, reorderable: bool) -> bool {
902        reorderable || self.mode.is_some()
903    }
904
905    /// The view is a drop target when it reorders OR accepts foreign rows.
906    pub(crate) fn is_drop_target(&self, reorderable: bool) -> bool {
907        reorderable || self.accept_foreign_rows
908    }
909
910    /// Build the drag payload for the (already selection-resolved) `rows`. Drops
911    /// any non-resident row (a lazy `Loading` row `read` can't serve) so `rows`
912    /// and `items` stay index-aligned and a Move never deletes a row whose data
913    /// wasn't transferred. Attaches MIME, and stashes the rows + a stable-key
914    /// removal thunk for the completion.
915    ///
916    /// `None` when no row survives the residency filter (an all-`Loading`
917    /// selection): the caller must refuse the drag rather than float an empty
918    /// payload nothing can accept.
919    pub(crate) fn build_payload(
920        &self,
921        source: ViewId,
922        mut rows: Vec<usize>,
923        read: &dyn Fn(usize, &mut dyn FnMut(&T)) -> bool,
924        snapshot_out: &SnapshotOutFn,
925    ) -> Option<DragPayload> {
926        let items: Option<Vec<T>> = if let Some(cf) = self.clone_item_fn.as_ref() {
927            let mut out = Vec::with_capacity(rows.len());
928            rows.retain(|&r| {
929                let mut got = None;
930                read(r, &mut |t| got = Some(cf(t)));
931                match got {
932                    Some(v) => {
933                        out.push(v);
934                        true
935                    }
936                    None => false,
937                }
938            });
939            Some(out)
940        } else {
941            None
942        };
943        if rows.is_empty() {
944            return None;
945        }
946        let mime_pairs: Vec<(String, Vec<u8>)> =
947            match (self.export_mime_fn.as_ref(), items.as_ref()) {
948                (Some(mf), Some(its)) => mf(its),
949                _ => Vec::new(),
950            };
951        let mut payload = DragPayload::typed(RowDragData::<T> {
952            source,
953            rows: rows.clone(),
954            items,
955        });
956        let has_mime = !mime_pairs.is_empty();
957        for (mime, bytes) in mime_pairs {
958            payload = payload.with_mime(&mime, bytes);
959        }
960        if has_mime {
961            payload.enrich_external_from_mime();
962        }
963        *self.removal.borrow_mut() = Some((snapshot_out)(&rows));
964        *self.dragged_rows.borrow_mut() = rows;
965        Some(payload)
966    }
967
968    /// Whether a **foreign** exported payload would be accepted here — for the
969    /// hover affordance. (Same-view / reorder-only payloads return `false`.)
970    pub(crate) fn accepts_foreign_export(&self, payload: &DragPayload, source: ViewId) -> bool {
971        self.accept_foreign_rows
972            && self.on_rows_received.is_some()
973            && payload
974                .get_typed::<RowDragData<T>>()
975                .is_some_and(|rd| rd.source != source && rd.is_export())
976    }
977
978    /// Foreign-receive sugar for a view's `on_drop`. Peeks before taking, so a
979    /// non-matching payload is left intact for any further fallback.
980    pub(crate) fn foreign_receive(
981        &self,
982        payload: &mut DragPayload,
983        source: ViewId,
984        insertion: usize,
985        ctx: &mut EventContext,
986    ) -> bool {
987        if self.accepts_foreign_export(payload, source)
988            && let Some(cb) = self.on_rows_received.as_ref()
989            && let Some(rd) = payload.take_typed::<RowDragData<T>>()
990            && let Some(items) = rd.items
991        {
992            cb(items, insertion, ctx);
993            return true;
994        }
995        false
996    }
997
998    /// The view's own `on_drop` calls this after applying a genuine SAME-VIEW
999    /// reorder, so the completion knows the change was already applied.
1000    pub(crate) fn note_self_reorder(&self) {
1001        self.self_reorder_flag.set(true);
1002    }
1003
1004    /// Install the `on_drag_ended` move-out completion. A same-view reorder set
1005    /// `self_reorder_flag` (skipped here); on `Move` + accepted-elsewhere the
1006    /// origin rows are removed via the app override (delivered **descending** so
1007    /// index-by-index removal stays valid) or the stable-key removal thunk.
1008    pub(crate) fn install_completion(&self, handlers: HandlerSet) -> HandlerSet {
1009        let Some(mode) = self.mode else {
1010            return handlers;
1011        };
1012        let flag = self.self_reorder_flag.clone();
1013        let dragged = self.dragged_rows.clone();
1014        let removal = self.removal.clone();
1015        let on_out = self.on_rows_transferred_out.clone();
1016        handlers.on_drag_ended(move |outcome, ctx| {
1017            let handled_by_us = flag.replace(false);
1018            let rows = std::mem::take(&mut *dragged.borrow_mut());
1019            let thunk = removal.borrow_mut().take();
1020            if handled_by_us {
1021                return;
1022            }
1023            let accepted_elsewhere = matches!(
1024                outcome,
1025                DropOutcome::InApp { accepted: true } | DropOutcome::OsMove
1026            );
1027            if mode != DragTransferMode::Move || !accepted_elsewhere || rows.is_empty() {
1028                return;
1029            }
1030            if let Some(cb) = on_out.as_ref() {
1031                let mut desc = rows;
1032                desc.sort_unstable();
1033                desc.reverse();
1034                cb(&desc, ctx);
1035            } else if let Some(thunk) = thunk {
1036                thunk();
1037            }
1038        })
1039    }
1040}
1041
1042/// Shared deferred-selection press logic for a data-view row (the drift a code
1043/// review caught: the `press_claimed` guard was missing in one view). Pressing
1044/// an already-selected row DEFERS the collapse-to-single to a release WITHOUT a
1045/// drag (an active drag consumes `PointerUp`), so grabbing a multi-selection
1046/// drags the whole set. `pending` is a per-row cell shared by the two calls.
1047pub(crate) mod deferred_select {
1048    use std::cell::Cell;
1049    use std::rc::Rc;
1050
1051    use teksilo_core::event::Modifiers;
1052    use teksilo_core::widget::EventContext;
1053
1054    use super::RowSelection;
1055
1056    /// Handle a primary `PointerDown` on row `index`. Returns without selecting
1057    /// if the press was claimed by an interactive child (also clearing a stale
1058    /// `pending`). Ctrl/Shift select immediately; a plain press on an
1059    /// already-selected row defers; otherwise selects.
1060    pub(crate) fn on_down(
1061        sel: &RowSelection,
1062        index: usize,
1063        modifiers: Modifiers,
1064        pending: &Rc<Cell<bool>>,
1065        ctx: &mut EventContext,
1066    ) -> bool {
1067        if ctx.press_claimed_by_interactive_child() {
1068            pending.set(false);
1069            return false;
1070        }
1071        // The accelerator-click that adds one row to a discontiguous selection:
1072        // Ctrl+click on Windows and Linux, ⌘-click on macOS — where ⌃-click is
1073        // the secondary click and would open a context menu instead.
1074        if modifiers.command() {
1075            sel.toggle(index);
1076            pending.set(false);
1077        } else if modifiers.shift() {
1078            sel.extend_to(index);
1079            pending.set(false);
1080        } else if sel.is_selected(index) {
1081            pending.set(true);
1082        } else {
1083            sel.select(index);
1084            pending.set(false);
1085        }
1086        true
1087    }
1088
1089    /// Handle a primary `PointerUp` on row `index` — reached only on a click
1090    /// WITHOUT a drag. Collapses the deferred multi-selection, unless the
1091    /// release belongs to an interactive child.
1092    pub(crate) fn on_up(
1093        sel: &RowSelection,
1094        index: usize,
1095        pending: &Rc<Cell<bool>>,
1096        ctx: &mut EventContext,
1097    ) {
1098        if ctx.press_claimed_by_interactive_child() {
1099            return;
1100        }
1101        if pending.replace(false) {
1102            sel.select(index);
1103        }
1104    }
1105}
1106
1107#[cfg(test)]
1108mod payload_tests {
1109    use super::*;
1110
1111    fn noop_snapshot() -> SnapshotOutFn {
1112        Rc::new(|_: &[usize]| Box::new(|| {}) as Box<dyn Fn()>)
1113    }
1114
1115    #[test]
1116    fn an_all_unresident_selection_refuses_the_drag() {
1117        // Every dragged row is still `Loading`: the residency filter empties
1118        // the set, and the drag must be refused outright — a floating payload
1119        // with no rows and no items would remove nothing on a Move and offer
1120        // nothing to a receiver.
1121        let mut export = RowExport::<u64>::default();
1122        export.set_exportable(DragTransferMode::Move);
1123        let read = |_: usize, _: &mut dyn FnMut(&u64)| false;
1124        let payload = export.build_payload(
1125            ViewId::next(ViewKind::List),
1126            vec![0, 1, 2],
1127            &read,
1128            &noop_snapshot(),
1129        );
1130        assert!(payload.is_none());
1131    }
1132
1133    #[test]
1134    fn a_partially_resident_selection_carries_only_the_resident_rows() {
1135        let mut export = RowExport::<u64>::default();
1136        export.set_exportable(DragTransferMode::Copy);
1137        // Row 1 is unresident; rows 0 and 2 resolve.
1138        let read = |i: usize, f: &mut dyn FnMut(&u64)| {
1139            if i == 1 {
1140                return false;
1141            }
1142            f(&(i as u64 * 10));
1143            true
1144        };
1145        let payload = export
1146            .build_payload(
1147                ViewId::next(ViewKind::List),
1148                vec![0, 1, 2],
1149                &read,
1150                &noop_snapshot(),
1151            )
1152            .expect("two rows are resident");
1153        let rd = payload.get_typed::<RowDragData<u64>>().unwrap();
1154        assert_eq!(rd.rows, vec![0, 2]);
1155        assert_eq!(rd.items.as_deref(), Some(&[0, 20][..]));
1156    }
1157}