abstracttui 0.6.0

A reactive, compositor-grade terminal UI engine: fine-grained signals, layered rendering with damage tracking, images (kitty/iTerm2/sixel/mosaic), software-rasterized 3D (GLB), themes and animation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
//! List: virtualized, selectable, keyboard+mouse vertical list.
//!
//! SELECTION vs ACTIVATION (0250 ruling, recorded in
//! reviews/study/platform-on-appkits.md §"The 0250 ruling"): selection
//! FOLLOWS MOVEMENT — arrows/Home/End/Page keys/click move it and
//! `on_select` is the selection-changed NOTIFICATION; activation is the
//! EXPLICIT "user chose this row" event — `on_activate` fires on Enter
//! (always), on Space (List has no toggle meaning, so Space aliases
//! Enter here), and on a click on the ALREADY-selected row. Never wire
//! commitment, navigation, or destruction to `on_select`.
//!
//! Double-click (app-kits 0535): by default List's click-on-selected
//! rule SUBSUMES it — click 1 selects, click 2 on the already-selected
//! row activates via [`List::on_activate`], timing-free (the picker
//! gesture, deliberately broader than a timed double-click). For
//! browsing surfaces that need strict SGR double-click (open-on-double,
//! slow re-click only re-selects), bind [`List::on_row_double_click`]
//! instead — it fires only when `EventCtx::click_count() >= 2` on the
//! row body and takes precedence over `on_activate` for that press.
//! `Table` uses the same timed convention.
//!
//! Row accessories (field-agora 0810): optional trailing column via
//! [`List::row_accessory`] + [`List::on_accessory_click`]. The engine
//! owns body/accessory/scrollbar column widths — no app-side X math.
//! Accessory clicks do not change selection; the scrollbar column is the
//! bar's (grab the thumb, or press bare track to teleport — the shared
//! gesture in `widgets::scrollbar`), never the row
//! beside it. Rich labels ride
//! [`List::rich_items`] (styled spans on the body column only).
//!
//! Row context actions are a separate, non-selecting gesture:
//! [`List::on_context_menu`] fires on a secondary-button press over an
//! item and reports the item index plus screen-space pointer/row geometry
//! in [`ListContext`]. The List deliberately does not import the app
//! overlay layer; pass that event to
//! [`ContextMenu`](crate::app::ContextMenu) when the app wants an owned,
//! keyboard-accessible menu.
//!
//! Disposal-safety law (ruling clause 4): the List completes ALL of its
//! own bookkeeping (selection write, sticky-key write, ensure-visible
//! scrolling) BEFORE any user callback runs, so a callback may dispose
//! the List's scope synchronously (the modal-picker close) without
//! tripping over dead signals.
//!
//! Cycle-7 hardening: VARIABLE-HEIGHT items (per-item height callback,
//! prefix-sum windowing — offsets are CONTENT CELL ROWS, item lookup is
//! a binary search), STICKY SELECTION BY KEY (`key_fn` +
//! `selection_key`: rebuilds re-find the selected key's new index, so
//! data mutations keep the same LOGICAL item selected), and
//! `scroll_to` (a command signal: set `Some(index)`, the list scrolls
//! it into view and consumes the request).
//!
//! Variable-height v1 honesty: an item's extra rows reserve SPACE (for
//! spacing/grouping); the label renders on the item's first row only —
//! wrapped multi-row item CONTENT is a later decision.
//!
//! ```
//! use abstracttui::base::Size;
//! use abstracttui::reactive::create_root;
//! use abstracttui::ui::{BufferCanvas, Element, UiTree};
//! use abstracttui::widgets::List;
//!
//! let mut tree = UiTree::new(Size::new(12, 3));
//! let (root, ()) = create_root(|cx| {
//!     let sel_key = cx.signal(String::from("beta"));
//!     let view = Element::new()
//!         .child(
//!             List::of(["alpha", "beta", "gamma"])
//!                 .key_fn(|_, item| item.to_string())
//!                 .selection_key(sel_key) // sticky across data changes
//!                 .view(cx),
//!         )
//!         .build();
//!     tree.mount(cx, view);
//! });
//! let mut canvas = BufferCanvas::new(Size::new(12, 3));
//! tree.draw(&mut canvas);
//! assert!(canvas.row_text(1).contains("beta"));
//! root.dispose();
//! ```
//!
//! OWNER: REACT.

use std::cell::{Cell, RefCell};
use std::rc::Rc;

use crate::base::{Point, Rect};
use crate::layout::{Dimension, Style as LayoutStyle};
use crate::reactive::{Scope, Signal};
use crate::render::rich::RichText;
use crate::render::{Attrs, Style};
use crate::theme::TokenSet;
use crate::ui::{dyn_view, Element, EventCtx, Key, Mods, MouseButton, MouseKind, Phase, UiEvent};
use crate::widgets::richtext::draw_rich_lines;
use crate::widgets::row_select;
use crate::widgets::scrollbar;

type HeightFn = Box<dyn Fn(usize, &str) -> i32>;
type KeyFn = Box<dyn Fn(usize, &str) -> String>;
type AccessoryFn = Box<dyn Fn(usize, &str) -> Option<String>>;

