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::build_context::BuildContext;
30use teksilo_core::drag_payload::{DragPayload, DropOutcome};
31use teksilo_core::widget::{EventContext, Widget};
32use teksilo_core::widget_builder::HandlerSet;
33use teksilo_core::widget_id::WidgetId;
34use teksilo_data::{
35 DataChange, DropPosition, ItemKey, KeyedSelectionModel, SelectionMode, SelectionModel,
36};
37
38/// How a data-view row/tile is *activated* (opened/committed) by pointer —
39/// distinct from *selection*, which also moves on arrow-key navigation. Mirrors
40/// the platform split other toolkits expose (Qt
41/// `SH_ItemView_ActivateItemOnSingleClick`, GTK `activate-on-single-click`).
42/// Enter/Space always activates regardless of this mode.
43///
44/// Pass to `ListView::activate_on`, `TreeView::activate_on`, etc.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
46pub enum ActivateOn {
47 /// One primary click activates the row (KDE / web / Scrivener convention).
48 /// Selection and activation happen on the same click.
49 SingleClick,
50 /// A double primary click activates the row; the first click only selects
51 /// it (Finder / Explorer / Qt and GTK default). This is the [`Default`].
52 #[default]
53 DoubleClick,
54}
55
56/// Which kind of data view minted a [`ViewId`]. Folded into the id so two
57/// different widget kinds that happen to draw the same value from the shared
58/// process counter can never be mistaken for one another — the reason a bare
59/// `usize` id was a latent cross-widget hazard.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
61pub(crate) enum ViewKind {
62 List,
63 Tree,
64 Table,
65 TreeTable,
66 Grid,
67}
68
69/// Opaque, kind-tagged, process-unique identity of a drag-capable data-view
70/// instance. Used to tell a view's OWN reorder (`SameView`) from a foreign drop
71/// on the receive side. Apps only ever compare two `ViewId`s for equality (e.g.
72/// out of a received [`RowDragData`]); there is no public constructor, and the
73/// value is stable for a view instance's lifetime, so it is safe to compare
74/// even across windows (each mint is globally unique).
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76pub struct ViewId(ViewKind, usize);
77
78impl ViewId {
79 /// Mint a fresh, globally-unique id for a view of the given kind.
80 pub(crate) fn next(kind: ViewKind) -> Self {
81 Self(kind, next_view_id())
82 }
83}
84
85/// What the *origin* view does to its own rows once a drag is accepted by a
86/// **foreign** target (a different `DropTarget` / view / the OS). Purely an
87/// origin-side cleanup choice — the receiver is unaffected. A same-view reorder
88/// is never a transfer, so this never applies to it.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
90pub enum DragTransferMode {
91 /// Leave the origin rows in place (the dragged data is duplicated).
92 Copy,
93 /// Remove the dragged rows from the origin once accepted elsewhere
94 /// (or exported as an OS move). This is the [`Default`].
95 #[default]
96 Move,
97}
98
99/// The public, generic drag payload every data-view row (or selected set)
100/// emits. It occupies the single typed slot of a
101/// [`teksilo_core::drag_payload::DragPayload`] and serves both audiences:
102///
103/// - the origin view's own erased classifier reads [`source`](Self::source) +
104/// [`rows`](Self::rows) to recognise a same-view reorder;
105/// - a **foreign** consumer (another view's custom `ListDataSource`, a
106/// `DropTarget::accept_typed::<RowDragData<T>>()`, or `on_rows_received`)
107/// reads [`items`](Self::items).
108///
109/// `items` is `Some` only when the origin view opted into export via
110/// `.exportable(..)` (which requires `T: Clone`); a plain `.reorderable(true)`
111/// drag carries `items == None` (nothing outside the origin could use it
112/// anyway), so a reorder-only view is never accidentally droppable elsewhere.
113#[derive(Debug)]
114pub struct RowDragData<T: 'static> {
115 /// Identity of the view that started the drag.
116 pub source: ViewId,
117 /// The dragged rows as the origin view's flat visible indices at
118 /// drag-start, ascending. Informational (row count, app callbacks): the
119 /// origin's accept path resolves the dragged rows' **stable keys** at
120 /// drag-start and never re-reads these indices at hover/drop time — they
121 /// go stale the moment the source reflows mid-drag (a spring-load
122 /// auto-expand, a peer write). A foreign consumer should read
123 /// [`items`](Self::items) instead.
124 pub rows: Vec<usize>,
125 /// Clones of the dragged items, `rows`-ordered. `None` for a reorder-only
126 /// (non-exportable) drag.
127 pub items: Option<Vec<T>>,
128}
129
130impl<T: 'static> RowDragData<T> {
131 /// The dragged items, if this is an export drag (`.exportable(..)` was set
132 /// on the origin). `None` for a reorder-only drag.
133 pub fn items(&self) -> Option<&[T]> {
134 self.items.as_deref()
135 }
136
137 /// Consume the payload for its items (avoids cloning on the receive side).
138 pub fn into_items(self) -> Option<Vec<T>> {
139 self.items
140 }
141
142 /// Whether this drag carries exportable items — i.e. the origin opted into
143 /// `.exportable(..)`. A foreign receiver should gate on this (a reorder-only
144 /// payload has the same Rust type but carries nothing usable).
145 pub fn is_export(&self) -> bool {
146 self.items.is_some()
147 }
148
149 /// Number of dragged rows.
150 pub fn len(&self) -> usize {
151 self.rows.len()
152 }
153
154 /// Whether no rows are carried (never true for a real drag).
155 pub fn is_empty(&self) -> bool {
156 self.rows.is_empty()
157 }
158}
159
160/// A drop indicator the data views' `paint` renders. `allowed == false` paints a
161/// muted line where an accepted-drop line would be — the pre-commit "you can't
162/// drop here" affordance.
163#[derive(Debug, Clone, Copy, PartialEq)]
164pub(crate) struct DropIndicator {
165 pub(crate) y: f32,
166 pub(crate) width: f32,
167 pub(crate) allowed: bool,
168}
169
170/// A process-unique id distinguishing data-view instances (for SameView drop
171/// detection when several views share one source).
172pub(crate) fn next_view_id() -> usize {
173 static NEXT: AtomicUsize = AtomicUsize::new(1);
174 NEXT.fetch_add(1, Ordering::Relaxed)
175}
176
177/// Map a flat insertion index (`0..=len`) to the `(target_index, position)` pair
178/// a `ListDataSource::can_accept` / `accept_drop` understands. `None` for an
179/// empty list. Insertion *before* row `i` is `(i, Before)`; insertion past the
180/// end is `(len-1, After)`.
181pub(crate) fn flat_insertion_target(insertion: usize, len: usize) -> Option<(usize, DropPosition)> {
182 if len == 0 {
183 None
184 } else if insertion >= len {
185 Some((len - 1, DropPosition::After))
186 } else {
187 Some((insertion, DropPosition::Before))
188 }
189}
190
191/// The default skeleton for a `Loading` row — a muted inset bar. The row's
192/// placement sizes it to the row's height and width.
193/// One row's tooltip, already resolved from its item and awaiting a
194/// `BuildContext` to attach it with.
195pub(crate) enum ResolvedRowTooltip {
196 Plain(teksilo_i18n::LocalizedString),
197 Rich(crate::tooltip::RichTooltipSource),
198 Composite(Box<dyn Widget>),
199}
200
201/// Per-row tooltip resolvers, shared by every data view that builds rows from
202/// a delegate.
203///
204/// A data view's rows are not authored by the app as widgets it can hang a
205/// `.tooltip(...)` on — they come out of a delegate, and the view owns the
206/// resulting `WidgetId`. So the view takes the *resolvers* instead and does the
207/// attaching itself, against the row it just built. Same shape as
208/// [`TabDelegate`](crate::tab_widget::TabDelegate)'s per-tab tooltip callbacks,
209/// and the same last-setter-wins matrix as the per-widget setters: each `set_*`
210/// clears the other two, so a row can never mature two tips at once.
211///
212/// Placement is [`Side`](crate::tooltip::TooltipPlacement::Side) for every
213/// view here — rows stack vertically, and a `Below` tip would cover the next
214/// row, which is the one the user is most likely reading next.
215///
216/// Cost: the body is resolved and built for each **realized** row, i.e. the
217/// virtualization window (visible + buffer), not the whole model — and again
218/// whenever those rows rebuild. Keep resolvers cheap; defer anything expensive
219/// (a backend read, a subtree walk) to the body's own first paint, which only
220/// happens if the tip is actually shown.
221pub(crate) struct RowTooltips<T: 'static> {
222 plain: Option<Rc<dyn Fn(usize, &T) -> Option<teksilo_i18n::LocalizedString>>>,
223 rich: Option<Rc<dyn Fn(usize, &T) -> Option<crate::tooltip::RichTooltipSource>>>,
224 composite: Option<Rc<dyn Fn(usize, &T) -> Option<Box<dyn Widget>>>>,
225 /// Whether a composite row tip offers dwell-to-sticky promotion.
226 composite_sticky: bool,
227}
228
229impl<T: 'static> Default for RowTooltips<T> {
230 fn default() -> Self {
231 Self {
232 plain: None,
233 rich: None,
234 composite: None,
235 composite_sticky: true,
236 }
237 }
238}
239
240impl<T: 'static> Clone for RowTooltips<T> {
241 fn clone(&self) -> Self {
242 Self {
243 plain: self.plain.clone(),
244 rich: self.rich.clone(),
245 composite: self.composite.clone(),
246 composite_sticky: self.composite_sticky,
247 }
248 }
249}
250
251impl<T: 'static> std::fmt::Debug for RowTooltips<T> {
252 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253 f.debug_struct("RowTooltips")
254 .field("plain", &self.plain.is_some())
255 .field("rich", &self.rich.is_some())
256 .field("composite", &self.composite.is_some())
257 .finish()
258 }
259}
260
261impl<T: 'static> RowTooltips<T> {
262 /// Whether any resolver is set — lets a view skip the per-row work.
263 pub(crate) fn is_set(&self) -> bool {
264 self.plain.is_some() || self.rich.is_some() || self.composite.is_some()
265 }
266
267 pub(crate) fn set_plain(
268 &mut self,
269 f: impl Fn(usize, &T) -> Option<teksilo_i18n::LocalizedString> + 'static,
270 ) {
271 *self = Self {
272 plain: Some(Rc::new(f)),
273 rich: None,
274 composite: None,
275 composite_sticky: self.composite_sticky,
276 };
277 }
278
279 pub(crate) fn set_rich(
280 &mut self,
281 f: impl Fn(usize, &T) -> Option<crate::tooltip::RichTooltipSource> + 'static,
282 ) {
283 *self = Self {
284 plain: None,
285 rich: Some(Rc::new(f)),
286 composite: None,
287 composite_sticky: self.composite_sticky,
288 };
289 }
290
291 pub(crate) fn set_composite(
292 &mut self,
293 f: impl Fn(usize, &T) -> Option<Box<dyn Widget>> + 'static,
294 ) {
295 *self = Self {
296 plain: None,
297 rich: None,
298 composite: Some(Rc::new(f)),
299 composite_sticky: self.composite_sticky,
300 };
301 }
302
303 /// Whether a composite row tip offers dwell promotion. Off suits a
304 /// read-only card: nothing to reach into, so nothing to pin.
305 pub(crate) fn set_composite_sticky(&mut self, on: bool) {
306 self.composite_sticky = on;
307 }
308
309 /// Resolve this row's tooltip, if any.
310 ///
311 /// Split from [`attach_resolved`](Self::attach_resolved) because a view can
312 /// only reach the item from inside the same borrow that builds the row
313 /// widget, while attaching needs the `BuildContext` and the resulting
314 /// `WidgetId` — which only exist after that borrow ends.
315 pub(crate) fn resolve(&self, index: usize, item: &T) -> Option<ResolvedRowTooltip> {
316 if let Some(f) = &self.composite {
317 f(index, item).map(ResolvedRowTooltip::Composite)
318 } else if let Some(f) = &self.rich {
319 f(index, item).map(ResolvedRowTooltip::Rich)
320 } else if let Some(f) = &self.plain {
321 f(index, item).map(ResolvedRowTooltip::Plain)
322 } else {
323 None
324 }
325 }
326
327 /// Attach a resolved tooltip to the row widget the view just built.
328 pub(crate) fn attach_resolved(
329 &self,
330 ctx: &mut teksilo_core::build_context::BuildContext,
331 row_id: teksilo_core::widget_id::WidgetId,
332 resolved: ResolvedRowTooltip,
333 ) {
334 // Rows stack vertically, so a `Below` tip would cover the next row —
335 // the one the user is most likely reading next.
336 let placement = crate::tooltip::TooltipPlacement::Side;
337 match resolved {
338 ResolvedRowTooltip::Composite(body) => {
339 let delay = ctx.theme().motion.tooltip_delay_heavy;
340 crate::tooltip::attach_composite_tooltip_widget_with_placement(
341 ctx,
342 row_id,
343 crate::tooltip::CompositeTooltipWidget::new()
344 .content_boxed(body)
345 .sticky(self.composite_sticky),
346 delay,
347 placement,
348 );
349 }
350 ResolvedRowTooltip::Rich(source) => {
351 let delay = ctx.theme().motion.tooltip_delay;
352 crate::tooltip::attach_rich_tooltip_source_with_placement(
353 ctx, row_id, source, delay, placement,
354 );
355 }
356 ResolvedRowTooltip::Plain(text) => {
357 let delay = ctx.theme().motion.tooltip_delay;
358 crate::tooltip::attach_plain_tooltip_with_placement(
359 ctx, row_id, text, delay, placement,
360 );
361 }
362 }
363 }
364}
365
366pub(crate) fn default_placeholder() -> Box<dyn Widget> {
367 use crate::primitives::{Padding, RectWidget};
368 Box::new(
369 Padding::uniform(6.0).child(
370 RectWidget::new()
371 .background(teksilo_tokens::SurfaceRole::Hover)
372 .corner_radius(teksilo_tokens::CornerRadius::uniform(4.0)),
373 ),
374 )
375}
376
377/// Index-facing row-selection facade backing the four data views.
378///
379/// An app installs *either* the index-based [`SelectionModel`] (positions) or a
380/// [`KeyedSelectionModel<K>`] (stable identities that survive reorder / filter /
381/// window-slide / multi-view). The views' click / keyboard / rebuild / paint
382/// paths all work in **indices**, so this facade erases the difference: the
383/// keyed variant carries the view's index↔key mapping (`key_at` / `len` /
384/// `contains_key`) and translates internally. The method surface deliberately
385/// mirrors `SelectionModel` so call sites read identically (`rs.select(i)`,
386/// `rs.is_selected(i)`, …).
387#[derive(Clone)]
388pub(crate) struct RowSelection {
389 mode: SelectionMode,
390 is_selected: Rc<dyn Fn(usize) -> bool>,
391 select_fn: Rc<dyn Fn(usize)>,
392 toggle_fn: Rc<dyn Fn(usize)>,
393 extend_fn: Rc<dyn Fn(usize)>,
394 /// Ctrl+Shift range extension: keeps whatever the previous gesture
395 /// selected instead of replacing it, so a second disjoint range can be
396 /// built without losing the first.
397 extend_additive_fn: Rc<dyn Fn(usize)>,
398 select_all_fn: Rc<dyn Fn(usize)>,
399 selected_indices_fn: Rc<dyn Fn() -> Vec<usize>>,
400 /// Cheap (O(selected count), never O(visible)) emptiness check for the
401 /// container-focus-ring gate — paint runs every frame and only needs to
402 /// know "is anything selected", not the set itself.
403 has_selection_fn: Rc<dyn Fn() -> bool>,
404 clear_fn: Rc<dyn Fn()>,
405 observe_fn: Rc<dyn Fn(Box<dyn Fn()>) -> ObserverHandle>,
406 on_change_fn: Rc<dyn Fn(&DataChange)>,
407 /// Unconditional prune for the version-signal-driven tree views (which
408 /// don't emit a `DataChange`): drop orphaned keys (keyed) or no-op (index).
409 prune_fn: Rc<dyn Fn()>,
410 /// Drop selected indices that no longer fit `0..count`, for the
411 /// version-signal-driven tree views' index-selection path: an index has
412 /// no identity to follow a moved row by (that's `focused_index`'s job,
413 /// via `RowAnchor`), so a structural change can only clamp it — never
414 /// re-land it on the row it used to point at. A no-op for the keyed
415 /// model, which is already fully reconciled by `prune_fn`.
416 prune_range_fn: Rc<dyn Fn(usize)>,
417}
418
419impl RowSelection {
420 /// Back the facade with the index-based [`SelectionModel`]. Index ops pass
421 /// straight through; `on_data_change` index-shifts (insert / remove) or
422 /// clears (reset) the selection, matching the legacy inline behaviour.
423 pub(crate) fn from_index(sel: SelectionModel) -> Self {
424 let (s_is, s_sel, s_tog, s_ext, s_all, s_idx, s_has, s_clr, s_obs, s_chg, s_range) = (
425 sel.clone(),
426 sel.clone(),
427 sel.clone(),
428 sel.clone(),
429 sel.clone(),
430 sel.clone(),
431 sel.clone(),
432 sel.clone(),
433 sel.clone(),
434 sel.clone(),
435 sel.clone(),
436 );
437 Self {
438 mode: sel.mode(),
439 is_selected: Rc::new(move |i| s_is.is_selected(i)),
440 select_fn: Rc::new(move |i| s_sel.select(i)),
441 toggle_fn: Rc::new(move |i| s_tog.toggle(i)),
442 extend_fn: Rc::new(move |i| s_ext.extend_to(i)),
443 extend_additive_fn: {
444 let s = sel.clone();
445 Rc::new(move |i| s.extend_to_additive(i))
446 },
447 select_all_fn: Rc::new(move |count| s_all.select_all(count)),
448 selected_indices_fn: Rc::new(move || s_idx.selected_indices()),
449 has_selection_fn: Rc::new(move || s_has.count() > 0),
450 clear_fn: Rc::new(move || s_clr.clear()),
451 observe_fn: Rc::new(move |cb| s_obs.selection_signal().observe(move |_| cb())),
452 on_change_fn: Rc::new(move |change| match change {
453 DataChange::ItemsInserted { range } => {
454 s_chg.adjust_for_insert(range.start, range.end - range.start);
455 }
456 DataChange::ItemsRemoved { range } => {
457 s_chg.adjust_for_remove(range.start, range.end - range.start);
458 }
459 DataChange::ItemsMoved { from, to, count } => {
460 s_chg.adjust_for_move(*from, *to, *count);
461 }
462 DataChange::Reset => s_chg.clear(),
463 _ => {}
464 }),
465 // The index model has no stable identity to prune against on a
466 // bare version bump — tree structural adjustments stay no-ops here
467 // (the legacy behaviour).
468 prune_fn: Rc::new(|| {}),
469 prune_range_fn: Rc::new(move |count| {
470 let kept: Vec<usize> = s_range
471 .selected_indices()
472 .into_iter()
473 .filter(|&i| i < count)
474 .collect();
475 if kept.len() != s_range.count() {
476 s_range.select_indices(kept, false);
477 }
478 }),
479 }
480 }
481
482 /// Back the facade with a [`KeyedSelectionModel<K>`] plus the view's
483 /// index↔key mapping. `key_at(i)` is the key at visible index `i`, `len()`
484 /// the visible count (for Shift-range ordering and `selected_indices`), and
485 /// `contains_key(&k)` whether the *source* still holds the key (for
486 /// prune-on-remove — a collapsed-but-present tree node must NOT be pruned,
487 /// so this is supplied by the view, not derived from the visible window).
488 pub(crate) fn from_keyed<K: ItemKey>(
489 keyed: KeyedSelectionModel<K>,
490 key_at: Rc<dyn Fn(usize) -> Option<K>>,
491 len: Rc<dyn Fn() -> usize>,
492 contains_key: Rc<dyn Fn(&K) -> bool>,
493 ) -> Self {
494 let mode = keyed.mode();
495 Self {
496 mode,
497 is_selected: {
498 let (k, ka) = (keyed.clone(), key_at.clone());
499 Rc::new(move |i| ka(i).map(|key| k.is_selected(&key)).unwrap_or(false))
500 },
501 select_fn: {
502 let (k, ka) = (keyed.clone(), key_at.clone());
503 Rc::new(move |i| {
504 if let Some(key) = ka(i) {
505 k.select(key);
506 }
507 })
508 },
509 toggle_fn: {
510 let (k, ka) = (keyed.clone(), key_at.clone());
511 Rc::new(move |i| {
512 if let Some(key) = ka(i) {
513 k.toggle(key);
514 }
515 })
516 },
517 extend_fn: {
518 // O(visible count) per Shift-click / Shift-arrow gesture:
519 // builds the full visible key order every call rather than
520 // just the `[anchor_index..=target_index]` span
521 // `KeyedSelectionModel::extend_to` actually inserts.
522 //
523 // Narrowing this to the sub-range was considered and
524 // rejected as not cleanly possible without touching
525 // `teksilo-data`: `extend_to`'s "anchor scrolled out of
526 // view / evicted" fallback (single-select `target`) is
527 // detected by NOT finding `anchor` in the `ordered_keys`
528 // slice it's given, and the anchor is a private field with
529 // no public accessor (`KeyedSelectionModel::anchor` isn't
530 // exposed, and there's no `index_of_key` on the view's
531 // key↔index mapping this facade carries either). Without
532 // that, this closure has no way to know the anchor's
533 // current index — or whether it still HAS one — to bound a
534 // sub-range with, and a shadow copy of the anchor tracked
535 // here would drift from `KeyedSelectionModel`'s own
536 // whenever something else drives `select`/`toggle`
537 // (clearing or moving the anchor) — a duplicated-state
538 // correctness risk for a micro-optimization on a
539 // human-triggered, once-per-gesture path (not a hot loop).
540 let (k, ka, l) = (keyed.clone(), key_at.clone(), len.clone());
541 Rc::new(move |i| {
542 if let Some(target) = ka(i) {
543 let ordered: Vec<K> = (0..l()).filter_map(|j| ka(j)).collect();
544 k.extend_to(target, &ordered);
545 }
546 })
547 },
548 extend_additive_fn: {
549 // Same visible-order rebuild as `extend_fn` above, and the same
550 // reasoning for why it is not narrowed to the anchor's span.
551 let (k, ka, l) = (keyed.clone(), key_at.clone(), len.clone());
552 Rc::new(move |i| {
553 if let Some(target) = ka(i) {
554 let ordered: Vec<K> = (0..l()).filter_map(|j| ka(j)).collect();
555 k.extend_to_additive(target, &ordered);
556 }
557 })
558 },
559 select_all_fn: {
560 let (k, ka) = (keyed.clone(), key_at.clone());
561 Rc::new(move |count| {
562 let keys: Vec<K> = (0..count).filter_map(|i| ka(i)).collect();
563 k.select_keys(keys, false);
564 })
565 },
566 selected_indices_fn: {
567 let (k, ka, l) = (keyed.clone(), key_at.clone(), len.clone());
568 Rc::new(move || {
569 (0..l())
570 .filter(|&i| ka(i).map(|key| k.is_selected(&key)).unwrap_or(false))
571 .collect()
572 })
573 },
574 has_selection_fn: {
575 let k = keyed.clone();
576 Rc::new(move || k.count() > 0)
577 },
578 clear_fn: {
579 let k = keyed.clone();
580 Rc::new(move || k.clear())
581 },
582 observe_fn: {
583 let k = keyed.clone();
584 Rc::new(move |cb| k.selection_signal().observe(move |_| cb()))
585 },
586 on_change_fn: {
587 let (k, c) = (keyed.clone(), contains_key.clone());
588 Rc::new(move |change| match change {
589 // Keys are stable across inserts / moves; only removals and
590 // resets can orphan a selected key.
591 DataChange::ItemsRemoved { .. } | DataChange::Reset => {
592 k.prune_missing(|key| c(key));
593 }
594 _ => {}
595 })
596 },
597 prune_fn: {
598 let (k, c) = (keyed, contains_key);
599 Rc::new(move || k.prune_missing(|key| c(key)))
600 },
601 // Keys already survive a version bump via `prune_fn` above —
602 // there is no separate index range to clamp.
603 prune_range_fn: Rc::new(|_count: usize| {}),
604 }
605 }
606
607 pub(crate) fn mode(&self) -> SelectionMode {
608 self.mode
609 }
610 pub(crate) fn is_selected(&self, index: usize) -> bool {
611 (self.is_selected)(index)
612 }
613 pub(crate) fn select(&self, index: usize) {
614 (self.select_fn)(index)
615 }
616 pub(crate) fn toggle(&self, index: usize) {
617 (self.toggle_fn)(index)
618 }
619 pub(crate) fn extend_to(&self, index: usize) {
620 (self.extend_fn)(index)
621 }
622 pub(crate) fn extend_to_additive(&self, index: usize) {
623 (self.extend_additive_fn)(index)
624 }
625 pub(crate) fn select_all(&self, count: usize) {
626 (self.select_all_fn)(count)
627 }
628 pub(crate) fn selected_indices(&self) -> Vec<usize> {
629 (self.selected_indices_fn)()
630 }
631 /// Whether anything is selected. Prefer this over
632 /// `!selected_indices().is_empty()` when only the emptiness matters (e.g.
633 /// a per-frame paint gate) — it costs O(selected count), never
634 /// O(visible), for both the index and keyed backings.
635 pub(crate) fn has_selection(&self) -> bool {
636 (self.has_selection_fn)()
637 }
638 pub(crate) fn clear(&self) {
639 (self.clear_fn)()
640 }
641 /// Subscribe to selection changes (drives the view's rebuild). Owns the
642 /// returned handle for the subscription's lifetime.
643 pub(crate) fn observe_for_rebuild(&self, cb: impl Fn() + 'static) -> ObserverHandle {
644 (self.observe_fn)(Box::new(cb))
645 }
646 /// React to a source data change (index-shift for the index model, prune
647 /// for the keyed model).
648 pub(crate) fn on_data_change(&self, change: &DataChange) {
649 (self.on_change_fn)(change)
650 }
651 /// Prune orphaned keys (keyed model) — used by the tree views, which drive
652 /// off a version signal rather than a `DataChange`. No-op for the index
653 /// model.
654 pub(crate) fn prune(&self) {
655 (self.prune_fn)()
656 }
657 /// Drop selected indices `>= count` (index model) after a structural
658 /// change with no delta to shift them by — a version-signal-driven tree
659 /// view's only defence against a selection left pointing past the
660 /// shrunk end (it cannot re-land on the row it used to point at; only
661 /// `focused_index`'s `RowAnchor` tracks identity). No-op for the keyed
662 /// model, already fully reconciled by `prune`.
663 pub(crate) fn prune_out_of_range(&self, count: usize) {
664 (self.prune_range_fn)(count)
665 }
666}
667
668/// Resolves a set of the origin view's flat indices to a **removal thunk** at
669/// drag-start. Invoked at completion, the thunk removes exactly those rows from
670/// the source. Resolving eagerly (rather than re-reading flat indices at
671/// completion) keeps a Move correct even if the origin's flat indices reshuffle
672/// mid-drag — e.g. a `TreeView` spring-load auto-expand — since the stable keys
673/// were already captured. The source erasure supplies it.
674pub(crate) type SnapshotOutFn = Rc<dyn Fn(&[usize]) -> Box<dyn Fn()>>;
675
676/// Active drag-drop feedback a tree data view paints itself: a between-rows
677/// insertion line (Before/After) or a highlighted row (an into-container drop).
678///
679/// Shared by `TreeView` and `TreeTableView` so both render the same affordance
680/// for the same source verdict.
681/// A stable handle to a row in a data view.
682///
683/// Per-row event handlers (a chevron toggle, a click, an activation) are built
684/// once and then live as long as the row widget does, so capturing the flat
685/// index they were built at is fragile: expanding a branch above, applying a
686/// filter, or sorting shifts every index below, and the stale handler would act
687/// on whatever row moved into that slot.
688///
689/// A `RowAnchor` closes over the row's **source-owned identity** instead and
690/// resolves the row's *current* position on demand. The key never surfaces in
691/// the anchor's type — it is captured inside the resolver, so views stay
692/// key-agnostic ([`TreeSource`](crate::tree_source::TreeSource) and
693/// [`ListSource`](crate::list_source::ListSource) both erase it).
694///
695/// Sources without identity (a bare `ListModel`, or any source that leaves
696/// `key_at` at its `None` default) get a fixed anchor that always reports the
697/// index it was built with — no worse than capturing the index directly.
698///
699/// A bare `ListModel` has no identity to offer (a `Vec` row *is* its position),
700/// so anchors over one are fixed. `SortFilterListModel` keys rows by their
701/// **source index**, which no sort/filter reprojection renumbers — so anchors
702/// over a projection do track their row across a filter change, which is the
703/// flat fragility in practice. They can still mis-resolve inside the window
704/// between an *upstream* insert/remove and the rebuild it schedules, since that
705/// does renumber source indices; no worse than the captured index they replace.
706/// The tree sources all carry real identity.
707///
708/// **Precondition: keys must be unique.** Resolution falls back to a lookup by
709/// key, which returns the *first* match, so a source handing out duplicate keys
710/// would silently redirect an anchor onto a different row — the very failure
711/// this type exists to prevent.
712#[derive(Clone)]
713pub struct RowAnchor {
714 resolve: Rc<dyn Fn() -> Option<usize>>,
715}
716
717impl RowAnchor {
718 /// Build an identity-backed anchor from a resolver.
719 pub(crate) fn new(resolve: Rc<dyn Fn() -> Option<usize>>) -> Self {
720 Self { resolve }
721 }
722
723 /// An anchor for a source with no identity: always reports `index`.
724 pub(crate) fn fixed(index: usize) -> Self {
725 Self {
726 resolve: Rc::new(move || Some(index)),
727 }
728 }
729
730 /// The row's current flat index, or `None` if it no longer exists in the
731 /// source (it was deleted, or filtered away).
732 pub fn index(&self) -> Option<usize> {
733 (self.resolve)()
734 }
735
736 /// Whether the row still exists.
737 pub fn is_live(&self) -> bool {
738 self.index().is_some()
739 }
740}
741
742impl std::fmt::Debug for RowAnchor {
743 /// Deliberately does NOT resolve: the resolver reads the source's
744 /// interior-mutable state, so a `{:?}` from inside code already holding a
745 /// borrow (a `set_source` closure, a reorder callback, a debugger's
746 /// pretty-printer) would panic on a `RefCell` conflict.
747 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
748 f.write_str("RowAnchor(..)")
749 }
750}
751
752/// Keep an open cell editor pointing at the row it was opened on.
753///
754/// `editing_cell` is a `(row, col)` pair that outlives rebuilds, so rows
755/// appearing or vanishing above an open editor would slide it onto a different
756/// row. The anchor is captured the first time an open editor is seen and
757/// re-resolved on every later rebuild: the row index is rewritten when it moved,
758/// and the editor closes outright when its row is gone — better than silently
759/// editing whoever took the slot.
760///
761/// Called from each body pane's `build`, which is the only place that sees both
762/// an editing change and a data change. It can therefore write `editing_cell`
763/// while that pane is building; the write is idempotent and converges in one
764/// extra pass (the next reconcile finds `cur == row` and writes nothing), which
765/// `an_editing_reconcile_converges_in_one_pass` pins.
766pub(crate) fn reconcile_editing_row(
767 editing_cell: &teksilo_core::signal::Signal<Option<(usize, usize)>>,
768 slot: &Rc<std::cell::RefCell<Option<RowAnchor>>>,
769 anchor_of: &dyn Fn(usize) -> RowAnchor,
770) {
771 let Some((row, col)) = editing_cell.get() else {
772 *slot.borrow_mut() = None;
773 return;
774 };
775 let existing = slot.borrow().clone();
776 match existing {
777 None => *slot.borrow_mut() = Some(anchor_of(row)),
778 Some(anchor) => match anchor.index() {
779 Some(cur) if cur != row => editing_cell.set(Some((cur, col))),
780 Some(_) => {}
781 None => {
782 editing_cell.set(None);
783 *slot.borrow_mut() = None;
784 }
785 },
786 }
787}
788
789/// Tint for the "drop into this container" row highlight. Defined once so the
790/// `DropFeedback` handed to the framework and the widget's own paint cannot
791/// drift into two different colors on the same row.
792pub(crate) fn drop_into_tint() -> teksilo_tokens::Color {
793 teksilo_tokens::Color::from_rgba(0.25, 0.47, 0.85, 0.25)
794}
795
796#[derive(Clone, Copy, PartialEq, Debug)]
797pub(crate) enum DropViz {
798 /// Horizontal insertion line at `y`, spanning `width`, indented by
799 /// `depth` tree levels — the level the dropped row lands at.
800 Line { y: f32, width: f32, depth: usize },
801 /// Highlighted target row `[top, top + height]`, spanning `width`,
802 /// indented by the target's own `depth` — the "drop into this folder"
803 /// affordance.
804 Rect {
805 top: f32,
806 height: f32,
807 width: f32,
808 depth: usize,
809 },
810}
811
812/// The reusable export / foreign-drop machinery shared by all five data views:
813/// the config fields, the drag-start payload build (selection set already
814/// resolved by the caller), the foreign-receive sugar, and the `on_drag_ended`
815/// move-out completion. Each view holds ONE of these instead of duplicating the
816/// logic five ways (the drift that a code review caught). See
817/// [docs/drag-and-drop.md §12](https://github.com/ferntech-eu/teksilo/blob/main/docs/drag-and-drop.md).
818pub(crate) struct RowExport<T: 'static> {
819 /// `Some` once `.exportable(..)` was called; the transfer mode also drives
820 /// the move-out completion.
821 pub(crate) mode: Option<DragTransferMode>,
822 /// Clones `&T` → `T` for the payload (set by `.exportable`/`.export_external`,
823 /// each `where T: Clone`, so the view constructor stays unconstrained).
824 #[allow(clippy::type_complexity)]
825 pub(crate) clone_item_fn: Option<Rc<dyn Fn(&T) -> T>>,
826 /// Builds MIME reps of the dragged items for OS / `DropZone` export.
827 #[allow(clippy::type_complexity)]
828 pub(crate) export_mime_fn: Option<Rc<dyn Fn(&[T]) -> Vec<(String, Vec<u8>)>>>,
829 /// App override for removing rows moved out to a foreign target.
830 #[allow(clippy::type_complexity)]
831 pub(crate) on_rows_transferred_out: Option<Rc<dyn Fn(&[usize], &mut EventContext)>>,
832 /// Accept exported rows from a different view/source (zero-custom-source).
833 pub(crate) accept_foreign_rows: bool,
834 /// Handler for rows accepted via `accept_foreign_rows`.
835 #[allow(clippy::type_complexity)]
836 pub(crate) on_rows_received: Option<Rc<dyn Fn(Vec<T>, usize, &mut EventContext)>>,
837 /// Set by the view's own `on_drop` when it applied a same-view reorder, so
838 /// the completion skips the move-out (already applied). The TabBar pattern.
839 pub(crate) self_reorder_flag: Rc<Cell<bool>>,
840 /// The rows carried by the in-flight drag (for the app move-out callback).
841 dragged_rows: Rc<RefCell<Vec<usize>>>,
842 /// Stable-key removal thunk for the default move-out, resolved at drag-start.
843 #[allow(clippy::type_complexity)]
844 removal: Rc<RefCell<Option<Box<dyn Fn()>>>>,
845}
846
847impl<T: 'static> Clone for RowExport<T> {
848 // Hand-written (not derived) so cloning does NOT require `T: Clone` — every
849 // field is an `Rc` / `Copy`, so a clone shares the same drag stash + flags,
850 // which is exactly what the per-row drag closure needs.
851 fn clone(&self) -> Self {
852 Self {
853 mode: self.mode,
854 clone_item_fn: self.clone_item_fn.clone(),
855 export_mime_fn: self.export_mime_fn.clone(),
856 on_rows_transferred_out: self.on_rows_transferred_out.clone(),
857 accept_foreign_rows: self.accept_foreign_rows,
858 on_rows_received: self.on_rows_received.clone(),
859 self_reorder_flag: self.self_reorder_flag.clone(),
860 dragged_rows: self.dragged_rows.clone(),
861 removal: self.removal.clone(),
862 }
863 }
864}
865
866impl<T: 'static> Default for RowExport<T> {
867 fn default() -> Self {
868 Self {
869 mode: None,
870 clone_item_fn: None,
871 export_mime_fn: None,
872 on_rows_transferred_out: None,
873 accept_foreign_rows: false,
874 on_rows_received: None,
875 self_reorder_flag: Rc::new(Cell::new(false)),
876 dragged_rows: Rc::new(RefCell::new(Vec::new())),
877 removal: Rc::new(RefCell::new(None)),
878 }
879 }
880}
881
882impl<T: 'static> RowExport<T> {
883 /// `.exportable(mode)` — carry item clones; `where T: Clone` at the call.
884 pub(crate) fn set_exportable(&mut self, mode: DragTransferMode)
885 where
886 T: Clone,
887 {
888 self.mode = Some(mode);
889 if self.clone_item_fn.is_none() {
890 self.clone_item_fn = Some(Rc::new(|t: &T| t.clone()));
891 }
892 }
893
894 /// `.export_external(f)` — attach MIME; implies exportable.
895 pub(crate) fn set_export_external(
896 &mut self,
897 f: impl Fn(&[T]) -> Vec<(String, Vec<u8>)> + 'static,
898 ) where
899 T: Clone,
900 {
901 if self.clone_item_fn.is_none() {
902 self.clone_item_fn = Some(Rc::new(|t: &T| t.clone()));
903 }
904 if self.mode.is_none() {
905 self.mode = Some(DragTransferMode::default());
906 }
907 self.export_mime_fn = Some(Rc::new(f));
908 }
909
910 pub(crate) fn set_on_rows_transferred_out(
911 &mut self,
912 f: impl Fn(&[usize], &mut EventContext) + 'static,
913 ) {
914 self.on_rows_transferred_out = Some(Rc::new(f));
915 }
916
917 pub(crate) fn set_on_rows_received(
918 &mut self,
919 f: impl Fn(Vec<T>, usize, &mut EventContext) + 'static,
920 ) {
921 self.on_rows_received = Some(Rc::new(f));
922 }
923
924 /// Rows are a drag source when the view reorders OR exports.
925 pub(crate) fn is_drag_source(&self, reorderable: bool) -> bool {
926 reorderable || self.mode.is_some()
927 }
928
929 /// The view is a drop target when it reorders OR accepts foreign rows.
930 pub(crate) fn is_drop_target(&self, reorderable: bool) -> bool {
931 reorderable || self.accept_foreign_rows
932 }
933
934 /// Build the drag payload for the (already selection-resolved) `rows`. Drops
935 /// any non-resident row (a lazy `Loading` row `read` can't serve) so `rows`
936 /// and `items` stay index-aligned and a Move never deletes a row whose data
937 /// wasn't transferred. Attaches MIME, and stashes the rows + a stable-key
938 /// removal thunk for the completion.
939 ///
940 /// `None` when no row survives the residency filter (an all-`Loading`
941 /// selection): the caller must refuse the drag rather than float an empty
942 /// payload nothing can accept.
943 pub(crate) fn build_payload(
944 &self,
945 source: ViewId,
946 mut rows: Vec<usize>,
947 read: &dyn Fn(usize, &mut dyn FnMut(&T)) -> bool,
948 snapshot_out: &SnapshotOutFn,
949 ) -> Option<DragPayload> {
950 let items: Option<Vec<T>> = if let Some(cf) = self.clone_item_fn.as_ref() {
951 let mut out = Vec::with_capacity(rows.len());
952 rows.retain(|&r| {
953 let mut got = None;
954 read(r, &mut |t| got = Some(cf(t)));
955 match got {
956 Some(v) => {
957 out.push(v);
958 true
959 }
960 None => false,
961 }
962 });
963 Some(out)
964 } else {
965 None
966 };
967 if rows.is_empty() {
968 return None;
969 }
970 let mime_pairs: Vec<(String, Vec<u8>)> =
971 match (self.export_mime_fn.as_ref(), items.as_ref()) {
972 (Some(mf), Some(its)) => mf(its),
973 _ => Vec::new(),
974 };
975 let mut payload = DragPayload::typed(RowDragData::<T> {
976 source,
977 rows: rows.clone(),
978 items,
979 });
980 let has_mime = !mime_pairs.is_empty();
981 for (mime, bytes) in mime_pairs {
982 payload = payload.with_mime(&mime, bytes);
983 }
984 if has_mime {
985 payload.enrich_external_from_mime();
986 }
987 *self.removal.borrow_mut() = Some((snapshot_out)(&rows));
988 *self.dragged_rows.borrow_mut() = rows;
989 Some(payload)
990 }
991
992 /// Whether a **foreign** exported payload would be accepted here — for the
993 /// hover affordance. (Same-view / reorder-only payloads return `false`.)
994 pub(crate) fn accepts_foreign_export(&self, payload: &DragPayload, source: ViewId) -> bool {
995 self.accept_foreign_rows
996 && self.on_rows_received.is_some()
997 && payload
998 .get_typed::<RowDragData<T>>()
999 .is_some_and(|rd| rd.source != source && rd.is_export())
1000 }
1001
1002 /// Foreign-receive sugar for a view's `on_drop`. Peeks before taking, so a
1003 /// non-matching payload is left intact for any further fallback.
1004 pub(crate) fn foreign_receive(
1005 &self,
1006 payload: &mut DragPayload,
1007 source: ViewId,
1008 insertion: usize,
1009 ctx: &mut EventContext,
1010 ) -> bool {
1011 if self.accepts_foreign_export(payload, source)
1012 && let Some(cb) = self.on_rows_received.as_ref()
1013 && let Some(rd) = payload.take_typed::<RowDragData<T>>()
1014 && let Some(items) = rd.items
1015 {
1016 cb(items, insertion, ctx);
1017 return true;
1018 }
1019 false
1020 }
1021
1022 /// The view's own `on_drop` calls this after applying a genuine SAME-VIEW
1023 /// reorder, so the completion knows the change was already applied.
1024 pub(crate) fn note_self_reorder(&self) {
1025 self.self_reorder_flag.set(true);
1026 }
1027
1028 /// Install the `on_drag_ended` move-out completion. A same-view reorder set
1029 /// `self_reorder_flag` (skipped here); on `Move` + accepted-elsewhere the
1030 /// origin rows are removed via the app override (delivered **descending** so
1031 /// index-by-index removal stays valid) or the stable-key removal thunk.
1032 pub(crate) fn install_completion(&self, handlers: HandlerSet) -> HandlerSet {
1033 let Some(mode) = self.mode else {
1034 return handlers;
1035 };
1036 let flag = self.self_reorder_flag.clone();
1037 let dragged = self.dragged_rows.clone();
1038 let removal = self.removal.clone();
1039 let on_out = self.on_rows_transferred_out.clone();
1040 handlers.on_drag_ended(move |outcome, ctx| {
1041 let handled_by_us = flag.replace(false);
1042 let rows = std::mem::take(&mut *dragged.borrow_mut());
1043 let thunk = removal.borrow_mut().take();
1044 if handled_by_us {
1045 return;
1046 }
1047 let accepted_elsewhere = matches!(
1048 outcome,
1049 DropOutcome::InApp { accepted: true } | DropOutcome::OsMove
1050 );
1051 if mode != DragTransferMode::Move || !accepted_elsewhere || rows.is_empty() {
1052 return;
1053 }
1054 if let Some(cb) = on_out.as_ref() {
1055 let mut desc = rows;
1056 desc.sort_unstable();
1057 desc.reverse();
1058 cb(&desc, ctx);
1059 } else if let Some(thunk) = thunk {
1060 thunk();
1061 }
1062 })
1063 }
1064}
1065
1066/// A layout- and accessibility-transparent wrapper whose only job is to own a
1067/// drag on a node that **strictly encloses** the node whose gesture arena takes
1068/// the press.
1069///
1070/// # Why the drag cannot live on the pressed node
1071///
1072/// [`DragActivation`](teksilo_tokens::DragActivation) — the policy that holds a
1073/// touch drag back until a long press so the scroll underneath can win first —
1074/// is read on two paths, and the node that *captures* the press is on neither
1075/// of them unless it is **already** the sequence's pan claimant:
1076///
1077/// * the **ancestor walk** of the tree's sequence enrolment, through
1078/// `PointerSequence::enrol_drag`;
1079/// * `PointerSequence::defer_own_drag`, the dual-role arm, which attaches the
1080/// activation to a member the node already holds — and which refuses anything
1081/// but a live `MemberRole::Pan`. A `SceneView` is such a node. A **row** is
1082/// not: the claim is the scrollable's, several levels out.
1083///
1084/// So a row that carries both its tap and its reorder `on_drag` is enrolled by
1085/// the captured branch's plain `enrol`, which consults no activation at all. It
1086/// latches that drag at `drag_slop` on the first sample past 18 dp, decides the
1087/// arbitration, and the scrollable's `PanClaim` — which needs 36 dp — is never
1088/// even evaluated. The view then neither scrolls nor reorders: the drag won and,
1089/// for a marquee that declines a press on a tile, did nothing. That is the
1090/// `list row · touch` row of `crates/teksilo-core/tests/arbitration_matrix.rs`,
1091/// read as a defect rather than as a rule.
1092///
1093/// Hanging the drag one level out fixes both halves at once, with no change to
1094/// the framework: the pressed node has no drag, so the walk reaches this
1095/// wrapper and enrols it *with* its activation. A precise pointer resolves
1096/// `Auto` to `Immediate` and latches at the same 5 dp it always did; a direct
1097/// pointer resolves it to `AfterLongPress` and the pan wins unless the contact
1098/// holds still.
1099///
1100/// # What must be true of the node inside
1101///
1102/// It must have a gesture arena of its own, or nothing captures the press and
1103/// the enrolment walk never starts — the drag would then compete by no path at
1104/// all. [`press_absorber`] is the no-op tap that guarantees one, for a row
1105/// whose application wired no activation. This is the `primitives::dead_zone`
1106/// precedent: a structural rule plus an absorber that makes the structure real.
1107///
1108/// Transparent in every other respect: it forwards the child's whole
1109/// [`LayoutResponse`](teksilo_core::widget::LayoutResponse) (grow weight,
1110/// shrink weight and compression floor, not
1111/// just the size), places the child at its own bounds, and emits no
1112/// accessibility properties, so the walker prunes it: a reorderable view's
1113/// accessibility tree has the same *shape* as the same view without the
1114/// wrapper, which is what
1115/// `a_reorderable_view_has_the_same_accessibility_shape` asserts.
1116pub(crate) struct DragSurface {
1117 child: Option<WidgetId>,
1118}
1119
1120impl DragSurface {
1121 /// Wrap a pre-registered widget by id.
1122 pub(crate) fn new(child: WidgetId) -> Self {
1123 Self { child: Some(child) }
1124 }
1125}
1126
1127impl std::fmt::Debug for DragSurface {
1128 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1129 f.debug_struct("DragSurface").finish()
1130 }
1131}
1132
1133impl Widget for DragSurface {
1134 fn build(&mut self, _ctx: &mut BuildContext) -> Vec<WidgetId> {
1135 self.child.into_iter().collect()
1136 }
1137
1138 fn layout_response(
1139 &self,
1140 proposal: teksilo_canvas::SizeProposal,
1141 ctx: &teksilo_core::widget::LayoutContext,
1142 ) -> teksilo_core::widget::LayoutResponse {
1143 self.child
1144 .and_then(|id| ctx.child_layout_response(id, proposal))
1145 .unwrap_or_else(|| proposal.resolve(0.0, 0.0).into())
1146 }
1147
1148 fn place_children(
1149 &self,
1150 bounds: teksilo_canvas::Rect,
1151 _proposal: teksilo_canvas::SizeProposal,
1152 children: &mut [teksilo_core::widget::WidgetPlacement],
1153 _ctx: &teksilo_core::widget::LayoutContext,
1154 ) {
1155 for child in children.iter_mut() {
1156 child.origin = bounds.origin();
1157 child.size = bounds.size();
1158 }
1159 }
1160
1161 fn children(&self) -> Vec<WidgetId> {
1162 self.child.into_iter().collect()
1163 }
1164}
1165
1166/// The `HandlerSet` a row's or tile's [`DragSurface`] carries, before its own
1167/// `on_drag` is chained onto it: the declaration that **the hold inside this
1168/// wrapper belongs to that drag**.
1169///
1170/// A19's ruling is that where a row has both a reorder and a context menu the
1171/// reorder wins the hold, and the menu moves to an overflow affordance plus
1172/// Secondary / `Shift+F10` / the AccessKit `ShowContextMenu` action. The
1173/// framework enforces "one hold, one meaning" implicitly, from the deferral on
1174/// the drag member — but that rule is keyed on the **node**, because a deferred
1175/// grab on some enclosing container is not a claim on the holds of everything
1176/// inside it (a `SceneView` that marquees after a hold must not thereby take the
1177/// touch context menu away from every widget placed in it; a finger has no
1178/// secondary button, so the hold is the only route those have).
1179///
1180/// A [`DragSurface`] is the one place that implicit rule reads one node too far
1181/// out. The wrapper is not an enclosing container: it is layout-, hit- and
1182/// accessibility-transparent, its subtree is exactly one row, and the drag it
1183/// carries is that row's own. So it says so, with the explicit subtree-wide
1184/// declaration [`LongPressRole::DragHandle`](teksilo_core::LongPressRole::DragHandle),
1185/// which `WidgetTree::long_press_is_a_grab` walks from the pressed node to the
1186/// root.
1187///
1188/// **It takes a hold only from a direct pointer**, because a hold is a
1189/// drag-start route only where a drag waits for one — which is the finger and
1190/// the pen. A mouse latches this same reorder on travel, at `drag_slop`, with no
1191/// deadline in it, so its hold is spent on nothing and stays the application's:
1192/// a row's own `on_long_press` still fires under a mouse however this wrapper is
1193/// declared. That gate lives in `long_press_is_a_grab`, not here, so every
1194/// `DragHandle` declaration gets it.
1195///
1196/// Deliberately **not** applied to the body-pane `DragSurface` that hosts
1197/// `GridView`'s marquee. That one *is* an enclosing container — its subtree is
1198/// every tile in the grid — and declaring it there would take the touch context
1199/// menu away from all of them, which is the defect this distinction exists to
1200/// avoid.
1201pub(crate) fn row_grab_surface() -> HandlerSet {
1202 HandlerSet::new().long_press_role(teksilo_core::LongPressRole::DragHandle)
1203}
1204
1205/// The no-op tap that guarantees a node its own gesture arena.
1206///
1207/// Merged onto every row, tile or body pane a [`DragSurface`] encloses. Without
1208/// an arena nothing captures the press, and the walk that enrols the surface's
1209/// drag never runs — so the drag would compete by no path at all.
1210///
1211/// `GridView` merges it onto every tile whether or not one encloses it, and for
1212/// a second reason: the grid's body pane carries an absorber too, so a tile with
1213/// no arena of its own leaves the pane holding the press — and a release
1214/// dispatched to the captor and bubbled target→root never reaches a tile
1215/// *beneath* it. A plain selectable grid lost both its finger tap and, on a
1216/// mouse, the release that collapses a multi-selection that way. The four row
1217/// views have no pane-level absorber, so a plain row there is merely arena-less,
1218/// which costs it nothing *so long as nothing above it competes for the press*.
1219/// An application that wraps such a view in anything tappable puts an arena
1220/// there itself, and the row loses its release the same way — see
1221/// `docs/data-view-touch.md`'s second known limit.
1222///
1223/// Applied unconditionally rather than only where the node would otherwise have
1224/// none: an extra no-op tap in an arena that already has one is inert (the
1225/// arena builds one `TapRecognizer` however many closures are installed), while
1226/// a condition enumerating the handlers a pane happens to attach today would
1227/// silently stop guaranteeing anything the next time one is added. It absorbs
1228/// nothing and answers nothing — the recognizer's existence is the whole point.
1229pub(crate) fn press_absorber() -> HandlerSet {
1230 HandlerSet::new().on_tap(|_tap, _ctx| {})
1231}
1232
1233/// Whether the primary release being dispatched still completes the press it
1234/// began — the question every **release-time commitment** in a data view's row
1235/// body has to ask before committing.
1236///
1237/// A row body commits two things on release: the deferred collapse of a
1238/// multi-selection ([`deferred_select::on_up`]), and — in `TreeView` — the
1239/// expansion toggle of a branch row. Both are correct for a click and wrong for
1240/// a finger that was scrolling, so both are gated on this.
1241///
1242/// It answers `false` in the two ways a row loses the press without a cancel it
1243/// can see:
1244///
1245/// * **a peer claimed the contact.** The scrollable above the row won the
1246/// arbitration with its `PanClaim` and the press is now a scroll. The row
1247/// cannot rely on being told: it is enrolled as a sequence member only when
1248/// it carries a drag (`reorderable` / `exportable`), and even then the
1249/// loser's `CancelReason::PeerClaimed` is *member*-level — deliberately
1250/// leaving the pointer alive so its winner can finish — so the `PointerUp`
1251/// still arrives here either way. `WidgetTree::update_press` ends the press
1252/// record on that claim, which is the fact this reads.
1253/// * **the pointer left the press's tap boundary.** The same predicate that
1254/// fails the tap and fires `cancel_taps`, so a release-time commit is
1255/// abandoned exactly when the activation is.
1256///
1257/// It stays `true` through a press-feedback delay — a finger that lands and
1258/// lifts before the delay elapses has still clicked — because the delay
1259/// withholds the *visual*, not the press.
1260///
1261/// The older reasoning at these sites, that "an active drag consumes
1262/// `PointerUp`", covers only a **drag**: a won pan claim is not an
1263/// `active_drag`, so the release is not routed to `handle_drag_drop` and does
1264/// reach the row.
1265pub(crate) fn release_completes_the_press(ctx: &teksilo_core::widget::EventContext) -> bool {
1266 ctx.press_is_inside()
1267}
1268
1269/// Shared selection-on-press/release logic for a data-view row, and the type
1270/// its two calls share.
1271///
1272/// # What a press decides, and when the decision is applied
1273///
1274/// A **precise** pointer (mouse) still selects on press, exactly as it always
1275/// has — that is the click convention on every desktop, and a press that never
1276/// becomes anything else is still a click. The one thing it defers is the
1277/// *collapse* of an existing multi-selection: pressing an already-selected row
1278/// keeps the whole set so it can be dragged, and collapses to the pressed row
1279/// only on a release that still belongs to it.
1280///
1281/// A **direct** pointer (a finger, a pen) defers the *whole* decision to the
1282/// release. A press from a finger is not yet a click: the same contact is the
1283/// opening sample of a scroll, and a scrolling finger must leave the selection
1284/// exactly as it found it. No release-time predicate can rescue a selection
1285/// already written on `PointerDown`, so the write itself moves to the release —
1286/// and a release the row has lost (a won `PanClaim`, a press that wandered out
1287/// of the tap boundary) is refused by
1288/// [`release_completes_the_press`], which is what makes a pan commit nothing.
1289///
1290/// The nav cursor travels with the selection rather than with the press, so the
1291/// arrow-key origin and the selection can never point at different rows: both
1292/// calls report whether the caller should move it *now*.
1293pub(crate) mod deferred_select {
1294 use std::cell::Cell;
1295 use std::rc::Rc;
1296
1297 use teksilo_core::event::Modifiers;
1298 use teksilo_core::widget::EventContext;
1299
1300 use super::RowSelection;
1301
1302 /// The selection change a press decided but has not applied yet.
1303 ///
1304 /// `Collapse` is the one a mouse defers; a direct pointer defers whichever
1305 /// of the three its modifiers chose.
1306 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1307 pub(crate) enum PendingSelect {
1308 /// Replace the selection with this row — a plain click, and the
1309 /// collapse of a multi-selection the press kept alive.
1310 Collapse,
1311 /// Accelerator-click: add or remove this row.
1312 Toggle,
1313 /// Shift-click: extend the range from the anchor.
1314 Extend,
1315 }
1316
1317 /// The per-row cell the two calls share. One per realized row.
1318 pub(crate) type Pending = Rc<Cell<Option<PendingSelect>>>;
1319
1320 /// A fresh, empty pending cell.
1321 pub(crate) fn pending_cell() -> Pending {
1322 Rc::new(Cell::new(None))
1323 }
1324
1325 fn apply(sel: &RowSelection, index: usize, what: PendingSelect) {
1326 match what {
1327 PendingSelect::Collapse => sel.select(index),
1328 PendingSelect::Toggle => sel.toggle(index),
1329 PendingSelect::Extend => sel.extend_to(index),
1330 }
1331 }
1332
1333 /// Handle a primary `PointerDown` on row `index`.
1334 ///
1335 /// Returns whether the caller should move its nav cursor to `index` now:
1336 /// `false` when an interactive child claimed the press (nothing happened
1337 /// here at all), and `false` for a direct pointer, whose decision — cursor
1338 /// included — belongs to the release.
1339 pub(crate) fn on_down(
1340 sel: &RowSelection,
1341 index: usize,
1342 modifiers: Modifiers,
1343 pending: &Pending,
1344 ctx: &mut EventContext,
1345 ) -> bool {
1346 if ctx.press_claimed_by_interactive_child() {
1347 pending.set(None);
1348 return false;
1349 }
1350 // The accelerator-click that adds one row to a discontiguous selection:
1351 // Ctrl+click on Windows and Linux, ⌘-click on macOS — where ⌃-click is
1352 // the secondary click and would open a context menu instead.
1353 let what = if modifiers.command() {
1354 PendingSelect::Toggle
1355 } else if modifiers.shift() {
1356 PendingSelect::Extend
1357 } else {
1358 PendingSelect::Collapse
1359 };
1360 if ctx.pointer_kind().is_direct() {
1361 // A finger's press is not yet a click — see the module header.
1362 pending.set(Some(what));
1363 return false;
1364 }
1365 if what == PendingSelect::Collapse && sel.is_selected(index) {
1366 // Grab-the-set-and-drag: keep the multi-selection alive for the
1367 // press, collapse it on a release without a drag.
1368 pending.set(Some(what));
1369 } else {
1370 apply(sel, index, what);
1371 pending.set(None);
1372 }
1373 true
1374 }
1375
1376 /// Handle a primary `PointerUp` on row `index`, applying whatever the press
1377 /// deferred.
1378 ///
1379 /// Returns whether the caller should move its nav cursor to `index` now —
1380 /// true exactly when a deferred decision was applied.
1381 ///
1382 /// Refuses when the release belongs to an interactive child, and when the
1383 /// press it would complete is no longer this row's
1384 /// ([`release_completes_the_press`](super::release_completes_the_press)).
1385 pub(crate) fn on_up(
1386 sel: &RowSelection,
1387 index: usize,
1388 pending: &Pending,
1389 ctx: &mut EventContext,
1390 ) -> bool {
1391 if ctx.press_claimed_by_interactive_child() {
1392 return false;
1393 }
1394 if !super::release_completes_the_press(ctx) {
1395 // The deferred decision is abandoned, not postponed: clear the flag
1396 // so it cannot fire on some later release this row does own.
1397 pending.set(None);
1398 return false;
1399 }
1400 match pending.replace(None) {
1401 Some(what) => {
1402 apply(sel, index, what);
1403 true
1404 }
1405 None => false,
1406 }
1407 }
1408}
1409
1410#[cfg(test)]
1411mod payload_tests {
1412 use super::*;
1413
1414 fn noop_snapshot() -> SnapshotOutFn {
1415 Rc::new(|_: &[usize]| Box::new(|| {}) as Box<dyn Fn()>)
1416 }
1417
1418 #[test]
1419 fn an_all_unresident_selection_refuses_the_drag() {
1420 // Every dragged row is still `Loading`: the residency filter empties
1421 // the set, and the drag must be refused outright — a floating payload
1422 // with no rows and no items would remove nothing on a Move and offer
1423 // nothing to a receiver.
1424 let mut export = RowExport::<u64>::default();
1425 export.set_exportable(DragTransferMode::Move);
1426 let read = |_: usize, _: &mut dyn FnMut(&u64)| false;
1427 let payload = export.build_payload(
1428 ViewId::next(ViewKind::List),
1429 vec![0, 1, 2],
1430 &read,
1431 &noop_snapshot(),
1432 );
1433 assert!(payload.is_none());
1434 }
1435
1436 #[test]
1437 fn a_partially_resident_selection_carries_only_the_resident_rows() {
1438 let mut export = RowExport::<u64>::default();
1439 export.set_exportable(DragTransferMode::Copy);
1440 // Row 1 is unresident; rows 0 and 2 resolve.
1441 let read = |i: usize, f: &mut dyn FnMut(&u64)| {
1442 if i == 1 {
1443 return false;
1444 }
1445 f(&(i as u64 * 10));
1446 true
1447 };
1448 let payload = export
1449 .build_payload(
1450 ViewId::next(ViewKind::List),
1451 vec![0, 1, 2],
1452 &read,
1453 &noop_snapshot(),
1454 )
1455 .expect("two rows are resident");
1456 let rd = payload.get_typed::<RowDragData<u64>>().unwrap();
1457 assert_eq!(rd.rows, vec![0, 2]);
1458 assert_eq!(rd.items.as_deref(), Some(&[0, 20][..]));
1459 }
1460}
1461
1462#[cfg(test)]
1463mod drag_surface_tests {
1464 use super::*;
1465 use crate::primitives::{FixedSize, HStack, Shrinkable};
1466 use teksilo_canvas::SizeProposal;
1467 use teksilo_core::widget_tree::WidgetTree;
1468
1469 /// The wrapper's own doc says it forwards the child's *whole*
1470 /// `LayoutResponse`, not just the size. Flattening it to a bare `Size` makes
1471 /// the surface rigid, which over-constrains any tight container it sits in —
1472 /// the failure `primitives::dead_zone` was written to avoid and
1473 /// `primitives::touch_target::tests::the_wrapper_forwards_its_child_shrink_weight`
1474 /// already pins for the other wrapper of this shape. Shrink is the
1475 /// discriminating field: a rigid surface refuses to compress at all, so its
1476 /// width stays at the child's ideal instead of yielding to the deficit.
1477 #[test]
1478 fn the_drag_surface_forwards_its_child_shrink_weight() {
1479 let mut tree = WidgetTree::new();
1480 let inner = tree.add(
1481 Shrinkable::new()
1482 .min_width(20.0)
1483 .child(FixedSize::new().width(100.0).height(20.0)),
1484 );
1485 let slot = tree.add(DragSurface::new(inner));
1486 let rigid = tree.add(FixedSize::new().width(100.0).height(20.0));
1487 tree.add(HStack::new().child(rigid).child(slot));
1488 tree.layout(SizeProposal::exact(120.0, 20.0));
1489 let w = tree.bounds(slot).width;
1490 assert!(
1491 w < 100.0,
1492 "the DragSurface must forward the child's shrink weight (width was {w})"
1493 );
1494 }
1495}