ailloli_ui_widgets/controls/
table_view.rs

1//! Retained, scrollable data table with typed row selection and rich cells.
2//!
3//! Column widths combine fixed, flex, and content-measured policies. The header
4//! remains fixed while the body scrolls on both axes; disabled rows are skipped
5//! by pointer and keyboard selection.
6
7use std::cell::Cell;
8use std::rc::Rc;
9use std::sync::Arc;
10
11use crate::layout::layout_ext::{apply_layout_size, finish_view_sized, LayoutExt};
12use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
13use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey};
14use ailloli_ui_core::geometry::{Constraints, Rect, Size};
15use ailloli_ui_core::scroll::{
16    ScrollAxes, ScrollBehavior, ScrollMetrics, ScrollState, ScrollbarAxis, ScrollbarGeometry,
17    ScrollbarGeometrySpec,
18};
19use ailloli_ui_core::style::{
20    Border, BoxShadow, FlexItemStyle, LayoutSizeHint, LayoutStyle, Length, Radius,
21};
22use ailloli_ui_core::{Color, FontId, IconId, Offset, TextStyle, Theme};
23use ailloli_ui_runtime::component::reactive::with_untracked_reads;
24use ailloli_ui_runtime::component::{
25    Binding, ComponentNode, Context, IntoView, Memo, Signal, View, Widget,
26};
27use ailloli_ui_runtime::input::{EventCtx, FocusPolicy};
28use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
29use ailloli_ui_runtime::scene::PaintCtx;
30use ailloli_ui_runtime::{
31    DrawBorder, DrawBoxShadow, DrawCmd, DrawImage, DrawRRect, DrawRect, DrawText, Invalidation,
32};
33use ailloli_ui_text::{PreparedTextLayout, TextLayoutParams, TextSystem, WrapMode};
34
35use super::badge::BadgeTone;
36use crate::scrollbar::{thumb_color_for_state, ScrollbarInteraction};
37use crate::transactional_layout::TransactionalLayoutPending;
38
39#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
40/// Density preset used to derive [`TableViewStyle`].
41///
42/// # Examples
43///
44/// ```
45/// use ailloli_ui_widgets::controls::TableViewSize;
46/// assert_eq!(TableViewSize::default(), TableViewSize::Default);
47/// assert_ne!(TableViewSize::Compact, TableViewSize::Default);
48/// ```
49pub enum TableViewSize {
50    /// 30-pixel header/rows and 72-pixel minimum columns.
51    Compact,
52    #[default]
53    /// 34-pixel header, 36-pixel rows, and 88-pixel minimum columns.
54    Default,
55}
56
57#[derive(Debug, Clone, Copy, Default, PartialEq)]
58/// Column-width resolution policy.
59///
60/// Every resolved width is floored by `TableViewStyle::min_column_width`. Raw
61/// negative fixed widths and flex weights become zero during resolution; flex
62/// columns divide remaining finite width by positive weight.
63///
64/// # Examples
65///
66/// ```
67/// use ailloli_ui_widgets::controls::TableColumnWidth;
68/// let widths = [TableColumnWidth::Fixed(120.0), TableColumnWidth::Flex(2.0), TableColumnWidth::Auto];
69/// assert_eq!(widths.len(), 3);
70/// ```
71pub enum TableColumnWidth {
72    /// Requested logical-pixel width before the style minimum is applied.
73    Fixed(f32),
74    /// Nonnegative share of finite remaining table width.
75    Flex(f32),
76    #[default]
77    /// Width of the widest header/cell content plus padding.
78    Auto,
79}
80
81#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
82/// Horizontal content alignment inside a table cell.
83///
84/// # Examples
85///
86/// ```
87/// use ailloli_ui_widgets::controls::TableAlign;
88/// assert_eq!(TableAlign::default(), TableAlign::Start);
89/// assert_eq!([TableAlign::Start, TableAlign::Center, TableAlign::End].len(), 3);
90/// ```
91pub enum TableAlign {
92    #[default]
93    /// Place content after left padding.
94    Start,
95    /// Center content without enforcing padding.
96    Center,
97    /// Place content before right padding.
98    End,
99}
100
101#[derive(Clone, Debug, PartialEq)]
102/// Table surfaces, typography, geometry, selection, and rich-cell appearance.
103///
104/// Dimensions are logical pixels and opacity is a multiplier. Fields are used as
105/// supplied without validation. The default is the regular preset of the default
106/// theme.
107///
108/// # Examples
109///
110/// ```
111/// use ailloli_ui_widgets::controls::TableViewStyle;
112/// let style = TableViewStyle::default();
113/// assert_eq!((style.header_height, style.row_height, style.min_column_width), (34.0, 36.0, 88.0));
114/// assert_eq!((style.progress_width, style.progress_height), (82.0, 4.0));
115/// ```
116pub struct TableViewStyle {
117    /// Root table surface.
118    pub background: Color,
119    /// Fixed header surface.
120    pub header_background: Color,
121    /// Regular row surface.
122    pub row_background: Color,
123    /// Odd zebra row surface.
124    pub row_alt_background: Color,
125    /// Reserved hovered-row surface token.
126    pub row_hover_background: Color,
127    /// Keyboard-active row surface.
128    pub row_active_background: Color,
129    /// Selected row surface, taking precedence over active/zebra.
130    pub row_selected_background: Color,
131    /// Horizontal and vertical separator color.
132    pub grid_color: Color,
133    /// Root table border.
134    pub border: Border,
135    /// Focused enabled table border.
136    pub focus_ring: Border,
137    /// Non-inset shadows painted in order.
138    pub shadows: Vec<BoxShadow>,
139    /// Primary cell text.
140    pub text: TextStyle,
141    /// Muted cell text.
142    pub muted_text: TextStyle,
143    /// Header text.
144    pub header_text: TextStyle,
145    /// Text used when table or row is disabled.
146    pub disabled_text: TextStyle,
147    /// Regular leading-row icon tint.
148    pub icon_tint: Color,
149    /// Leading-row icon tint while selected.
150    pub selected_icon_tint: Color,
151    /// Badge label text.
152    pub badge_text: TextStyle,
153    /// Progress track color.
154    pub progress_track: Color,
155    /// Progress fill color.
156    pub progress_fill: Color,
157    /// Root table corner radii.
158    pub radius: Radius,
159    /// Body row height in logical pixels.
160    pub row_height: f32,
161    /// Fixed header height in logical pixels.
162    pub header_height: f32,
163    /// Horizontal cell padding in logical pixels.
164    pub cell_padding_x: f32,
165    /// Minimum resolved column width in logical pixels.
166    pub min_column_width: f32,
167    /// Leading-row icon side length in logical pixels.
168    pub icon_size: f32,
169    /// Leading icon/text gap in logical pixels.
170    pub icon_gap: f32,
171    /// Preferred progress track width in logical pixels.
172    pub progress_width: f32,
173    /// Progress track height in logical pixels.
174    pub progress_height: f32,
175    /// Disabled row/table alpha multiplier.
176    pub disabled_opacity: f32,
177}
178
179impl Default for TableViewStyle {
180    fn default() -> Self {
181        Self::from_theme(Theme::default(), TableViewSize::Default)
182    }
183}
184
185impl TableViewStyle {
186    /// Derives table style from `theme` and density.
187    ///
188    /// Compact uses row/header heights `30/30`, padding `8`, 12-pixel body text,
189    /// and minimum column width `72`; default uses `36/34`, `10`, `13`, and `88`.
190    ///
191    /// # Examples
192    ///
193    /// ```
194    /// use ailloli_ui_core::Theme;
195    /// use ailloli_ui_widgets::controls::{TableViewSize, TableViewStyle};
196    /// let style = TableViewStyle::from_theme(Theme::default(), TableViewSize::Compact);
197    /// assert_eq!((style.row_height, style.header_height, style.min_column_width), (30.0, 30.0, 72.0));
198    /// ```
199    pub fn from_theme(theme: Theme, size: TableViewSize) -> Self {
200        let palette = theme.palette();
201        let (row_height, header_height, padding, text_size, min_column_width) = match size {
202            TableViewSize::Compact => (30.0, 30.0, 8.0, 12, 72.0),
203            TableViewSize::Default => (36.0, 34.0, 10.0, 13, 88.0),
204        };
205        Self {
206            background: palette.surface,
207            header_background: palette.surface_elevated,
208            row_background: Color::TRANSPARENT,
209            row_alt_background: palette.surface_elevated.with_alpha(0.28),
210            row_hover_background: palette.surface_elevated,
211            row_active_background: palette.accent.with_alpha(0.10),
212            row_selected_background: palette.accent.with_alpha(0.18),
213            grid_color: palette.border,
214            border: Border::new(1.0, palette.border),
215            focus_ring: Border::new(1.0, palette.focus),
216            shadows: vec![theme.shadows().sm],
217            text: TextStyle::new(FontId::Ui, text_size, palette.text),
218            muted_text: TextStyle::new(FontId::Ui, text_size, palette.text_muted),
219            header_text: TextStyle::new(FontId::Ui, 11, palette.text_muted),
220            disabled_text: TextStyle::new(
221                FontId::Ui,
222                text_size,
223                palette.text_muted.with_alpha(0.68),
224            ),
225            icon_tint: palette.text_muted,
226            selected_icon_tint: palette.accent,
227            badge_text: TextStyle::new(FontId::Ui, 11, palette.text),
228            progress_track: palette.surface_elevated,
229            progress_fill: palette.accent,
230            radius: Radius::uniform(theme.radius().md),
231            row_height,
232            header_height,
233            cell_padding_x: padding,
234            min_column_width,
235            icon_size: 16.0,
236            icon_gap: 6.0,
237            progress_width: 82.0,
238            progress_height: 4.0,
239            disabled_opacity: 0.42,
240        }
241    }
242}
243
244#[derive(Clone, Debug, PartialEq)]
245/// Header label, width policy, and default cell alignment for one column.
246///
247/// Labels are stored unchanged. The default is auto width and start alignment.
248///
249/// # Examples
250///
251/// ```
252/// use ailloli_ui_widgets::controls::{TableAlign, TableColumn};
253/// let column = TableColumn::new("Name").width(160.0).align(TableAlign::Start);
254/// let _ = column;
255/// ```
256pub struct TableColumn {
257    /// Header label.
258    label: String,
259    /// Resolution policy.
260    width: TableColumnWidth,
261    /// Header and default body-cell alignment.
262    align: TableAlign,
263}
264
265impl TableColumn {
266    /// Creates an auto-width, start-aligned column.
267    ///
268    /// # Examples
269    ///
270    /// ```
271    /// use ailloli_ui_widgets::controls::TableColumn;
272    /// let column = TableColumn::new("Status");
273    /// let _ = column;
274    /// ```
275    pub fn new(label: impl Into<String>) -> Self {
276        Self {
277            label: label.into(),
278            width: TableColumnWidth::Auto,
279            align: TableAlign::Start,
280        }
281    }
282
283    /// Sets fixed width after `f32::max(width, 0.0)` normalization.
284    ///
285    /// The table style's minimum column width is still applied during layout.
286    ///
287    /// # Examples
288    ///
289    /// ```
290    /// use ailloli_ui_widgets::controls::TableColumn;
291    /// let column = TableColumn::new("Name").width(160.0);
292    /// let _ = column;
293    /// ```
294    pub fn width(mut self, width: f32) -> Self {
295        self.width = TableColumnWidth::Fixed(width.max(0.0));
296        self
297    }
298
299    /// Sets an exact width policy without builder-time normalization.
300    ///
301    /// Fixed widths and flex weights are normalized during layout.
302    ///
303    /// # Examples
304    ///
305    /// ```
306    /// use ailloli_ui_widgets::controls::{TableColumn, TableColumnWidth};
307    /// let column = TableColumn::new("Name").column_width(TableColumnWidth::Auto);
308    /// let _ = column;
309    /// ```
310    pub fn column_width(mut self, width: TableColumnWidth) -> Self {
311        self.width = width;
312        self
313    }
314
315    /// Sets flex width with weight normalized by `f32::max(weight, 0.0)`.
316    ///
317    /// Zero-weight flex columns receive only the style minimum.
318    ///
319    /// # Examples
320    ///
321    /// ```
322    /// use ailloli_ui_widgets::controls::TableColumn;
323    /// let column = TableColumn::new("Description").flex(2.0);
324    /// let _ = column;
325    /// ```
326    pub fn flex(mut self, weight: f32) -> Self {
327        self.width = TableColumnWidth::Flex(weight.max(0.0));
328        self
329    }
330
331    /// Restores content-measured auto width.
332    ///
333    /// # Examples
334    ///
335    /// ```
336    /// use ailloli_ui_widgets::controls::TableColumn;
337    /// let column = TableColumn::new("Name").width(100.0).auto();
338    /// let _ = column;
339    /// ```
340    pub fn auto(mut self) -> Self {
341        self.width = TableColumnWidth::Auto;
342        self
343    }
344
345    /// Sets header alignment and fallback alignment for cells in this column.
346    ///
347    /// # Examples
348    ///
349    /// ```
350    /// use ailloli_ui_widgets::controls::{TableAlign, TableColumn};
351    /// let column = TableColumn::new("Total").align(TableAlign::End);
352    /// let _ = column;
353    /// ```
354    pub fn align(mut self, align: TableAlign) -> Self {
355        self.align = align;
356        self
357    }
358}
359
360#[derive(Clone, Debug, PartialEq)]
361/// Visual representation of a table cell.
362///
363/// # Examples
364///
365/// ```
366/// use ailloli_ui_widgets::controls::{BadgeTone, TableCellKind};
367/// let kinds = [TableCellKind::Text, TableCellKind::Muted,
368///              TableCellKind::Badge(BadgeTone::Success), TableCellKind::Progress(0.5)];
369/// assert_eq!(kinds.len(), 4);
370/// ```
371pub enum TableCellKind {
372    /// Primary text.
373    Text,
374    /// Muted text.
375    Muted,
376    /// Pill badge with the supplied semantic tone.
377    Badge(BadgeTone),
378    /// Progress track whose fill is clamped to `0.0..=1.0` when painted.
379    Progress(f32),
380}
381
382#[derive(Clone, Debug, PartialEq)]
383/// Cell content and optional alignment override.
384///
385/// A missing override inherits its [`TableColumn`] alignment. Extra row cells
386/// beyond the column count are ignored; missing cells leave blank columns.
387///
388/// # Examples
389///
390/// ```
391/// use ailloli_ui_widgets::controls::{TableAlign, TableCell};
392/// let cell = TableCell::text("42").align(TableAlign::End);
393/// let _ = cell;
394/// ```
395pub struct TableCell {
396    /// Text or badge label; progress cells store an empty label.
397    label: String,
398    /// Rendering kind.
399    kind: TableCellKind,
400    /// Per-cell alignment override.
401    align: Option<TableAlign>,
402}
403
404impl TableCell {
405    /// Creates a primary-text cell.
406    ///
407    /// # Examples
408    ///
409    /// ```
410    /// use ailloli_ui_widgets::controls::TableCell;
411    /// let cell = TableCell::text("Ready");
412    /// let _ = cell;
413    /// ```
414    pub fn text(label: impl Into<String>) -> Self {
415        Self {
416            label: label.into(),
417            kind: TableCellKind::Text,
418            align: None,
419        }
420    }
421
422    /// Creates a muted-text cell.
423    ///
424    /// # Examples
425    ///
426    /// ```
427    /// use ailloli_ui_widgets::controls::TableCell;
428    /// let cell = TableCell::muted("Optional");
429    /// let _ = cell;
430    /// ```
431    pub fn muted(label: impl Into<String>) -> Self {
432        Self {
433            label: label.into(),
434            kind: TableCellKind::Muted,
435            align: None,
436        }
437    }
438
439    /// Creates a semantic-tone badge cell.
440    ///
441    /// # Examples
442    ///
443    /// ```
444    /// use ailloli_ui_widgets::controls::{BadgeTone, TableCell};
445    /// let cell = TableCell::badge("Healthy", BadgeTone::Success);
446    /// let _ = cell;
447    /// ```
448    pub fn badge(label: impl Into<String>, tone: BadgeTone) -> Self {
449        Self {
450            label: label.into(),
451            kind: TableCellKind::Badge(tone),
452            align: None,
453        }
454    }
455
456    /// Creates an unlabeled progress cell.
457    ///
458    /// Finite values are clamped to `0.0..=1.0` during paint; NaN paints only
459    /// the track because the computed fill is not positive.
460    ///
461    /// # Examples
462    ///
463    /// ```
464    /// use ailloli_ui_widgets::controls::TableCell;
465    /// let cell = TableCell::progress(0.75);
466    /// let _ = cell;
467    /// ```
468    pub fn progress(value: f32) -> Self {
469        Self {
470            label: String::new(),
471            kind: TableCellKind::Progress(value),
472            align: None,
473        }
474    }
475
476    /// Overrides the owning column's alignment for this cell.
477    ///
478    /// # Examples
479    ///
480    /// ```
481    /// use ailloli_ui_widgets::controls::{TableAlign, TableCell};
482    /// let cell = TableCell::text("Centered").align(TableAlign::Center);
483    /// let _ = cell;
484    /// ```
485    pub fn align(mut self, align: TableAlign) -> Self {
486        self.align = Some(align);
487        self
488    }
489}
490
491#[derive(Clone)]
492/// Typed row ID, ordered cells, visual selection, availability, and leading icon.
493///
494/// Row IDs need not be unique. The per-row `selected` binding is visual only;
495/// table-level controlled selection compares IDs and may therefore select every
496/// duplicate ID visually.
497///
498/// # Examples
499///
500/// ```
501/// use ailloli_ui_widgets::controls::{TableCell, TableRow};
502/// let row = TableRow::new(7).cell(TableCell::text("Seven"));
503/// assert_eq!(*row.id(), 7);
504/// ```
505pub struct TableRow<T> {
506    /// Value written or emitted on row activation.
507    id: T,
508    /// Cells in column order.
509    cells: Vec<TableCell>,
510    /// Independent static or reactive visual-selection flag.
511    selected: Binding<bool>,
512    /// Static or reactive activation-disabled flag.
513    disabled: Binding<bool>,
514    /// Optional icon painted only in the first column.
515    leading_icon: Option<IconId>,
516}
517
518impl<T> TableRow<T> {
519    /// Creates an enabled, visually unselected row with no cells or icon.
520    ///
521    /// # Examples
522    ///
523    /// ```
524    /// use ailloli_ui_widgets::controls::TableRow;
525    /// let row = TableRow::new("row-id");
526    /// assert_eq!(row.id(), &"row-id");
527    /// ```
528    pub fn new(id: T) -> Self {
529        Self {
530            id,
531            cells: Vec::new(),
532            selected: Binding::Static(false),
533            disabled: Binding::Static(false),
534            leading_icon: None,
535        }
536    }
537
538    /// Appends one cell in column order.
539    ///
540    /// # Examples
541    ///
542    /// ```
543    /// use ailloli_ui_widgets::controls::{TableCell, TableRow};
544    /// let row = TableRow::new(1).cell(TableCell::text("One"));
545    /// assert_eq!(row.cells_ref().len(), 1);
546    /// ```
547    pub fn cell(mut self, cell: TableCell) -> Self {
548        self.cells.push(cell);
549        self
550    }
551
552    /// Extends cells in iterator order without clearing existing cells.
553    ///
554    /// # Examples
555    ///
556    /// ```
557    /// use ailloli_ui_widgets::controls::{TableCell, TableRow};
558    /// let row = TableRow::new(1).cells([TableCell::text("One"), TableCell::muted("Aux")]);
559    /// assert_eq!(row.cells_ref().len(), 2);
560    /// ```
561    pub fn cells(mut self, cells: impl IntoIterator<Item = TableCell>) -> Self {
562        self.cells.extend(cells);
563        self
564    }
565
566    /// Sets an independent static or reactive visual-selection flag.
567    ///
568    /// This does not update `TableView::selected` or invoke selection callbacks.
569    ///
570    /// # Examples
571    ///
572    /// ```
573    /// use ailloli_ui_widgets::controls::TableRow;
574    /// let row = TableRow::new(1).selected(true);
575    /// let _ = row;
576    /// ```
577    pub fn selected(mut self, selected: impl Into<Binding<bool>>) -> Self {
578        self.selected = selected.into();
579        self
580    }
581
582    /// Sets static or reactive row-disabled state.
583    ///
584    /// Disabled rows use reduced opacity and are skipped by hit testing and
585    /// keyboard navigation.
586    ///
587    /// # Examples
588    ///
589    /// ```
590    /// use ailloli_ui_widgets::controls::TableRow;
591    /// let row = TableRow::new(1).disabled(true);
592    /// let _ = row;
593    /// ```
594    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
595        self.disabled = disabled.into();
596        self
597    }
598
599    /// Uses a memo as the reactive row-disabled binding.
600    ///
601    /// # Examples
602    ///
603    /// ```
604    /// use ailloli_ui_runtime::component::Memo;
605    /// use ailloli_ui_widgets::controls::TableRow;
606    /// let row = TableRow::new(1).disabled_signal(Memo::new(|| false));
607    /// let _ = row;
608    /// ```
609    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
610        self.disabled(disabled)
611    }
612
613    /// Sets the first-column leading icon, replacing any previous one.
614    ///
615    /// # Examples
616    ///
617    /// ```
618    /// use ailloli_ui_core::IconId;
619    /// use ailloli_ui_widgets::controls::TableRow;
620    /// let row = TableRow::new(1).leading_icon(IconId::History);
621    /// let _ = row;
622    /// ```
623    pub fn leading_icon(mut self, icon: IconId) -> Self {
624        self.leading_icon = Some(icon);
625        self
626    }
627
628    /// Borrows the typed row ID.
629    ///
630    /// # Examples
631    ///
632    /// ```
633    /// use ailloli_ui_widgets::controls::TableRow;
634    /// let row = TableRow::new(42);
635    /// assert_eq!(row.id(), &42);
636    /// ```
637    pub fn id(&self) -> &T {
638        &self.id
639    }
640
641    /// Borrows cells in insertion order.
642    ///
643    /// # Examples
644    ///
645    /// ```
646    /// use ailloli_ui_widgets::controls::{TableCell, TableRow};
647    /// let row = TableRow::new(1).cell(TableCell::text("One"));
648    /// assert_eq!(row.cells_ref().len(), 1);
649    /// ```
650    pub fn cells_ref(&self) -> &[TableCell] {
651        &self.cells
652    }
653}
654
655/// Shared context-aware callback for an activated row ID.
656type TableSelectHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T)>;
657
658/// Scrollable table with typed row activation and controlled visual selection.
659///
660/// `T` is cloned when a row is activated; `A` is the application action returned
661/// by non-context callbacks. [`Self::bind_selected`] installs writable selection,
662/// while [`Self::selected`] is read-only. Activating an enabled row writes and/or
663/// invokes configured handlers even when its ID already equals the selection.
664/// Overflowing body axes paint overlay scrollbars above the clipped rows while
665/// the header remains fixed. Thumb dragging and centered track clicks do not
666/// activate rows; a disabled table accepts neither interaction.
667///
668/// # Examples
669///
670/// ```
671/// use ailloli_ui_widgets::controls::{TableCell, TableColumn, TableRow, TableView};
672/// let table: TableView<i32> = TableView::new()
673///     .column(TableColumn::new("Value"))
674///     .row(TableRow::new(1).cell(TableCell::text("One")));
675/// let _ = table;
676/// ```
677pub struct TableView<T, A = ()> {
678    /// Root layout configured by table layout builders.
679    pub(crate) layout: LayoutStyle,
680    /// Flex-parent participation.
681    pub(crate) flex_item: FlexItemStyle,
682    /// Column definitions in display order.
683    columns: Vec<TableColumn>,
684    /// Rows in display order.
685    rows: Vec<TableRow<T>>,
686    /// Optional readable table-level selection.
687    selected: Option<Binding<T>>,
688    /// Optional writable selection signal.
689    bound_selected: Option<Signal<T>>,
690    /// Whole-table disabled binding.
691    disabled: Binding<bool>,
692    /// Row activation callback.
693    on_select: Option<TableSelectHandler<T, A>>,
694    /// Table appearance and geometry.
695    style: TableViewStyle,
696    /// Optional nonnegative body viewport height cap in logical pixels.
697    max_body_height: Option<f32>,
698    /// Whether unselected/inactive odd rows use alternate background.
699    zebra: bool,
700}
701
702impl<T: Clone + PartialEq + 'static, A: 'static> Default for TableView<T, A> {
703    fn default() -> Self {
704        Self::new()
705    }
706}
707
708impl<T: Clone + PartialEq + 'static, A: 'static> LayoutExt for TableView<T, A> {
709    fn layout_mut(&mut self) -> &mut LayoutStyle {
710        &mut self.layout
711    }
712}
713
714impl<T: Clone + PartialEq + 'static, A: 'static> TableView<T, A> {
715    /// Creates an enabled empty table with zebra stripes enabled.
716    ///
717    /// It has no columns, rows, selection, handler, or body-height cap.
718    ///
719    /// # Examples
720    ///
721    /// ```
722    /// use ailloli_ui_widgets::controls::TableView;
723    /// let table: TableView<i32> = TableView::new();
724    /// let _ = table;
725    /// ```
726    pub fn new() -> Self {
727        Self {
728            layout: LayoutStyle::default(),
729            flex_item: FlexItemStyle::default(),
730            columns: Vec::new(),
731            rows: Vec::new(),
732            selected: None,
733            bound_selected: None,
734            disabled: Binding::Static(false),
735            on_select: None,
736            style: TableViewStyle::default(),
737            max_body_height: None,
738            zebra: true,
739        }
740    }
741
742    /// Appends a column in display order.
743    ///
744    /// # Examples
745    ///
746    /// ```
747    /// use ailloli_ui_widgets::controls::{TableColumn, TableView};
748    /// let table: TableView<i32> = TableView::new().column(TableColumn::new("Name"));
749    /// let _ = table;
750    /// ```
751    pub fn column(mut self, column: TableColumn) -> Self {
752        self.columns.push(column);
753        self
754    }
755
756    /// Appends one row in display order.
757    ///
758    /// # Examples
759    ///
760    /// ```
761    /// use ailloli_ui_widgets::controls::{TableRow, TableView};
762    /// let table: TableView<i32> = TableView::new().row(TableRow::new(1));
763    /// let _ = table;
764    /// ```
765    pub fn row(mut self, row: TableRow<T>) -> Self {
766        self.rows.push(row);
767        self
768    }
769
770    /// Extends rows in iterator order without clearing existing rows.
771    ///
772    /// # Examples
773    ///
774    /// ```
775    /// use ailloli_ui_widgets::controls::{TableRow, TableView};
776    /// let table: TableView<i32> = TableView::new().rows([TableRow::new(1), TableRow::new(2)]);
777    /// let _ = table;
778    /// ```
779    pub fn rows(mut self, rows: impl IntoIterator<Item = TableRow<T>>) -> Self {
780        self.rows.extend(rows);
781        self
782    }
783
784    /// Sets a read-only static or reactive selection and clears writable binding.
785    ///
786    /// Every row with an equal ID paints selected. Row activation can still invoke
787    /// `on_select`, but cannot mutate this binding.
788    ///
789    /// # Examples
790    ///
791    /// ```
792    /// use ailloli_ui_widgets::controls::TableView;
793    /// let table: TableView<i32> = TableView::new().selected(1);
794    /// let _ = table;
795    /// ```
796    pub fn selected(mut self, selected: impl Into<Binding<T>>) -> Self {
797        self.selected = Some(selected.into());
798        self.bound_selected = None;
799        self
800    }
801
802    /// Binds a writable table-level selection signal.
803    ///
804    /// Activating an enabled row writes its ID even if equal to the current value,
805    /// before invoking the optional callback.
806    ///
807    /// # Examples
808    ///
809    /// ```
810    /// use ailloli_ui_runtime::component::State;
811    /// use ailloli_ui_widgets::controls::TableView;
812    /// let table: TableView<i32> = TableView::new().bind_selected(State::new(1));
813    /// let _ = table;
814    /// ```
815    pub fn bind_selected(mut self, selected: impl Into<Signal<T>>) -> Self {
816        let signal = selected.into();
817        self.selected = Some(Binding::Signal(signal.clone()));
818        self.bound_selected = Some(signal);
819        self
820    }
821
822    /// Sets static or reactive whole-table disabled state.
823    ///
824    /// Disabled tables are not focusable and ignore input; all rows paint with
825    /// disabled text/icon/progress treatment.
826    ///
827    /// # Examples
828    ///
829    /// ```
830    /// use ailloli_ui_widgets::controls::TableView;
831    /// let table: TableView<i32> = TableView::new().disabled(true);
832    /// let _ = table;
833    /// ```
834    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
835        self.disabled = disabled.into();
836        self
837    }
838
839    /// Uses a memo as the reactive whole-table disabled binding.
840    ///
841    /// # Examples
842    ///
843    /// ```
844    /// use ailloli_ui_runtime::component::Memo;
845    /// use ailloli_ui_widgets::controls::TableView;
846    /// let table: TableView<i32> = TableView::new().disabled_signal(Memo::new(|| false));
847    /// let _ = table;
848    /// ```
849    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
850        self.disabled(disabled)
851    }
852
853    /// Dispatches the application action returned for an activated enabled row.
854    ///
855    /// The handler runs even when the row ID already equals controlled selection.
856    /// Disabled or out-of-range rows emit nothing.
857    ///
858    /// # Examples
859    ///
860    /// ```
861    /// use ailloli_ui_widgets::controls::TableView;
862    /// let table: TableView<i32, i32> = TableView::new().on_select(|id| id);
863    /// let _ = table;
864    /// ```
865    pub fn on_select(mut self, f: impl Fn(T) -> A + 'static) -> Self {
866        self.on_select = Some(Rc::new(move |ctx, id| ctx.dispatch(f(id))));
867        self
868    }
869
870    /// Handles an activated enabled row with direct event-context access.
871    ///
872    /// # Examples
873    ///
874    /// ```
875    /// use ailloli_ui_widgets::controls::TableView;
876    /// let table: TableView<i32> = TableView::new().on_select_ctx(|_ctx, _id| {});
877    /// let _ = table;
878    /// ```
879    pub fn on_select_ctx(mut self, f: impl Fn(&mut EventCtx<A>, T) + 'static) -> Self {
880        self.on_select = Some(Rc::new(f));
881        self
882    }
883
884    /// Replaces table style without altering explicit layout values.
885    ///
886    /// # Examples
887    ///
888    /// ```
889    /// use ailloli_ui_widgets::controls::{TableView, TableViewStyle};
890    /// let table: TableView<i32> = TableView::new().table_style(TableViewStyle::default());
891    /// let _ = table;
892    /// ```
893    pub fn table_style(mut self, style: TableViewStyle) -> Self {
894        self.style = style;
895        self
896    }
897
898    /// Re-derives style from the default theme and requested density.
899    ///
900    /// This overwrites every prior table-style customization.
901    ///
902    /// # Examples
903    ///
904    /// ```
905    /// use ailloli_ui_widgets::controls::{TableView, TableViewSize};
906    /// let table: TableView<i32> = TableView::new().table_size(TableViewSize::Compact);
907    /// let _ = table;
908    /// ```
909    pub fn table_size(mut self, size: TableViewSize) -> Self {
910        self.style = TableViewStyle::from_theme(Theme::default(), size);
911        self
912    }
913
914    /// Sets an optional maximum intrinsic body height in logical pixels.
915    ///
916    /// Finite negatives become `0.0`; finite nonnegative values are retained;
917    /// NaN and either infinity clear the cap. Explicit layout height can still
918    /// override intrinsic sizing.
919    ///
920    /// # Examples
921    ///
922    /// ```
923    /// use ailloli_ui_widgets::controls::TableView;
924    /// let capped: TableView<i32> = TableView::new().max_body_height(144.0);
925    /// let uncapped: TableView<i32> = TableView::new().max_body_height(f32::NAN);
926    /// let _ = (capped, uncapped);
927    /// ```
928    pub fn max_body_height(mut self, height: f32) -> Self {
929        self.max_body_height = height.is_finite().then_some(height.max(0.0));
930        self
931    }
932
933    /// Enables or disables alternate background on odd unselected/inactive rows.
934    ///
935    /// # Examples
936    ///
937    /// ```
938    /// use ailloli_ui_widgets::controls::TableView;
939    /// let table: TableView<i32> = TableView::new().zebra(false);
940    /// let _ = table;
941    /// ```
942    pub fn zebra(mut self, enabled: bool) -> Self {
943        self.zebra = enabled;
944        self
945    }
946
947    /// Replaces the preferred table width.
948    ///
949    /// Numeric inputs are logical pixels; [`Length::Auto`] preserves intrinsic
950    /// sizing and [`Length::Fill`] requests the parent-provided width.
951    ///
952    /// # Examples
953    ///
954    /// ```
955    /// use ailloli_ui_widgets::controls::TableView;
956    /// let table: TableView<i32> = TableView::new().width(420.0);
957    /// let _ = table;
958    /// ```
959    pub fn width(mut self, value: impl Into<Length>) -> Self {
960        self.layout.width = value.into();
961        self
962    }
963
964    /// Replaces the preferred table height.
965    ///
966    /// Numeric inputs are logical pixels. An explicit height controls the whole
967    /// table, including its fixed header, and can override intrinsic body sizing.
968    ///
969    /// # Examples
970    ///
971    /// ```
972    /// use ailloli_ui_widgets::controls::TableView;
973    /// let table: TableView<i32> = TableView::new().height(280.0);
974    /// let _ = table;
975    /// ```
976    pub fn height(mut self, value: impl Into<Length>) -> Self {
977        self.layout.height = value.into();
978        self
979    }
980
981    /// Replaces the minimum-width declaration.
982    ///
983    /// # Examples
984    ///
985    /// ```
986    /// use ailloli_ui_widgets::controls::TableView;
987    /// let table: TableView<i32> = TableView::new().min_width(240.0);
988    /// let _ = table;
989    /// ```
990    pub fn min_width(mut self, value: impl Into<Length>) -> Self {
991        self.layout.min_width = value.into();
992        self
993    }
994
995    /// Replaces the maximum-width declaration.
996    ///
997    /// # Examples
998    ///
999    /// ```
1000    /// use ailloli_ui_widgets::controls::TableView;
1001    /// let table: TableView<i32> = TableView::new().max_width(960.0);
1002    /// let _ = table;
1003    /// ```
1004    pub fn max_width(mut self, value: impl Into<Length>) -> Self {
1005        self.layout.max_width = value.into();
1006        self
1007    }
1008
1009    /// Replaces the minimum-height declaration.
1010    ///
1011    /// # Examples
1012    ///
1013    /// ```
1014    /// use ailloli_ui_widgets::controls::TableView;
1015    /// let table: TableView<i32> = TableView::new().min_height(120.0);
1016    /// let _ = table;
1017    /// ```
1018    pub fn min_height(mut self, value: impl Into<Length>) -> Self {
1019        self.layout.min_height = value.into();
1020        self
1021    }
1022
1023    /// Replaces the maximum-height declaration.
1024    ///
1025    /// # Examples
1026    ///
1027    /// ```
1028    /// use ailloli_ui_widgets::controls::TableView;
1029    /// let table: TableView<i32> = TableView::new().max_height(640.0);
1030    /// let _ = table;
1031    /// ```
1032    pub fn max_height(mut self, value: impl Into<Length>) -> Self {
1033        self.layout.max_height = value.into();
1034        self
1035    }
1036
1037    /// Requests parent-fill sizing on both axes.
1038    ///
1039    /// # Examples
1040    ///
1041    /// ```
1042    /// use ailloli_ui_widgets::controls::TableView;
1043    /// let table: TableView<i32> = TableView::new().fill();
1044    /// let _ = table;
1045    /// ```
1046    pub fn fill(mut self) -> Self {
1047        self.layout.width = Length::Fill;
1048        self.layout.height = Length::Fill;
1049        self
1050    }
1051
1052    /// Requests parent-fill width while preserving the height declaration.
1053    ///
1054    /// # Examples
1055    ///
1056    /// ```
1057    /// use ailloli_ui_widgets::controls::TableView;
1058    /// let table: TableView<i32> = TableView::new().height(240.0).fill_width();
1059    /// let _ = table;
1060    /// ```
1061    pub fn fill_width(mut self) -> Self {
1062        self.layout.width = Length::Fill;
1063        self
1064    }
1065
1066    /// Requests parent-fill height while preserving the width declaration.
1067    ///
1068    /// # Examples
1069    ///
1070    /// ```
1071    /// use ailloli_ui_widgets::controls::TableView;
1072    /// let table: TableView<i32> = TableView::new().width(360.0).fill_height();
1073    /// let _ = table;
1074    /// ```
1075    pub fn fill_height(mut self) -> Self {
1076        self.layout.height = Length::Fill;
1077        self
1078    }
1079
1080    /// Replaces every outer margin edge with `value` logical pixels.
1081    ///
1082    /// The value is stored verbatim, including negative and non-finite input.
1083    ///
1084    /// # Examples
1085    ///
1086    /// ```
1087    /// use ailloli_ui_widgets::controls::TableView;
1088    /// let table: TableView<i32> = TableView::new().margin(8.0);
1089    /// let _ = table;
1090    /// ```
1091    pub fn margin(mut self, value: f32) -> Self {
1092        self.layout = self.layout.margin(value);
1093        self
1094    }
1095
1096    /// Replaces every inner padding edge with `value` logical pixels.
1097    ///
1098    /// The value is stored verbatim, including negative and non-finite input.
1099    ///
1100    /// # Examples
1101    ///
1102    /// ```
1103    /// use ailloli_ui_widgets::controls::TableView;
1104    /// let table: TableView<i32> = TableView::new().padding(12.0);
1105    /// let _ = table;
1106    /// ```
1107    pub fn padding(mut self, value: f32) -> Self {
1108        self.layout = self.layout.padding(value);
1109        self
1110    }
1111
1112    /// Sets this table's flex-grow weight to one.
1113    ///
1114    /// # Examples
1115    ///
1116    /// ```
1117    /// use ailloli_ui_widgets::controls::TableView;
1118    /// let table: TableView<i32> = TableView::new().flex_grow();
1119    /// let _ = table;
1120    /// ```
1121    pub fn flex_grow(mut self) -> Self {
1122        self.flex_item = self.flex_item.flex_grow(1.0);
1123        self
1124    }
1125
1126    /// Sets the dimensionless flex-grow weight, clamped to at least zero.
1127    ///
1128    /// NaN and negative infinity become zero; positive infinity is retained.
1129    ///
1130    /// # Examples
1131    ///
1132    /// ```
1133    /// use ailloli_ui_widgets::controls::TableView;
1134    /// let table: TableView<i32> = TableView::new().flex_grow_by(2.0);
1135    /// let _ = table;
1136    /// ```
1137    pub fn flex_grow_by(mut self, value: f32) -> Self {
1138        self.flex_item = self.flex_item.flex_grow(value);
1139        self
1140    }
1141
1142    /// Sets the dimensionless flex-shrink weight, clamped to at least zero.
1143    ///
1144    /// NaN and negative infinity become zero; positive infinity is retained.
1145    ///
1146    /// # Examples
1147    ///
1148    /// ```
1149    /// use ailloli_ui_widgets::controls::TableView;
1150    /// let table: TableView<i32> = TableView::new().flex_shrink(1.0);
1151    /// let _ = table;
1152    /// ```
1153    pub fn flex_shrink(mut self, value: f32) -> Self {
1154        self.flex_item = self.flex_item.flex_shrink(value);
1155        self
1156    }
1157
1158    /// Replaces the preferred main-axis size used by a flex parent.
1159    ///
1160    /// Numeric inputs are logical pixels.
1161    ///
1162    /// # Examples
1163    ///
1164    /// ```
1165    /// use ailloli_ui_widgets::controls::TableView;
1166    /// let table: TableView<i32> = TableView::new().flex_basis(320.0);
1167    /// let _ = table;
1168    /// ```
1169    pub fn flex_basis(mut self, value: impl Into<Length>) -> Self {
1170        self.flex_item = self.flex_item.flex_basis(value);
1171        self
1172    }
1173
1174    /// Overrides the flex parent's cross-axis alignment for this table.
1175    ///
1176    /// # Examples
1177    ///
1178    /// ```
1179    /// use ailloli_ui_core::style::AlignItems;
1180    /// use ailloli_ui_widgets::controls::TableView;
1181    /// let table: TableView<i32> = TableView::new().align_self(AlignItems::Center);
1182    /// let _ = table;
1183    /// ```
1184    pub fn align_self(mut self, value: ailloli_ui_core::style::AlignItems) -> Self {
1185        self.flex_item = self.flex_item.align_self(value);
1186        self
1187    }
1188}
1189
1190impl<T: Clone + PartialEq + 'static, A: 'static> IntoView<A> for TableView<T, A> {
1191    /// Builds the retained component and preserves layout/flex metadata.
1192    fn into_view(self) -> View<A> {
1193        finish_view_sized(
1194            View::component(TableViewComponent {
1195                layout: self.layout,
1196                columns: self.columns,
1197                rows: self.rows,
1198                selected: self.selected,
1199                bound_selected: self.bound_selected,
1200                disabled: self.disabled,
1201                on_select: self.on_select,
1202                style: self.style,
1203                max_body_height: self.max_body_height,
1204                zebra: self.zebra,
1205            }),
1206            self.flex_item,
1207            LayoutSizeHint::from_layout(self.layout),
1208        )
1209    }
1210}
1211
1212/// Component-stage table configuration copied into the retained widget.
1213struct TableViewComponent<T, A> {
1214    /// Root size, bounds, and inset declarations.
1215    layout: LayoutStyle,
1216    /// Column definitions in display order.
1217    columns: Vec<TableColumn>,
1218    /// Rows in display order.
1219    rows: Vec<TableRow<T>>,
1220    /// Optional readable table-level selection.
1221    selected: Option<Binding<T>>,
1222    /// Optional writable table-level selection.
1223    bound_selected: Option<Signal<T>>,
1224    /// Whole-table disabled state.
1225    disabled: Binding<bool>,
1226    /// Optional activation handler.
1227    on_select: Option<TableSelectHandler<T, A>>,
1228    /// Appearance and geometry tokens.
1229    style: TableViewStyle,
1230    /// Optional body viewport height cap in logical pixels.
1231    max_body_height: Option<f32>,
1232    /// Whether eligible odd rows use alternate background.
1233    zebra: bool,
1234}
1235
1236impl<T: Clone + PartialEq + 'static, A: 'static> ComponentNode<A> for TableViewComponent<T, A> {
1237    /// Allocates scroll, keyboard-active, and measured-geometry signals.
1238    fn build(&self, context: &mut Context<A>) -> View<A> {
1239        View::leaf(TableViewWidget {
1240            layout: self.layout,
1241            columns: self.columns.clone(),
1242            rows: self.rows.clone(),
1243            selected: self.selected.clone(),
1244            bound_selected: self.bound_selected.clone(),
1245            disabled: self.disabled.clone(),
1246            on_select: self.on_select.clone(),
1247            style: self.style.clone(),
1248            max_body_height: self.max_body_height,
1249            zebra: self.zebra,
1250            scroll: context.signal_with_invalidation(ScrollState::new(), Invalidation::Paint),
1251            active_index: context.signal(None),
1252            metrics: context.signal_with_invalidation(TableMetrics::default(), Invalidation::Paint),
1253            behavior: ScrollBehavior::new(ScrollAxes::BOTH),
1254            scrollbar_interaction: context
1255                .signal_with_invalidation(ScrollbarInteraction::default(), Invalidation::Paint),
1256            pending_layout: Cell::new(None),
1257        })
1258    }
1259}
1260
1261#[derive(Debug, Clone, Copy, Default, PartialEq)]
1262/// Last laid-out body viewport and scrollable content extents.
1263struct TableMetrics {
1264    /// Visible body size, excluding the fixed header, in logical pixels.
1265    viewport: Size,
1266    /// Total scrollable body size in logical pixels.
1267    content: Size,
1268}
1269
1270#[derive(Debug, Clone)]
1271/// Display-ready column label and resolved horizontal geometry.
1272struct ResolvedColumn {
1273    /// Header label copied from the column definition.
1274    label: String,
1275    /// Horizontal content offset from the table's left edge.
1276    x: f32,
1277    /// Resolved logical-pixel width after minimum enforcement.
1278    width: f32,
1279    /// Header and fallback cell alignment.
1280    align: TableAlign,
1281}
1282
1283/// Per-paint table geometry shared by header and body rendering.
1284struct TableGeometry {
1285    /// Resolved columns in display order.
1286    columns: Vec<ResolvedColumn>,
1287    /// Total horizontal scroll extent in logical pixels.
1288    content_width: f32,
1289    /// Fixed header rectangle in window coordinates.
1290    header_rect: Rect,
1291    /// Scrollable body viewport in window coordinates.
1292    body_rect: Rect,
1293}
1294
1295#[derive(Debug, Clone, Copy)]
1296/// Common geometry and state used while painting one rich cell.
1297struct CellPaint {
1298    /// Cell rectangle after first-column icon adjustment.
1299    rect: Rect,
1300    /// Effective per-cell horizontal alignment.
1301    align: TableAlign,
1302    /// Alpha multiplier, normally one or disabled opacity.
1303    opacity: f32,
1304    /// Whether disabled typography/progress treatment applies.
1305    disabled: bool,
1306}
1307
1308/// Retained table widget with reactive state and input/paint behavior.
1309struct TableViewWidget<T, A> {
1310    /// Root size, bounds, and inset declarations.
1311    layout: LayoutStyle,
1312    /// Column definitions in display order.
1313    columns: Vec<TableColumn>,
1314    /// Rows in display order.
1315    rows: Vec<TableRow<T>>,
1316    /// Optional readable table-level selection.
1317    selected: Option<Binding<T>>,
1318    /// Optional writable table-level selection.
1319    bound_selected: Option<Signal<T>>,
1320    /// Whole-table disabled state.
1321    disabled: Binding<bool>,
1322    /// Optional activation handler.
1323    on_select: Option<TableSelectHandler<T, A>>,
1324    /// Appearance and geometry tokens.
1325    style: TableViewStyle,
1326    /// Optional body viewport height cap in logical pixels.
1327    max_body_height: Option<f32>,
1328    /// Whether eligible odd rows use alternate background.
1329    zebra: bool,
1330    /// Two-axis body scroll state.
1331    scroll: Signal<ScrollState>,
1332    /// Keyboard-active row index, if explicitly set.
1333    active_index: Signal<Option<usize>>,
1334    /// Last layout's body viewport and content extents.
1335    metrics: Signal<TableMetrics>,
1336    /// Wheel/reveal policy, constrained to both axes.
1337    behavior: ScrollBehavior,
1338    /// Retained hover and captured overlay-scrollbar gesture.
1339    scrollbar_interaction: Signal<ScrollbarInteraction>,
1340    /// Geometry-derived state owned by one exact authoritative attempt.
1341    pending_layout: Cell<Option<TransactionalLayoutPending<PendingTableLayout>>>,
1342}
1343
1344/// State published only by the successful attempt that computed it.
1345#[derive(Clone, Copy)]
1346struct PendingTableLayout {
1347    /// Final authoritative body metrics.
1348    metrics: Option<TableMetrics>,
1349    /// Final authoritative clamp.
1350    scroll: Option<ScrollState>,
1351    /// Geometry-dependent gesture cleanup.
1352    scrollbar_interaction: Option<ScrollbarInteraction>,
1353}
1354
1355impl<T: Clone + PartialEq + 'static, A: 'static> Widget<A> for TableViewWidget<T, A> {
1356    /// Returns the stable diagnostic widget name.
1357    fn debug_name(&self) -> &'static str {
1358        "TableView"
1359    }
1360
1361    /// Resolves columns, root size, body metrics, and clamped scroll state.
1362    fn layout(
1363        &self,
1364        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1365        ctx: &mut LayoutCtx<'_>,
1366        _children: &mut [LayoutChild],
1367        constraints: Constraints,
1368    ) -> LayoutResult {
1369        let intrinsic_columns = self.resolve_columns_layout(ctx, constraints.max_w);
1370        let content_width = sum_column_widths(&intrinsic_columns);
1371        let body_content_height = self.body_content_height();
1372        let body_intrinsic = self
1373            .max_body_height
1374            .map(|max_h| body_content_height.min(max_h))
1375            .unwrap_or(body_content_height);
1376        let intrinsic = Size::new(
1377            content_width.max(self.style.min_column_width),
1378            self.style.header_height + body_intrinsic,
1379        );
1380        let size = apply_layout_size(intrinsic, self.layout, constraints);
1381        let final_columns = self.resolve_columns_layout(ctx, size.w);
1382        let final_content_width = sum_column_widths(&final_columns).max(size.w);
1383        let body_h = (size.h - self.style.header_height).max(0.0);
1384        let metrics = TableMetrics {
1385            viewport: Size::new(size.w, body_h),
1386            content: Size::new(final_content_width, body_content_height),
1387        };
1388        let retained_scroll = with_untracked_reads(|| self.scroll.read());
1389        let scroll = retained_scroll
1390            .clamp_to(
1391                ScrollMetrics::new(metrics.viewport, metrics.content),
1392                ScrollAxes::BOTH,
1393            )
1394            .state();
1395
1396        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
1397        let geometries = self.scrollbar_geometries_for_state(paint_bounds, metrics, scroll);
1398        let interactive_geometries = if self.disabled.read() {
1399            Vec::new()
1400        } else {
1401            geometries
1402        };
1403        let mut interaction = with_untracked_reads(|| self.scrollbar_interaction.read());
1404        let interaction_changed = interaction.reconcile(ctx.layout_pass(), &interactive_geometries);
1405        if ctx.layout_pass().is_committed() {
1406            let retained_metrics = with_untracked_reads(|| self.metrics.read());
1407            self.pending_layout.set(TransactionalLayoutPending::new(
1408                ctx,
1409                PendingTableLayout {
1410                    metrics: (retained_metrics != metrics).then_some(metrics),
1411                    scroll: (retained_scroll != scroll).then_some(scroll),
1412                    scrollbar_interaction: interaction_changed.then_some(interaction),
1413                },
1414            ));
1415        }
1416        LayoutResult {
1417            size,
1418            children: Vec::new(),
1419            paint_bounds,
1420            visual_bounds: self.visual_bounds(paint_bounds),
1421            overlay_hit_bounds: interactive_geometries
1422                .iter()
1423                .map(|geometry| geometry.hit_track)
1424                .collect(),
1425            clip: None,
1426            is_window_root_clip: false,
1427            artifact: None,
1428        }
1429    }
1430
1431    /// Publishes geometry-derived internal state only after authoritative commit.
1432    fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
1433        let Some(pending) = self
1434            .pending_layout
1435            .take()
1436            .and_then(|pending| pending.into_committed(ctx))
1437        else {
1438            return;
1439        };
1440        if let Some(metrics) = pending.metrics {
1441            self.metrics.set(metrics);
1442        }
1443        if let Some(scroll) = pending.scroll {
1444            self.scroll.set(scroll);
1445        }
1446        if let Some(interaction) = pending.scrollbar_interaction {
1447            self.scrollbar_interaction.set(interaction);
1448        }
1449    }
1450
1451    /// Paints shadows, surfaces, fixed header, scrolling body, and borders.
1452    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
1453        let disabled = self.disabled.read();
1454        let geometry = self.geometry_paint(ctx, bounds);
1455        let scroll = self.scroll.read().offset;
1456
1457        for shadow in self.style.shadows.iter().copied().filter(|s| !s.inset) {
1458            if shadow.color.a > 0.0 {
1459                ctx.push(DrawCmd::BoxShadow(DrawBoxShadow {
1460                    rect: bounds,
1461                    radius: self.style.radius,
1462                    shadow,
1463                }));
1464            }
1465        }
1466
1467        ctx.push(DrawCmd::RRect(DrawRRect {
1468            rect: bounds,
1469            radius: self.style.radius.tl,
1470            color: self.style.background,
1471        }));
1472
1473        self.paint_header(ctx, &geometry, scroll.x, disabled);
1474        self.paint_body(ctx, &geometry, scroll, disabled);
1475        self.paint_scrollbars(ctx, bounds, disabled);
1476
1477        ctx.push(DrawCmd::Border(DrawBorder {
1478            rect: bounds,
1479            radius: self.style.radius,
1480            border: self.style.border,
1481        }));
1482
1483        if ctx.is_focused() && !disabled {
1484            ctx.push(DrawCmd::Border(DrawBorder {
1485                rect: bounds,
1486                radius: self.style.radius,
1487                border: self.style.focus_ring,
1488            }));
1489        }
1490    }
1491
1492    /// Handles body scrolling, enabled-row activation, and keyboard navigation.
1493    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1494        if self.disabled.read() {
1495            return;
1496        }
1497        if matches!(event, Event::Pointer(_)) {
1498            let metrics = self.metrics.read();
1499            let geometries = self.scrollbar_geometries(bounds, metrics);
1500            let current = self.scroll.read();
1501            let mut interaction = self.scrollbar_interaction.read();
1502            let response = interaction.handle_event(ctx, event, &geometries);
1503            if response.state_changed {
1504                self.scrollbar_interaction.set(interaction);
1505            }
1506            if let Some((axis, target)) = response.scroll_to {
1507                let target = match axis {
1508                    ScrollbarAxis::Horizontal => Offset::new(target, current.offset.y),
1509                    ScrollbarAxis::Vertical => Offset::new(current.offset.x, target),
1510                };
1511                let outcome = current.scroll_to(
1512                    target,
1513                    ScrollMetrics::new(metrics.viewport, metrics.content),
1514                    ScrollAxes::BOTH,
1515                );
1516                if outcome.changed {
1517                    self.scroll.set(outcome.state());
1518                }
1519            }
1520            if response.repaint {
1521                ctx.request_repaint();
1522            }
1523            if response.consumed {
1524                ctx.stop_propagation();
1525                return;
1526            }
1527        }
1528        match event {
1529            Event::Pointer(PointerEvent::Wheel {
1530                pos,
1531                delta,
1532                modifiers,
1533                ..
1534            }) => {
1535                let body = self.body_rect(bounds);
1536                if !body.contains(pos.x, pos.y) {
1537                    return;
1538                }
1539                let metrics = self.metrics.read();
1540                let out = self.scroll.read().scroll_by(
1541                    self.behavior.wheel_delta_with_modifiers(*delta, *modifiers),
1542                    ScrollMetrics::new(metrics.viewport, metrics.content),
1543                    ScrollAxes::BOTH,
1544                );
1545                if out.changed {
1546                    self.scroll.set(out.state());
1547                    ctx.request_repaint();
1548                    ctx.stop_propagation();
1549                }
1550            }
1551            Event::Pointer(PointerEvent::Button {
1552                pos,
1553                button: MouseButton::Left,
1554                pressed: false,
1555                ..
1556            }) => {
1557                if let Some(idx) = self.row_index_at(bounds, pos.y) {
1558                    if self.set_active(Some(idx), ctx) {
1559                        ctx.stop_propagation();
1560                    }
1561                    if self.select_row(ctx, idx) {
1562                        ctx.stop_propagation();
1563                    }
1564                }
1565            }
1566            Event::Keyboard(key) if key.state == KeyState::Pressed => {
1567                self.handle_keyboard(ctx, key);
1568            }
1569            _ => {}
1570        }
1571    }
1572
1573    /// Is focusable only when the table and at least one row are enabled.
1574    fn focus_policy(&self) -> FocusPolicy {
1575        if self.disabled.read() || self.rows.iter().all(|row| row.disabled.read()) {
1576            FocusPolicy::NotFocusable
1577        } else {
1578            FocusPolicy::Focusable
1579        }
1580    }
1581}
1582
1583impl<T: Clone + PartialEq + 'static, A: 'static> TableViewWidget<T, A> {
1584    /// Resolves body-overlay bars for each overflowing axis.
1585    fn scrollbar_geometries(&self, bounds: Rect, table: TableMetrics) -> Vec<ScrollbarGeometry> {
1586        self.scrollbar_geometries_for_state(bounds, table, self.scroll.read())
1587    }
1588
1589    /// Resolves body-overlay bars for explicit transaction-local scroll state.
1590    fn scrollbar_geometries_for_state(
1591        &self,
1592        bounds: Rect,
1593        table: TableMetrics,
1594        scroll: ScrollState,
1595    ) -> Vec<ScrollbarGeometry> {
1596        let body = self.body_rect(bounds);
1597        let metrics = ScrollMetrics::new(table.viewport, table.content);
1598        let max = metrics.max_offset();
1599        let show_horizontal = max.x > 0.5;
1600        let show_vertical = max.y > 0.5;
1601        let mut geometries = Vec::with_capacity(2);
1602        if show_vertical {
1603            let reserve = if show_horizontal { 9.0 } else { 0.0 };
1604            if let Some(geometry) =
1605                ScrollbarGeometrySpec::new(ScrollbarAxis::Vertical, body, metrics, scroll)
1606                    .with_paint_metrics(6.0, 24.0, 3.0)
1607                    .with_end_reserve(reserve)
1608                    .resolve()
1609            {
1610                geometries.push(geometry);
1611            }
1612        }
1613        if show_horizontal {
1614            let reserve = if show_vertical { 9.0 } else { 0.0 };
1615            if let Some(geometry) =
1616                ScrollbarGeometrySpec::new(ScrollbarAxis::Horizontal, body, metrics, scroll)
1617                    .with_paint_metrics(6.0, 24.0, 3.0)
1618                    .with_end_reserve(reserve)
1619                    .resolve()
1620            {
1621                geometries.push(geometry);
1622            }
1623        }
1624        geometries
1625    }
1626
1627    /// Paints derived-color table scrollbars above body contents.
1628    fn paint_scrollbars(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, disabled: bool) {
1629        let interaction = self.scrollbar_interaction.read();
1630        for geometry in self.scrollbar_geometries(bounds, self.metrics.read()) {
1631            let visual = interaction.visual_state(geometry.axis, ctx.is_hovered() && !disabled);
1632            ctx.push(DrawCmd::RRect(DrawRRect {
1633                rect: geometry.track,
1634                radius: 3.0,
1635                color: self.style.grid_color.with_alpha(0.22),
1636            }));
1637            ctx.push(DrawCmd::RRect(DrawRRect {
1638                rect: geometry.thumb,
1639                radius: 3.0,
1640                color: thumb_color_for_state(self.style.muted_text.color.with_alpha(0.58), visual),
1641            }));
1642        }
1643    }
1644
1645    /// Resolves column widths using the layout context's optional text system.
1646    fn resolve_columns_layout(
1647        &self,
1648        ctx: &mut LayoutCtx<'_>,
1649        available_width: f32,
1650    ) -> Vec<ResolvedColumn> {
1651        let text_system = ctx.text_system.as_deref_mut();
1652        self.resolve_columns_with(text_system, available_width)
1653    }
1654
1655    /// Resolves columns and fixed/body rectangles for the current paint bounds.
1656    fn geometry_paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect) -> TableGeometry {
1657        let columns = {
1658            let text_system = ctx.text_system.as_deref_mut();
1659            self.resolve_columns_with(text_system, bounds.w)
1660        };
1661        let content_width = sum_column_widths(&columns).max(bounds.w);
1662        TableGeometry {
1663            columns,
1664            content_width,
1665            header_rect: Rect::new(
1666                bounds.x,
1667                bounds.y,
1668                bounds.w,
1669                self.style.header_height.min(bounds.h),
1670            ),
1671            body_rect: self.body_rect(bounds),
1672        }
1673    }
1674
1675    /// Resolves fixed, auto, and flex policies and assigns cumulative x offsets.
1676    ///
1677    /// Every result is floored by `min_column_width`. Positive flex weights
1678    /// divide finite remaining width; without finite available width they retain
1679    /// the minimum.
1680    fn resolve_columns_with(
1681        &self,
1682        mut text_system: Option<&mut TextSystem>,
1683        available_width: f32,
1684    ) -> Vec<ResolvedColumn> {
1685        let mut base_widths = Vec::with_capacity(self.columns.len());
1686        let mut flex_total = 0.0f32;
1687        let mut fixed_auto_total = 0.0f32;
1688
1689        for (col_idx, column) in self.columns.iter().enumerate() {
1690            let width = match column.width {
1691                TableColumnWidth::Fixed(width) => width.max(0.0),
1692                TableColumnWidth::Auto => {
1693                    self.auto_column_width(text_system.as_deref_mut(), col_idx, column)
1694                }
1695                TableColumnWidth::Flex(weight) => {
1696                    flex_total += weight.max(0.0);
1697                    self.style.min_column_width
1698                }
1699            };
1700            if !matches!(column.width, TableColumnWidth::Flex(_)) {
1701                fixed_auto_total += width;
1702            }
1703            base_widths.push(width.max(self.style.min_column_width));
1704        }
1705
1706        if flex_total > 0.0 && available_width.is_finite() {
1707            let flex_indices = self.columns.iter().enumerate().filter_map(|(idx, col)| {
1708                if let TableColumnWidth::Flex(weight) = col.width {
1709                    Some((idx, weight.max(0.0)))
1710                } else {
1711                    None
1712                }
1713            });
1714            let remaining = (available_width - fixed_auto_total).max(0.0);
1715            for (idx, weight) in flex_indices {
1716                let share = if flex_total > 0.0 {
1717                    remaining * (weight / flex_total)
1718                } else {
1719                    0.0
1720                };
1721                base_widths[idx] = share.max(self.style.min_column_width);
1722            }
1723        }
1724
1725        let mut x = 0.0;
1726        self.columns
1727            .iter()
1728            .zip(base_widths)
1729            .map(|(column, width)| {
1730                let out = ResolvedColumn {
1731                    label: column.label.clone(),
1732                    x,
1733                    width,
1734                    align: column.align,
1735                };
1736                x += width;
1737                out
1738            })
1739            .collect()
1740    }
1741
1742    /// Measures a header and all present cells, with deterministic fallbacks.
1743    ///
1744    /// First-column leading-icon allowance and horizontal padding are added to
1745    /// the widest measured content.
1746    fn auto_column_width(
1747        &self,
1748        mut text_system: Option<&mut TextSystem>,
1749        col_idx: usize,
1750        column: &TableColumn,
1751    ) -> f32 {
1752        let mut width = measure_text_system(
1753            text_system.as_deref_mut(),
1754            &column.label,
1755            self.style.header_text,
1756        )
1757        .unwrap_or(48.0);
1758        for row in &self.rows {
1759            if let Some(cell) = row.cells.get(col_idx) {
1760                width = width.max(self.measure_cell(text_system.as_deref_mut(), cell));
1761            }
1762        }
1763        if col_idx == 0 && self.rows.iter().any(|row| row.leading_icon.is_some()) {
1764            width += self.style.icon_size + self.style.icon_gap;
1765        }
1766        width + self.style.cell_padding_x * 2.0
1767    }
1768
1769    /// Measures one cell's intrinsic content width or returns kind-specific fallback.
1770    fn measure_cell(&self, text_system: Option<&mut TextSystem>, cell: &TableCell) -> f32 {
1771        match cell.kind {
1772            TableCellKind::Text => {
1773                measure_text_system(text_system, &cell.label, self.style.text).unwrap_or(48.0)
1774            }
1775            TableCellKind::Muted => {
1776                measure_text_system(text_system, &cell.label, self.style.muted_text).unwrap_or(48.0)
1777            }
1778            TableCellKind::Badge(_) => {
1779                measure_text_system(text_system, &cell.label, self.style.badge_text).unwrap_or(32.0)
1780                    + 18.0
1781            }
1782            TableCellKind::Progress(_) => self.style.progress_width,
1783        }
1784    }
1785
1786    /// Paints the horizontally scrolling header inside its fixed viewport.
1787    fn paint_header(
1788        &self,
1789        ctx: &mut PaintCtx<'_>,
1790        geometry: &TableGeometry,
1791        scroll_x: f32,
1792        disabled: bool,
1793    ) {
1794        let header = geometry.header_rect;
1795        if header.w <= 0.0 || header.h <= 0.0 {
1796            return;
1797        }
1798        ctx.push(DrawCmd::Rect(DrawRect {
1799            rect: header,
1800            color: self.style.header_background,
1801        }));
1802        ctx.with_clip(header, |ctx| {
1803            for col in &geometry.columns {
1804                let cell = Rect::new(header.x + col.x - scroll_x, header.y, col.width, header.h);
1805                paint_text_cell(
1806                    ctx,
1807                    &col.label,
1808                    self.style.header_text,
1809                    cell,
1810                    col.align,
1811                    self.style.cell_padding_x,
1812                    if disabled {
1813                        self.style.disabled_opacity
1814                    } else {
1815                        1.0
1816                    },
1817                );
1818                if cell.right() < header.x || cell.x > header.right() {
1819                    continue;
1820                }
1821                ctx.push(DrawCmd::Rect(DrawRect {
1822                    rect: Rect::new(cell.right() - 1.0, header.y, 1.0, header.h),
1823                    color: self.style.grid_color,
1824                }));
1825            }
1826        });
1827        ctx.push(DrawCmd::Rect(DrawRect {
1828            rect: Rect::new(header.x, header.bottom() - 1.0, header.w, 1.0),
1829            color: self.style.grid_color,
1830        }));
1831    }
1832
1833    /// Paints visible rows with vertical/horizontal scroll offsets and state precedence.
1834    ///
1835    /// Selection wins over keyboard-active state, which wins over zebra styling.
1836    fn paint_body(
1837        &self,
1838        ctx: &mut PaintCtx<'_>,
1839        geometry: &TableGeometry,
1840        scroll: Offset,
1841        disabled: bool,
1842    ) {
1843        let body = geometry.body_rect;
1844        if body.w <= 0.0 || body.h <= 0.0 {
1845            return;
1846        }
1847        let active = self.normalized_active_index();
1848        let selected = self.selected_value();
1849        ctx.with_clip(body, |ctx| {
1850            for (idx, row) in self.rows.iter().enumerate() {
1851                let y = body.y + idx as f32 * self.style.row_height - scroll.y;
1852                let row_rect = Rect::new(body.x, y, body.w, self.style.row_height);
1853                if row_rect.bottom() < body.y || row_rect.y > body.bottom() {
1854                    continue;
1855                }
1856                let row_disabled = disabled || row.disabled.read();
1857                let row_selected = row.selected.read()
1858                    || selected
1859                        .as_ref()
1860                        .is_some_and(|selected| selected == &row.id);
1861                let is_active = active == Some(idx);
1862                let opacity = if row_disabled {
1863                    self.style.disabled_opacity
1864                } else {
1865                    1.0
1866                };
1867                let bg = if row_selected {
1868                    self.style.row_selected_background
1869                } else if is_active {
1870                    self.style.row_active_background
1871                } else if self.zebra && idx % 2 == 1 {
1872                    self.style.row_alt_background
1873                } else {
1874                    self.style.row_background
1875                };
1876                if bg.a > 0.0 {
1877                    ctx.push(DrawCmd::Rect(DrawRect {
1878                        rect: row_rect,
1879                        color: bg.with_alpha(bg.a * opacity),
1880                    }));
1881                }
1882                self.paint_row_cells(
1883                    ctx,
1884                    geometry,
1885                    row,
1886                    idx,
1887                    row_rect,
1888                    scroll.x,
1889                    opacity,
1890                    row_selected,
1891                    row_disabled,
1892                );
1893                ctx.push(DrawCmd::Rect(DrawRect {
1894                    rect: Rect::new(row_rect.x, row_rect.bottom() - 1.0, row_rect.w, 1.0),
1895                    color: self.style.grid_color,
1896                }));
1897            }
1898        });
1899    }
1900
1901    #[allow(clippy::too_many_arguments)]
1902    /// Paints visible cells, leading icon, grid lines, and the first-row top edge.
1903    fn paint_row_cells(
1904        &self,
1905        ctx: &mut PaintCtx<'_>,
1906        geometry: &TableGeometry,
1907        row: &TableRow<T>,
1908        row_idx: usize,
1909        row_rect: Rect,
1910        scroll_x: f32,
1911        opacity: f32,
1912        selected: bool,
1913        disabled: bool,
1914    ) {
1915        for (col_idx, col) in geometry.columns.iter().enumerate() {
1916            let cell_rect = Rect::new(
1917                row_rect.x + col.x - scroll_x,
1918                row_rect.y,
1919                col.width,
1920                row_rect.h,
1921            );
1922            if cell_rect.right() < geometry.body_rect.x || cell_rect.x > geometry.body_rect.right()
1923            {
1924                continue;
1925            }
1926            if col_idx > 0 {
1927                ctx.push(DrawCmd::Rect(DrawRect {
1928                    rect: Rect::new(cell_rect.x, row_rect.y, 1.0, row_rect.h),
1929                    color: self
1930                        .style
1931                        .grid_color
1932                        .with_alpha(self.style.grid_color.a * 0.72),
1933                }));
1934            }
1935            let mut content_rect = cell_rect;
1936            if col_idx == 0 {
1937                if let Some(icon) = &row.leading_icon {
1938                    let icon_rect = Rect::new(
1939                        cell_rect.x + self.style.cell_padding_x,
1940                        row_rect.y + (row_rect.h - self.style.icon_size) * 0.5,
1941                        self.style.icon_size,
1942                        self.style.icon_size,
1943                    );
1944                    let tint = if selected {
1945                        self.style.selected_icon_tint
1946                    } else {
1947                        self.style.icon_tint
1948                    };
1949                    ctx.push(DrawCmd::Image(DrawImage {
1950                        rect: icon_rect,
1951                        icon: icon.clone(),
1952                        tint: tint.with_alpha(tint.a * opacity),
1953                        rotation_rad: 0.0,
1954                    }));
1955                    content_rect.x += self.style.icon_size + self.style.icon_gap;
1956                    content_rect.w =
1957                        (content_rect.w - self.style.icon_size - self.style.icon_gap).max(0.0);
1958                }
1959            }
1960            let Some(cell) = row.cells.get(col_idx) else {
1961                continue;
1962            };
1963            let align = cell.align.unwrap_or(col.align);
1964            ctx.with_clip(cell_rect, |ctx| {
1965                self.paint_cell(
1966                    ctx,
1967                    cell,
1968                    CellPaint {
1969                        rect: content_rect,
1970                        align,
1971                        opacity,
1972                        disabled,
1973                    },
1974                );
1975            });
1976        }
1977        if row_idx == 0 {
1978            ctx.push(DrawCmd::Rect(DrawRect {
1979                rect: Rect::new(
1980                    row_rect.x,
1981                    row_rect.y,
1982                    geometry.content_width.max(row_rect.w),
1983                    1.0,
1984                ),
1985                color: self.style.grid_color,
1986            }));
1987        }
1988    }
1989
1990    /// Dispatches a cell to text, badge, or progress rendering.
1991    fn paint_cell(&self, ctx: &mut PaintCtx<'_>, cell: &TableCell, paint: CellPaint) {
1992        match cell.kind {
1993            TableCellKind::Text => paint_text_cell(
1994                ctx,
1995                &cell.label,
1996                if paint.disabled {
1997                    self.style.disabled_text
1998                } else {
1999                    self.style.text
2000                },
2001                paint.rect,
2002                paint.align,
2003                self.style.cell_padding_x,
2004                paint.opacity,
2005            ),
2006            TableCellKind::Muted => paint_text_cell(
2007                ctx,
2008                &cell.label,
2009                if paint.disabled {
2010                    self.style.disabled_text
2011                } else {
2012                    self.style.muted_text
2013                },
2014                paint.rect,
2015                paint.align,
2016                self.style.cell_padding_x,
2017                paint.opacity,
2018            ),
2019            TableCellKind::Badge(tone) => {
2020                self.paint_badge_cell(ctx, &cell.label, tone, paint);
2021            }
2022            TableCellKind::Progress(value) => {
2023                self.paint_progress_cell(ctx, value, paint);
2024            }
2025        }
2026    }
2027
2028    /// Paints a measured 18-pixel pill; missing text services paint nothing.
2029    fn paint_badge_cell(
2030        &self,
2031        ctx: &mut PaintCtx<'_>,
2032        label: &str,
2033        tone: BadgeTone,
2034        paint: CellPaint,
2035    ) {
2036        let Some(layout) = layout_text(ctx, label, self.style.badge_text) else {
2037            return;
2038        };
2039        let badge_w = layout.metrics.width.max(10.0) + 18.0;
2040        let badge_h = 18.0;
2041        let x = aligned_x(paint.rect, badge_w, paint.align, self.style.cell_padding_x);
2042        let y = paint.rect.y + (paint.rect.h - badge_h) * 0.5;
2043        let color =
2044            tone_color(tone).with_alpha(if paint.disabled { 0.18 } else { 0.28 } * paint.opacity);
2045        ctx.push(DrawCmd::RRect(DrawRRect {
2046            rect: Rect::new(x, y, badge_w, badge_h),
2047            radius: badge_h * 0.5,
2048            color,
2049        }));
2050        let baseline = layout
2051            .lines
2052            .first()
2053            .map(|line| line.baseline_y)
2054            .unwrap_or(0.0);
2055        ctx.push(DrawCmd::Text(DrawText {
2056            pos: [
2057                x + (badge_w - layout.metrics.width) * 0.5,
2058                y + (badge_h - layout.metrics.height) * 0.5 + baseline,
2059            ],
2060            color: self
2061                .style
2062                .badge_text
2063                .color
2064                .with_alpha(self.style.badge_text.color.a * paint.opacity),
2065            decoration: ailloli_ui_core::TextDecoration::None,
2066            layout,
2067        }));
2068    }
2069
2070    /// Paints a bounded progress track and clamped fill.
2071    ///
2072    /// A NaN value leaves the track visible but fails the positive-fill test.
2073    fn paint_progress_cell(&self, ctx: &mut PaintCtx<'_>, value: f32, paint: CellPaint) {
2074        let w = self
2075            .style
2076            .progress_width
2077            .min((paint.rect.w - self.style.cell_padding_x * 2.0).max(0.0));
2078        let h = self.style.progress_height;
2079        if w <= 0.0 || h <= 0.0 {
2080            return;
2081        }
2082        let x = aligned_x(paint.rect, w, paint.align, self.style.cell_padding_x);
2083        let y = paint.rect.y + (paint.rect.h - h) * 0.5;
2084        let track = Rect::new(x, y, w, h);
2085        ctx.push(DrawCmd::RRect(DrawRRect {
2086            rect: track,
2087            radius: h * 0.5,
2088            color: self
2089                .style
2090                .progress_track
2091                .with_alpha(self.style.progress_track.a * paint.opacity),
2092        }));
2093        let fill_w = w * value.clamp(0.0, 1.0);
2094        if fill_w > 0.0 {
2095            ctx.push(DrawCmd::RRect(DrawRRect {
2096                rect: Rect::new(x, y, fill_w, h),
2097                radius: h * 0.5,
2098                color: if paint.disabled {
2099                    self.style.progress_fill.with_alpha(0.36 * paint.opacity)
2100                } else {
2101                    self.style
2102                        .progress_fill
2103                        .with_alpha(self.style.progress_fill.a * paint.opacity)
2104                },
2105            }));
2106        }
2107    }
2108
2109    /// Handles arrow, boundary, and activation keys for enabled rows.
2110    fn handle_keyboard(&self, ctx: &mut EventCtx<A>, key: &ailloli_ui_core::event::KeyEvent) {
2111        match &key.key {
2112            Key::Named(NamedKey::ArrowDown) => self.move_active(ctx, 1),
2113            Key::Named(NamedKey::ArrowUp) => self.move_active(ctx, -1),
2114            Key::Named(NamedKey::Home) => {
2115                let next = self.rows.iter().position(|row| !row.disabled.read());
2116                if self.set_active(next, ctx) {
2117                    ctx.stop_propagation();
2118                }
2119            }
2120            Key::Named(NamedKey::End) => {
2121                let next = self.rows.iter().rposition(|row| !row.disabled.read());
2122                if self.set_active(next, ctx) {
2123                    ctx.stop_propagation();
2124                }
2125            }
2126            Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space) => {
2127                let idx = self.normalized_active_index();
2128                if let Some(idx) = idx {
2129                    if self.select_row(ctx, idx) {
2130                        ctx.stop_propagation();
2131                    }
2132                }
2133            }
2134            _ => {}
2135        }
2136    }
2137
2138    /// Moves to the next enabled row with wraparound in the requested direction.
2139    fn move_active(&self, ctx: &mut EventCtx<A>, direction: isize) {
2140        let next = next_enabled(&self.rows, self.normalized_active_index(), direction);
2141        if self.set_active(next, ctx) {
2142            ctx.stop_propagation();
2143        }
2144    }
2145
2146    /// Stores a changed active index, reveals it, and requests repaint.
2147    ///
2148    /// Returns `false` without side effects when `next` already matches.
2149    fn set_active(&self, next: Option<usize>, ctx: &mut EventCtx<A>) -> bool {
2150        if self.active_index.read() == next {
2151            return false;
2152        }
2153        self.active_index.set(next);
2154        if let Some(idx) = next {
2155            self.reveal_row(idx, ctx);
2156        }
2157        ctx.request_repaint();
2158        true
2159    }
2160
2161    /// Writes and/or emits an enabled row activation.
2162    ///
2163    /// Returns whether a binding or handler was configured. Equal selection IDs
2164    /// are still written, while missing/disabled rows return `false`.
2165    fn select_row(&self, ctx: &mut EventCtx<A>, idx: usize) -> bool {
2166        let Some(row) = self.rows.get(idx) else {
2167            return false;
2168        };
2169        if row.disabled.read() {
2170            return false;
2171        }
2172        let mut changed = false;
2173        if let Some(selected) = &self.bound_selected {
2174            selected.set(row.id.clone());
2175            changed = true;
2176        }
2177        if let Some(handler) = &self.on_select {
2178            handler(ctx, row.id.clone());
2179            changed = true;
2180        }
2181        if changed {
2182            self.active_index.set(Some(idx));
2183            self.reveal_row(idx, ctx);
2184            ctx.request_repaint();
2185        }
2186        changed
2187    }
2188
2189    /// Scrolls vertically just enough to reveal the indexed row.
2190    fn reveal_row(&self, idx: usize, ctx: &mut EventCtx<A>) {
2191        let metrics = self.metrics.read();
2192        let row = Rect::new(
2193            0.0,
2194            idx as f32 * self.style.row_height,
2195            metrics.content.w,
2196            self.style.row_height,
2197        );
2198        let out = self.scroll.read().reveal_rect(
2199            row,
2200            ScrollMetrics::new(metrics.viewport, metrics.content),
2201            ScrollAxes::VERTICAL,
2202        );
2203        if out.changed {
2204            self.scroll.set(out.state());
2205            ctx.request_repaint();
2206        }
2207    }
2208
2209    /// Returns a valid enabled active row, selected match, or first enabled row.
2210    fn normalized_active_index(&self) -> Option<usize> {
2211        if let Some(idx) = self.active_index.read() {
2212            if idx < self.rows.len() && !self.rows[idx].disabled.read() {
2213                return Some(idx);
2214            }
2215        }
2216        if let Some(selected) = self.selected_value() {
2217            if let Some(idx) = self
2218                .rows
2219                .iter()
2220                .position(|row| !row.disabled.read() && row.id == selected)
2221            {
2222                return Some(idx);
2223            }
2224        }
2225        self.rows.iter().position(|row| !row.disabled.read())
2226    }
2227
2228    /// Clones the current table-level selection when configured.
2229    fn selected_value(&self) -> Option<T> {
2230        self.selected.as_ref().map(Binding::read)
2231    }
2232
2233    /// Maps a body-window y coordinate through vertical scroll to a row index.
2234    fn row_index_at(&self, bounds: Rect, y: f32) -> Option<usize> {
2235        let body = self.body_rect(bounds);
2236        if y < body.y || y > body.bottom() {
2237            return None;
2238        }
2239        let content_y = y - body.y + self.scroll.read().offset.y;
2240        let idx = (content_y / self.style.row_height).floor() as usize;
2241        (idx < self.rows.len()).then_some(idx)
2242    }
2243
2244    /// Removes the header from table bounds and floors body height at zero.
2245    fn body_rect(&self, bounds: Rect) -> Rect {
2246        let header_h = self.style.header_height.min(bounds.h);
2247        Rect::new(
2248            bounds.x,
2249            bounds.y + header_h,
2250            bounds.w,
2251            (bounds.h - header_h).max(0.0),
2252        )
2253    }
2254
2255    /// Returns row count multiplied by the configured logical-pixel row height.
2256    fn body_content_height(&self) -> f32 {
2257        self.rows.len() as f32 * self.style.row_height
2258    }
2259
2260    /// Expands paint bounds to include every configured shadow.
2261    fn visual_bounds(&self, rect: Rect) -> Rect {
2262        self.style.shadows.iter().fold(rect, |bounds, shadow| {
2263            union_rect(bounds, shadow.paint_bounds(rect))
2264        })
2265    }
2266}
2267
2268/// Finds the next enabled row with wraparound, or `None` when none exists.
2269fn next_enabled<T>(rows: &[TableRow<T>], active: Option<usize>, direction: isize) -> Option<usize> {
2270    if rows.is_empty() {
2271        return None;
2272    }
2273    let start = active.unwrap_or(if direction >= 0 { 0 } else { rows.len() - 1 });
2274    for step in 1..=rows.len() {
2275        let idx = if direction >= 0 {
2276            (start + step) % rows.len()
2277        } else {
2278            (start + rows.len() - (step % rows.len())) % rows.len()
2279        };
2280        if !rows[idx].disabled.read() {
2281            return Some(idx);
2282        }
2283    }
2284    None
2285}
2286
2287/// Sums resolved logical-pixel widths without additional normalization.
2288fn sum_column_widths(columns: &[ResolvedColumn]) -> f32 {
2289    columns.iter().map(|column| column.width).sum()
2290}
2291
2292/// Measures unwrapped text when a text system is available.
2293fn measure_text_system(
2294    text_system: Option<&mut TextSystem>,
2295    text: &str,
2296    style: TextStyle,
2297) -> Option<f32> {
2298    text_system.map(|text_system| {
2299        text_system
2300            .layout_cached(TextLayoutParams {
2301                text,
2302                style,
2303                max_width: None,
2304                wrap_mode: WrapMode::NoWrap,
2305            })
2306            .metrics
2307            .width
2308    })
2309}
2310
2311/// Produces a cached unwrapped text layout when painting services are available.
2312fn layout_text(
2313    ctx: &mut PaintCtx<'_>,
2314    text: &str,
2315    style: TextStyle,
2316) -> Option<Arc<PreparedTextLayout>> {
2317    ctx.text_system.as_deref_mut().map(|text_system| {
2318        text_system.layout_cached(TextLayoutParams {
2319            text,
2320            style,
2321            max_width: None,
2322            wrap_mode: WrapMode::NoWrap,
2323        })
2324    })
2325}
2326
2327/// Paints one vertically centered text layout at the requested alignment.
2328fn paint_text_cell(
2329    ctx: &mut PaintCtx<'_>,
2330    text: &str,
2331    style: TextStyle,
2332    rect: Rect,
2333    align: TableAlign,
2334    padding_x: f32,
2335    opacity: f32,
2336) {
2337    let Some(layout) = layout_text(ctx, text, style) else {
2338        return;
2339    };
2340    let x = aligned_x(rect, layout.metrics.width, align, padding_x);
2341    let baseline = layout
2342        .lines
2343        .first()
2344        .map(|line| line.baseline_y)
2345        .unwrap_or(0.0);
2346    let y = rect.y + (rect.h - layout.metrics.height) * 0.5 + baseline;
2347    ctx.push(DrawCmd::Text(DrawText {
2348        pos: [x, y],
2349        color: style.color.with_alpha(style.color.a * opacity),
2350        decoration: ailloli_ui_core::TextDecoration::None,
2351        layout,
2352    }));
2353}
2354
2355/// Resolves a content origin, applying padding only at start/end alignment.
2356fn aligned_x(rect: Rect, content_w: f32, align: TableAlign, padding_x: f32) -> f32 {
2357    match align {
2358        TableAlign::Start => rect.x + padding_x,
2359        TableAlign::Center => rect.x + (rect.w - content_w) * 0.5,
2360        TableAlign::End => rect.right() - padding_x - content_w,
2361    }
2362}
2363
2364/// Maps every badge tone to a color from the default theme palette.
2365fn tone_color(tone: BadgeTone) -> Color {
2366    let palette = Theme::default().palette();
2367    match tone {
2368        BadgeTone::Neutral => palette.text_muted,
2369        BadgeTone::Accent => palette.accent,
2370        BadgeTone::Danger => palette.danger,
2371        BadgeTone::Success => palette.success,
2372        BadgeTone::Warning => palette.warning,
2373        BadgeTone::Info => palette.info,
2374        BadgeTone::Muted => palette.text_muted,
2375    }
2376}
2377
2378/// Returns the smallest axis-aligned rectangle containing both inputs.
2379fn union_rect(a: Rect, b: Rect) -> Rect {
2380    let x0 = a.x.min(b.x);
2381    let y0 = a.y.min(b.y);
2382    let x1 = a.right().max(b.right());
2383    let y1 = a.bottom().max(b.bottom());
2384    Rect::new(x0, y0, x1 - x0, y1 - y0)
2385}