/// The dismiss glyph [`List::on_remove`] draws — `✕` U+2715, the same
/// spelling the block close affordance uses. East-Asian-NARROW and
/// absent from emoji-data, so it is single-width under every terminal
/// convention; `×` U+00D7 is East-Asian-AMBIGUOUS and was rejected (the
/// 0595 glyph-research method). Width 1 is test-pinned.
const REMOVE_GLYPH: &str = "✕";

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum ListHitZone {
    Body,
    Accessory,
    Scrollbar,
}

/// Column widths for one list viewport (content coordinates).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
struct ListColumns {
    body_w: i32,
    accessory_w: i32,
    bar_w: i32,
}

/// Where a pointer landed: an item row plus its zone, or the scrollbar
/// strip (which belongs to no row).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum ListHit {
    Row(usize, ListHitZone),
    Scrollbar,
}

/// Accessory labels, resolved ONCE per build: the caller's closure runs
/// exactly once per item, and the text is pre-truncated and pre-measured
/// against the (build-fixed) accessory width. Hit-testing and painting
/// then borrow — neither allocates, so hover motion is free.
type AccessoryCells = Rc<Vec<Option<(String, i32)>>>;

/// A secondary-button press over a List item.
///
/// Both coordinates are in SCREEN cells, including when the List lives
/// inside a positioned overlay. `screen_row` is the visible portion of
/// the item, excluding the scrollbar; anchor a popup at
/// `screen_position` and use `index` to build row-specific actions.
/// The gesture does not move selection and never activates the row.
#[non_exhaustive]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct ListContext {
    pub index: usize,
    pub screen_position: Point,
    pub screen_row: Rect,
    pub mods: Mods,
}

#[allow(clippy::too_many_arguments)]
fn list_context(
    index: usize,
    position: Point,
    rect: Rect,
    cols: ListColumns,
    offset: i32,
    prefix: &[i32],
    layer_origin: Point,
    mods: Mods,
) -> ListContext {
    let top = (rect.y + prefix[index] - offset).max(rect.y);
    let bottom = (rect.y + prefix[index + 1] - offset).min(rect.bottom());
    ListContext {
        index,
        screen_position: Point::new(position.x + layer_origin.x, position.y + layer_origin.y),
        screen_row: Rect::new(
            rect.x + layer_origin.x,
            top + layer_origin.y,
            cols.body_w + cols.accessory_w,
            (bottom - top).max(0),
        ),
        mods,
    }
}

fn list_columns(viewport_w: i32, show_bar: bool, accessory_w: i32) -> ListColumns {
    let bar_w = i32::from(show_bar);
    let accessory_w = accessory_w.max(0);
    let body_w = (viewport_w - bar_w - accessory_w).max(0);
    ListColumns {
        body_w,
        accessory_w,
        bar_w,
    }
}

fn list_hit_zone(local_x: i32, cols: ListColumns) -> ListHitZone {
    if cols.bar_w > 0 && local_x >= cols.body_w + cols.accessory_w {
        ListHitZone::Scrollbar
    } else if cols.accessory_w > 0 && local_x >= cols.body_w {
        ListHitZone::Accessory
    } else {
        ListHitZone::Body
    }
}

/// The ONE hit resolver: hover ink and clicks both route through it, so
/// what lights up under the pointer is exactly what a press will act on.
///
/// The accessory zone is the whole column width on the row where the
/// accessory is DRAWN (an item's first row) — a forgiving target — and
/// only for rows that actually have one. Everything else is body.
fn resolve_hit(
    local: Point,
    cols: ListColumns,
    offset: i32,
    prefix: &[i32],
    len: usize,
    cells: Option<&AccessoryCells>,
) -> Option<ListHit> {
    let zone = list_hit_zone(local.x, cols);
    if zone == ListHitZone::Scrollbar {
        return Some(ListHit::Scrollbar);
    }
    let row = local.y + offset;
    let total_rows = *prefix.last()?;
    if row < 0 || row >= total_rows {
        return None;
    }
    let idx = prefix.partition_point(|&p| p <= row).saturating_sub(1);
    if idx >= len {
        return None;
    }
    let on_accessory = zone == ListHitZone::Accessory
        && row == prefix[idx]
        && cells.is_some_and(|c| c[idx].is_some());
    Some(ListHit::Row(
        idx,
        if on_accessory {
            ListHitZone::Accessory
        } else {
            ListHitZone::Body
        },
    ))
}

/// A virtualized, selectable vertical list — the picker surface.
///
/// Bind [`selection`](List::selection) to a `Signal<usize>`; selection
/// follows movement ([`on_select`](List::on_select) is the
/// notification), and [`on_activate`](List::on_activate) is the commit:
/// Enter, Space, or a click on the already-selected row (which is why a
/// double-click activates with no timer). The canonical build is
/// `.view(cx)`. See the [module docs](crate::widgets::list) for the
/// full selection-vs-activation contract.
pub struct List {
    items: Vec<String>,
    selection: Option<Signal<usize>>,
    selection_key: Option<Signal<String>>,
    key_fn: Option<KeyFn>,
    heights: Option<HeightFn>,
    scroll_to: Option<Signal<Option<usize>>>,
    offset_y: Option<Signal<i32>>,
    focused: Option<Signal<bool>>,
    layout: Option<LayoutStyle>,
    on_select: Option<Box<dyn FnMut(usize)>>,
    on_activate: Option<Box<dyn FnMut(usize)>>,
    accessory_fn: Option<AccessoryFn>,
    accessory_width: Option<i32>,
    on_accessory_click: Option<Box<dyn FnMut(usize)>>,
    on_remove: Option<Box<dyn FnMut(usize)>>,
    on_row_double_click: Option<Box<dyn FnMut(usize)>>,
    on_context_menu: Option<Box<dyn FnMut(ListContext)>>,
    rich_items: Option<Vec<RichText>>,
}

impl List {
    /// Ergonomic constructor: anything iterable into strings —
    /// `List::of(["a", "b"])`, an iterator chain, string slices.
    /// (`new` keeps the plain `Vec<String>` signature so existing
    /// `.collect()` call sites stay inferable.)
    pub fn of<I, S>(items: I) -> List
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        List::new(items.into_iter().map(Into::into).collect())
    }

    pub fn new(items: Vec<String>) -> List {
        List {
            items,
            selection: None,
            selection_key: None,
            key_fn: None,
            heights: None,
            scroll_to: None,
            offset_y: None,
            focused: None,
            layout: None,
            on_select: None,
            on_activate: None,
            accessory_fn: None,
            accessory_width: None,
            on_accessory_click: None,
            on_remove: None,
            on_row_double_click: None,
            on_context_menu: None,
            rich_items: None,
        }
    }

    /// Bind an external selection signal (index); default is internal.
    pub fn selection(mut self, selection: Signal<usize>) -> List {
        self.selection = Some(selection);
        self
    }

    /// Stable item identity for sticky selection: with `selection_key`
    /// bound, rebuilds re-find the key's CURRENT index (data mutations
    /// keep the logical item selected) and selecting writes the key.
    pub fn key_fn(mut self, f: impl Fn(usize, &str) -> String + 'static) -> List {
        self.key_fn = Some(Box::new(f));
        self
    }

    /// The selected item's KEY (see [`List::key_fn`]).
    pub fn selection_key(mut self, key: Signal<String>) -> List {
        self.selection_key = Some(key);
        self
    }

    /// Per-item height in cell rows (min 1). Enables variable-height
    /// virtualization; without it every item is one row.
    pub fn item_heights(mut self, f: impl Fn(usize, &str) -> i32 + 'static) -> List {
        self.heights = Some(Box::new(f));
        self
    }

    /// Command signal: set `Some(index)` to scroll that item into view;
    /// the list consumes the request (resets to `None`).
    pub fn scroll_to(mut self, request: Signal<Option<usize>>) -> List {
        self.scroll_to = Some(request);
        self
    }

    /// Bind the first visible CONTENT ROW (the [`Scroll::offset_y`]
    /// convention). Default is internal, which means a rebuild starts
    /// back at the top — bind this whenever the caller's data changes
    /// under a `Dyn`, so dismissing a row with [`List::on_remove`] does
    /// not scroll the reader to the head of the list.
    ///
    /// The List clamps a bound offset into range on every build, so a
    /// list that shrinks can never strand the viewport past its end.
    ///
    /// [`Scroll::offset_y`]: crate::widgets::Scroll::offset_y
    pub fn offset_y(mut self, offset: Signal<i32>) -> List {
        self.offset_y = Some(offset);
        self
    }

    /// Bind an external focus signal (D4-2): true while the list holds
    /// keyboard focus — panes wire their stroke color to it (§3.2).
    pub fn focus_signal(mut self, focused: Signal<bool>) -> List {
        self.focused = Some(focused);
        self
    }

    pub fn layout(mut self, layout: LayoutStyle) -> List {
        self.layout = Some(layout);
        self
    }

    /// Selection-changed NOTIFICATION: fires whenever the highlighted
    /// index MOVES (arrows, Page keys, Home/End, a click on a different
    /// row). It is not a commitment — for "the user chose this row",
    /// bind [`List::on_activate`]. All List bookkeeping (selection
    /// write, ensure-visible) completes before this runs, so the
    /// callback may dispose the List's scope synchronously.
    pub fn on_select(mut self, f: impl FnMut(usize) + 'static) -> List {
        self.on_select = Some(Box::new(f));
        self
    }

    /// ACTIVATION: the user committed the selected row (0250 ruling).
    /// Fires with the current index on Enter, on Space (no toggle
    /// meaning in a List), and on a click on the ALREADY-selected row —
    /// a click on an unselected row only selects. Double-clicks work by
    /// subsumption when [`List::on_row_double_click`] is unbound: click 1
    /// selects, click 2 is a click on the selected row (no timing
    /// requirement — the picker gesture). When `on_row_double_click` IS
    /// bound, a timed double-click (`click_count() >= 2`) fires that
    /// callback instead of this one for the second press. When unbound,
    /// Enter/Space pass through to app shortcuts exactly as before this
    /// event existed. The callback may dispose the List's scope
    /// synchronously (close-the-picker is the intended use).
    pub fn on_activate(mut self, f: impl FnMut(usize) + 'static) -> List {
        self.on_activate = Some(Box::new(f));
        self
    }

    /// Trailing column label per row (`None` = no accessory cell).
    /// Width is the max label width unless [`List::accessory_width`]
    /// pins it. Clicks in the accessory column route to
    /// [`List::on_accessory_click`] and do not move selection.
    pub fn row_accessory(mut self, f: impl Fn(usize, &str) -> Option<String> + 'static) -> List {
        self.accessory_fn = Some(Box::new(f));
        self
    }

    /// Fixed accessory column width in cells (default: max label width).
    pub fn accessory_width(mut self, cells: i32) -> List {
        self.accessory_width = Some(cells.max(1));
        self
    }

    /// Fires when the user clicks the trailing accessory column.
    pub fn on_accessory_click(mut self, f: impl FnMut(usize) + 'static) -> List {
        self.on_accessory_click = Some(Box::new(f));
        self
    }

    /// Removable rows: draws a trailing `✕` on every row and fires `f`
    /// with the row index when it is clicked. Remove that index from
    /// YOUR data and let your `Dyn` rebuild — the List owns the rest.
    ///
    /// On the rebuild the List re-settles selection so it can never name
    /// a row that no longer exists: with [`List::key_fn`] +
    /// [`List::selection_key`] bound the selected item is re-found by
    /// key, and when the selected item was the one removed (its key is
    /// gone) selection falls to the same slot clamped into the shorter
    /// list — the next row down, or the new last row.
    ///
    /// This is the one-call form of [`List::row_accessory`] +
    /// [`List::accessory_width`] + [`List::on_accessory_click`]. Bind
    /// those directly instead when the trailing column is a badge or a
    /// per-row action rather than a dismiss.
    pub fn on_remove(mut self, f: impl FnMut(usize) + 'static) -> List {
        self.on_remove = Some(Box::new(f));
        self
    }

    /// Browsing-surface double-click: fires on the row BODY when the
    /// second press of a click chain lands on the already-selected row
    /// (`EventCtx::click_count() >= 2`). Supersedes [`List::on_activate`]
    /// for that press. Accessory and scrollbar columns are excluded.
    pub fn on_row_double_click(mut self, f: impl FnMut(usize) + 'static) -> List {
        self.on_row_double_click = Some(Box::new(f));
        self
    }

    /// Secondary-button action request for an item. Fires on
    /// `MouseButton::Right` DOWN over either the row body or its
    /// accessory, never over empty space or the scrollbar. The callback
    /// receives screen-space geometry suitable for an anchored popup.
    ///
    /// This gesture does not move selection, call `on_select`, or call
    /// `on_activate`. When unbound, right presses continue bubbling.
    /// Pair it with [`ContextMenu`](crate::app::ContextMenu) for the
    /// standard owned menu surface. Shift+F10 invokes the same callback
    /// for the selected row and first scrolls that row into view.
    pub fn on_context_menu(mut self, f: impl FnMut(ListContext) + 'static) -> List {
        self.on_context_menu = Some(Box::new(f));
        self
    }

    /// Per-row rich labels (same length as `items`). Body column only;
    /// accessories stay plain text. Replaces the plain string on the
    /// first visible row of each item.
    pub fn rich_items(mut self, items: Vec<RichText>) -> List {
        self.rich_items = Some(items);
        self
    }

    /// Canonical one-call build (cycle 8): tokens resolve from the
    /// app's THEME CONTEXT (a tracked read — building inside a
    /// `dyn_view` re-renders on theme switch) and the finished `View`
    /// comes back ready for `.child(..)`. Use `element(cx, &tokens)`
    /// when you need explicit theming or extra Element customization.
    pub fn view(self, cx: Scope) -> crate::ui::View {
        let t = crate::widgets::theme_tokens(cx);
        self.element(cx, &t).build()
    }

    pub fn element(self, cx: Scope, t: &TokenSet) -> Element {
        let text_fg = t.text;
        let ground = t.surface;
        let sel_bg = t.selection_bg;
        let sel_fg = t.selection_fg;
        let track = t.border;
        let thumb = t.text_muted;
        let accent = t.accent;

        let items = Rc::new(self.items);
        let len = items.len();
        // Prefix sums over item heights: prefix[i] = first content row
        // of item i; prefix[len] = total rows. Uniform lists get the
        // identity prefix — ONE windowing code path. (Shared with
        // `RowSelect` — `widgets::row_select` owns the selection core.)
        let prefix: Rc<Vec<i32>> = Rc::new(row_select::prefix_sums(len, |i| {
            self.heights.as_ref().map(|f| f(i, &items[i])).unwrap_or(1)
        }));
        let total_rows = *prefix.last().unwrap_or(&0);

        let selection = self.selection.unwrap_or_else(|| cx.signal(0usize));
        let hover = cx.signal(None::<ListHit>);
        // Solved viewport size, published by the root's `size_probe` one
        // turn after a resize (RT1-2: paint never writes signals — the
        // probe latches an `after(0)` instead). The `scroll_to` command
        // is the only reader; event handlers measure from their own
        // `ctx.current_rect()`, which is already authoritative.
        let view_box = cx.signal((0i32, 0i32));
        // Sticky selection: the KEY re-finds its index at build time —
        // this is what survives data mutations (each mutation rebuilds
        // through the caller's Dyn).
        let keys: Option<Rc<Vec<String>>> = self.key_fn.map(|f| {
            Rc::new(
                items
                    .iter()
                    .enumerate()
                    .map(|(i, s)| f(i, s))
                    .collect::<Vec<_>>(),
            )
        });
        // First visible CONTENT ROW. A bound offset survives rebuilds
        // (see `offset_y`) — but the items it points into may have
        // shrunk since it was written, so clamp it here for the same
        // reason selection is settled below: no viewport past the end.
        let offset = self.offset_y.unwrap_or_else(|| cx.signal(0i32));

        // The SELECTION CORE, shared with `RowSelect` (which drives the
        // same model over rows it does not render): settle-on-rebuild,
        // sticky-by-key, ensure-visible, and the select transition.
        let model = row_select::SelectionModel {
            len,
            keys: keys.clone(),
            prefix: prefix.clone(),
            selection,
            selection_key: self.selection_key,
            offset,
        };
        // Settle selection against THIS build's items — see
        // `SelectionModel::settle` for why a stale index is a real
        // defect and not merely untidy.
        model.settle();
        if self.offset_y.is_some() {
            offset.update(|o| *o = (*o).clamp(0, (total_rows - 1).max(0)));
        }
        let on_select: crate::widgets::SharedCallback<usize> =
            Rc::new(RefCell::new(self.on_select));
        let on_activate: crate::widgets::SharedCallback<usize> =
            Rc::new(RefCell::new(self.on_activate));
        let on_row_double_click: crate::widgets::SharedCallback<usize> =
            Rc::new(RefCell::new(self.on_row_double_click));
        let on_context_menu: crate::widgets::SharedCallback<ListContext> =
            Rc::new(RefCell::new(self.on_context_menu));

        // `on_remove` is `row_accessory` + `accessory_width` +
        // `on_accessory_click` with the dismiss glyph filled in; an
        // explicit `row_accessory` still wins, so a caller can keep a
        // custom label and still get the removal bookkeeping.
        let removable = self.on_remove.is_some();
        // A dismiss is consequence-bearing, so its hot ink is `error` —
        // the same ruling the Block close affordance follows. A generic
        // `row_accessory` is a badge or a neutral per-row action, and an
        // unread count painted red would be a lie, so it takes the
        // ordinary hover accent. The CONSEQUENCE decides, not the label.
        let acc_hot_ink = if removable { t.error } else { t.accent };
        let accessory_fn: Option<AccessoryFn> = self.accessory_fn.or_else(|| {
            removable.then(|| {
                Box::new(|_: usize, _: &str| Some(REMOVE_GLYPH.to_string())) as AccessoryFn
            })
        });
        let on_accessory_click: crate::widgets::SharedCallback<usize> =
            Rc::new(RefCell::new(self.on_accessory_click.or(self.on_remove)));

        // ONE pass: the caller's closure runs exactly once per item and
        // the label is truncated and measured against the accessory
        // width, which is fixed for this build. Painting and hit-testing
        // then borrow — no allocation on the hover or click path.
        let accessory_w = accessory_fn.as_ref().map_or(0, |f| {
            self.accessory_width.unwrap_or_else(|| {
                items
                    .iter()
                    .enumerate()
                    .filter_map(|(i, s)| f(i, s))
                    .map(|l| unicode_width::UnicodeWidthStr::width(l.as_str()) as i32 + 1)
                    .max()
                    .unwrap_or(0)
            })
        });
        let accessory_cells: Option<AccessoryCells> = accessory_fn.map(|f| {
            Rc::new(
                items
                    .iter()
                    .enumerate()
                    .map(|(i, s)| {
                        f(i, s).map(|label| {
                            let text = crate::text::truncate_ellipsis(&label, accessory_w.max(0));
                            let w = unicode_width::UnicodeWidthStr::width(text.as_str()) as i32;
                            (text, w)
                        })
                    })
                    .collect::<Vec<_>>(),
            )
        });
        let rich_items = self.rich_items.map(Rc::new);
        let layout = self
            .layout
            .unwrap_or_else(|| LayoutStyle::default().grow(1.0));

        let select = {
            let on_select = on_select.clone();
            let model = model.clone();
            move |target: usize, view_h: i32| {
                // The model writes selection, the sticky key, and the
                // ensure-visible offset — ALL widget bookkeeping lands
                // BEFORE the user callback (0250 ruling clause 4,
                // disposal-safety law): a callback that disposes this
                // List's scope must find no widget code left to run on
                // dead signals.
                if model.select(target, view_h) {
                    // Held borrow across `f`: safe — dispatch-only slot
                    // (the SharedCallback held-borrow contract).
                    if let Some(f) = on_select.borrow_mut().as_mut() {
                        f(target);
                    }
                }
            }
        };

        // scroll_to command signal: consume Some(idx) into an offset.
        if let Some(request) = self.scroll_to {
            let model = model.clone();
            cx.effect_labeled("list-scroll-to", move || {
                let Some(idx) = request.get() else {
                    return;
                };
                if len == 0 {
                    request.set(None);
                    return;
                }
                let vh = view_box.get().1;
                if vh <= 0 {
                    return; // hold the request until the probe measures
                }
                model.ensure_visible(idx.min(len - 1), vh);
                request.set(None); // consumed (one extra no-op run)
            });
        }

        let prefix_for_handler = prefix.clone();
        // Scrollbar grab (rows below the thumb's top edge): a plain cell,
        // because a pointer gesture is not app state. `None` = no drag of
        // ours is live, and a bare `Drag` that arrives without one
        // belongs to somebody else's gesture.
        let bar_grab: Rc<Cell<Option<i32>>> = Rc::new(Cell::new(None));
        let activate = on_activate;
        let accessory_click = on_accessory_click;
        let row_double_click = on_row_double_click;
        let context_menu = on_context_menu;
        let accessory_w_handler = accessory_w;
        let cells_handler = accessory_cells.clone();
        let hover_handler = hover;
        let model_handler = model.clone();
        let handler = move |ctx: &mut EventCtx, ev: &UiEvent| {
            let rect = ctx.current_rect();
            let h = rect.h.max(1);
            let hit_at = |pos: Point| {
                let cols = list_columns(rect.w, total_rows > h, accessory_w_handler);
                resolve_hit(
                    Point::new(pos.x - rect.x, pos.y - rect.y),
                    cols,
                    offset.get_untracked(),
                    &prefix_for_handler,
                    len,
                    cells_handler.as_ref(),
                )
            };
            match ev {
                UiEvent::MouseLeave => {
                    hover_handler.set_if_changed(None);
                }
                UiEvent::Key(k) => {
                    // The portable keyboard equivalent of a secondary
                    // press. Modified function keys are distinct on the
                    // baseline terminal wire; a physical Menu key is not.
                    if k.key == Key::F(10) && k.mods == Mods::SHIFT {
                        if len == 0 || context_menu.borrow().is_none() {
                            return;
                        }
                        let idx = selection.get_untracked().min(len - 1);
                        model_handler.ensure_visible(idx, h);
                        let cols = list_columns(rect.w, total_rows > h, accessory_w_handler);
                        let first = offset.get_untracked();
                        let y = (rect.y + prefix_for_handler[idx] - first)
                            .clamp(rect.y, rect.bottom().saturating_sub(1));
                        let event = list_context(
                            idx,
                            Point::new(rect.x, y),
                            rect,
                            cols,
                            first,
                            &prefix_for_handler,
                            ctx.layer_origin(),
                            k.mods,
                        );
                        ctx.stop_propagation();
                        if let Some(f) = context_menu.borrow_mut().as_mut() {
                            f(event);
                        }
                        return;
                    }
                    // Activation keys (0250 ruling clause 2): Enter
                    // always; Space too, because a List has no toggle
                    // meaning. Consumed ONLY when a callback is bound —
                    // an unbound List leaves Enter/Space to the app's
                    // own shortcuts (pre-0250 behavior, kept).
                    if matches!(k.key, Key::Enter | Key::Char(' ')) {
                        if len > 0 {
                            // Held borrow: safe — dispatch-only slot (the
                            // SharedCallback held-borrow contract).
                            if let Some(f) = activate.borrow_mut().as_mut() {
                                f(selection.get_untracked().min(len - 1));
                                ctx.stop_propagation();
                            }
                        }
                        return;
                    }
                    let cur = selection.get_untracked();
                    let Some(target) = row_select::nav_target(k.key, cur, len, (h as usize).max(1))
                    else {
                        return;
                    };
                    select(target, h);
                    ctx.stop_propagation();
                }
                UiEvent::Mouse(m) => match m.kind {
                    MouseKind::Move => {
                        hover_handler.set_if_changed(hit_at(m.pos));
                    }
                    MouseKind::ScrollUp | MouseKind::ScrollDown => {
                        let delta = if m.kind == MouseKind::ScrollUp { -3 } else { 3 };
                        let max_off = (total_rows - h).max(0);
                        let to = (offset.get_untracked() + delta).clamp(0, max_off);
                        // Only a scroller that actually MOVED owns the
                        // wheel; at either end it bubbles so a parent
                        // scroller takes over (no dead zone at the edge).
                        if offset.set_if_changed(to) {
                            // The pointer did not move but the content
                            // under it did — re-resolve so the ink never
                            // lights a row the cursor has left.
                            hover_handler.set_if_changed(hit_at(m.pos));
                            ctx.stop_propagation();
                        }
                    }
                    MouseKind::Up(MouseButton::Left) => {
                        bar_grab.set(None);
                    }
                    MouseKind::Drag(MouseButton::Left) => {
                        // Only OUR grab scrolls: a drag that arrives
                        // with none is another widget's gesture passing
                        // through, never a teleport of this offset.
                        let Some(dy) = bar_grab.get() else { return };
                        let bar = scrollbar::metrics(rect, 1, offset.get_untracked(), total_rows);
                        if bar.overflows() {
                            offset.set_if_changed(scrollbar::offset_at(&bar, m.pos.y, dy));
                            hover_handler.set_if_changed(hit_at(m.pos));
                            ctx.stop_propagation();
                        }
                    }
                    MouseKind::Down(MouseButton::Left) => {
                        match hit_at(m.pos) {
                            // The strip is ours: it takes hold of the
                            // thumb (a press ON it moves nothing) or
                            // teleports from bare track, and either way
                            // never falls through to what sits behind.
                            Some(ListHit::Scrollbar) => {
                                let bar =
                                    scrollbar::metrics(rect, 1, offset.get_untracked(), total_rows);
                                if let Some(zone) = scrollbar::hit(&bar, m.pos) {
                                    if bar.overflows() {
                                        let dy = scrollbar::grab_for(&bar, zone);
                                        bar_grab.set(Some(dy));
                                        if matches!(zone, scrollbar::Zone::Track) {
                                            offset.set_if_changed(scrollbar::offset_at(
                                                &bar, m.pos.y, dy,
                                            ));
                                            hover_handler.set_if_changed(hit_at(m.pos));
                                        }
                                    }
                                }
                                ctx.stop_propagation();
                            }
                            None => {}
                            Some(ListHit::Row(idx, ListHitZone::Accessory)) => {
                                if let Some(f) = accessory_click.borrow_mut().as_mut() {
                                    f(idx);
                                }
                            }
                            Some(ListHit::Row(idx, _)) => {
                                let was_selected = selection.get_untracked() == idx;
                                select(idx, h);
                                if was_selected {
                                    if ctx.click_count() >= 2 {
                                        if let Some(f) = row_double_click.borrow_mut().as_mut() {
                                            f(idx);
                                        } else if let Some(f) = activate.borrow_mut().as_mut() {
                                            f(idx);
                                        }
                                    } else if let Some(f) = activate.borrow_mut().as_mut() {
                                        f(idx);
                                    }
                                }
                            }
                        }
                        ctx.stop_propagation();
                    }
                    MouseKind::Down(MouseButton::Right) => {
                        let Some(ListHit::Row(idx, _)) = hit_at(m.pos) else {
                            return;
                        };
                        // An unbound List does not claim the terminal's
                        // secondary-button gesture. This lets an ancestor
                        // provide a broader surface menu.
                        let mut slot = context_menu.borrow_mut();
                        let Some(f) = slot.as_mut() else { return };
                        let cols = list_columns(rect.w, total_rows > h, accessory_w_handler);
                        let event = list_context(
                            idx,
                            m.pos,
                            rect,
                            cols,
                            offset.get_untracked(),
                            &prefix_for_handler,
                            ctx.layer_origin(),
                            m.mods,
                        );
                        // All widget work ends before user code: the
                        // callback may synchronously dispose this List.
                        ctx.stop_propagation();
                        f(event);
                    }
                    _ => {}
                },
                _ => {}
            }
        };

        let mut el = Element::new()
            .style(layout)
            .role(crate::ui::Role::List)
            .access_value(move || {
                // An empty list has nothing selected — announcing a row
                // number here is the same phantom-row defect the
                // selection settle above exists to prevent.
                if len == 0 {
                    return "0 items".into();
                }
                format!("{} items, selected {}", len, selection.get_untracked() + 1)
            })
            // Solved-size readback for `scroll_to` (0130 measured-extent
            // seam): the probe records the rect during paint and latches
            // ONE `after(0)` to publish it, so the viewport height
            // reaches the reactive graph without paint ever writing a
            // signal. A steady frame records an unchanged size and
            // schedules nothing.
            .draw(super::scroll::size_probe(cx, view_box))
            // The internal bar column owns left drags (first-app/1335):
            // screen select mode stands down over the STRIP only, so the
            // thumb keeps its gesture while every row stays selectable.
            //
            // Gated on `overflows()`, not merely on the bar being drawn:
            // a one-row viewport draws a full-height thumb with ZERO
            // travel, which the gesture refuses to steer. A cell nothing
            // can drag must not swallow a selection either — that is the
            // contract `Element::drag_zone` states.
            .drag_zone(move |rect| {
                let cols = list_columns(rect.w, total_rows > rect.h, accessory_w);
                if cols.bar_w == 0 {
                    return None;
                }
                let strip = Rect::new(
                    rect.x + cols.body_w + cols.accessory_w,
                    rect.y,
                    cols.bar_w,
                    rect.h,
                );
                scrollbar::metrics(strip, cols.bar_w, 0, total_rows)
                    .overflows()
                    .then_some(strip)
            })
            .focusable();
        if let Some(focused) = self.focused {
            el = el.focus_signal(focused);
        }
        let prefix_for_draw = prefix;
        let accessory_w_draw = accessory_w;
        let cells_draw = accessory_cells;
        let rich_items_draw = rich_items;
        let hover_draw = hover;
        let accent_draw = accent;
        el.on(Phase::Bubble, handler).child(dyn_view(
            LayoutStyle::default()
                .width(Dimension::Percent(1.0))
                .height(Dimension::Percent(1.0)),
            move || {
                let sel = selection.get();
                let first_row = offset.get().max(0);
                let pointer = hover_draw.get();
                let items = items.clone();
                let prefix = prefix_for_draw.clone();
                let cells_inner = cells_draw.clone();
                let rich_items_inner = rich_items_draw.clone();
                Element::new()
                    .style(
                        LayoutStyle::default()
                            .width(Dimension::Percent(1.0))
                            .height(Dimension::Percent(1.0)),
                    )
                    .draw(move |canvas, rect| {
                        if rect.is_empty() || items.is_empty() {
                            return;
                        }
                        let base = Style::new().fg(text_fg).bg(ground);
                        canvas.fill_styled(rect, ' ', &base);
                        let total = *prefix.last().unwrap_or(&0);
                        let show_bar = total > rect.h;
                        let cols = list_columns(rect.w, show_bar, accessory_w_draw);
                        let text_w = cols.body_w;
                        let bar_hot = pointer == Some(ListHit::Scrollbar);
                        // Virtualization: first visible item by
                        // binary search, walk until off-screen.
                        let mut idx = prefix
                            .partition_point(|&p| p <= first_row)
                            .saturating_sub(1);
                        while idx < items.len() {
                            let top = prefix[idx] - first_row;
                            if top >= rect.h {
                                break;
                            }
                            let item_h = prefix[idx + 1] - prefix[idx];
                            let selected = idx == sel;
                            // The accessory BELONGS to the row: entering
                            // it must not make the row go dark. So ink
                            // says WHICH ROW is hot and BOLD says WHICH
                            // ZONE — hue alone cannot carry both, since
                            // `accent` and `error` are the same red in
                            // several built-in themes.
                            let hot_zone = match pointer {
                                Some(ListHit::Row(i, z)) if i == idx => Some(z),
                                _ => None,
                            };
                            let style = if selected {
                                Style::new().fg(sel_fg).bg(sel_bg)
                            } else if hot_zone.is_some() {
                                Style::new().fg(accent_draw).bg(ground)
                            } else {
                                base
                            };
                            let body_style = if hot_zone == Some(ListHitZone::Body) {
                                style.attrs(Attrs::BOLD)
                            } else {
                                style
                            };
                            if selected {
                                // Body + accessory wear the selection pair.
                                let row_w = cols.body_w + cols.accessory_w;
                                for r in 0..item_h {
                                    let y = rect.y + top + r;
                                    if y >= rect.y && y < rect.bottom() {
                                        canvas.fill_styled(
                                            crate::base::Rect::new(rect.x, y, row_w, 1),
                                            ' ',
                                            &style,
                                        );
                                    }
                                }
                            }
                            let y = rect.y + top;
                            if y >= rect.y && y < rect.bottom() {
                                if let Some(rich) =
                                    rich_items_inner.as_ref().and_then(|v| v.get(idx))
                                {
                                    let shaped = rich.wrap(text_w.max(0));
                                    // Hover ink reaches rich rows too —
                                    // it is the row's BASE ink, so spans
                                    // that set their own `fg` still win.
                                    draw_rich_lines(
                                        canvas,
                                        crate::base::Rect::new(rect.x, y, text_w, 1),
                                        shaped.lines.iter().take(1),
                                        if selected {
                                            sel_fg
                                        } else if hot_zone.is_some() {
                                            accent_draw
                                        } else {
                                            text_fg
                                        },
                                        crate::render::rich::HAlign::Left,
                                    );
                                } else {
                                    let line =
                                        crate::text::truncate_ellipsis(&items[idx], text_w.max(0));
                                    canvas.print_styled(
                                        crate::base::Point::new(rect.x, y),
                                        &line,
                                        &body_style,
                                    );
                                }
                            }
                            if cols.accessory_w > 0 {
                                // Pre-truncated and pre-measured at build
                                // (see AccessoryCells): painting borrows.
                                if let Some((acc_text, acc_w)) =
                                    cells_inner.as_ref().and_then(|c| c[idx].as_ref())
                                {
                                    let acc_hot = hot_zone == Some(ListHitZone::Accessory);
                                    let acc_x =
                                        rect.x + cols.body_w + (cols.accessory_w - acc_w).max(0);
                                    let acc_style = if selected {
                                        // Selection outranks hover: the
                                        // audited selection pair stays,
                                        // and BOLD marks the zone. The
                                        // hot inks are NOT contrast-
                                        // audited against selection_bg.
                                        if acc_hot {
                                            style.attrs(Attrs::BOLD)
                                        } else {
                                            style
                                        }
                                    } else if acc_hot {
                                        Style::new().fg(acc_hot_ink).bg(ground).attrs(Attrs::BOLD)
                                    } else {
                                        style
                                    };
                                    if y >= rect.y && y < rect.bottom() {
                                        canvas.print_styled(
                                            crate::base::Point::new(acc_x, y),
                                            acc_text,
                                            &acc_style,
                                        );
                                    }
                                }
                            }
                            idx += 1;
                        }
                        if show_bar {
                            let bar = scrollbar::metrics(rect, cols.bar_w, first_row, total);
                            scrollbar::draw(
                                canvas,
                                &bar,
                                bar_hot,
                                track,
                                thumb,
                                accent_draw,
                                ground,
                            );
                        }
                    })
                    .build()
            },
        ))
    }
}

#[cfg(test)]
#[path = "list_tests.rs"]
mod tests;