Skip to main content

gpui_kit_grid/state/
mod.rs

1//! `LiveGridState`: the grid view. It owns the view settings, pulls store
2//! snapshots, runs projection rebuilds in the background and plans what the
3//! body element paints.
4
5mod a11y;
6// How a highlighted change paints a cell.
7mod change;
8// Clicks.
9mod click;
10mod columns;
11// The column chooser.
12mod chooser;
13// Copy.
14mod copy;
15// Exporting to a stream or a file.
16mod export;
17// Expanding and collapsing on screen.
18mod disclosure;
19// Dragging rows.
20mod drag;
21// Editing cells.
22mod edit;
23// The built-in cell editors.
24mod editors;
25mod events;
26// Removed rows fading out on screen.
27mod fade;
28mod frame;
29// The text style of drag ghosts, which GPUI draws outside the root.
30mod ghost;
31// The group panel.
32mod group_panel;
33// The grid without its delegate type.
34mod handle;
35// Links in cells.
36mod link;
37// Grouping and expansion.
38mod grouping;
39// Group captions on screen.
40mod groups;
41mod header;
42// Images in cells.
43mod images;
44mod layout;
45mod menu;
46// Commits waiting for an answer.
47mod pending;
48mod pinned;
49mod progress;
50mod projection;
51mod scroll;
52mod selection;
53mod stats;
54mod style;
55// Totals and group footers.
56mod summary;
57mod tooltip;
58// The tree on screen.
59mod tree;
60// Elements in cells.
61mod widgets;
62
63use std::{
64    hash::{Hash, Hasher as _},
65    sync::Arc,
66};
67
68use gpui_kit::base::{AutoScroll, Scrollbar, TestSupportExt as _};
69use gpui_kit::component::{ActiveTheme as _, Size as ComponentSize};
70use gpui_kit::{
71    App, Bounds, Context, EventEmitter, FocusHandle, Focusable, InteractiveElement as _,
72    IntoElement, KeyContext, ParentElement as _, Pixels, PlatformInfo, Render, SharedString,
73    StatefulInteractiveElement as _, Styled as _, Task, Window, div, prelude::FluentBuilder as _,
74    px,
75};
76use web_time::Instant;
77
78pub(crate) use self::{
79    a11y::{A11yPlan, FOCUS_CELL_ID},
80    tooltip::CellHover,
81};
82use self::{
83    a11y::{RowNumbering, root_role},
84    click::PendingClick,
85    columns::ColumnLayout,
86    frame::PaintedLine,
87    ghost::GhostTextStyle,
88    grouping::ExpansionRevision,
89    groups::CaptionTexts,
90    header::HeaderState,
91    menu::OpenMenu,
92    pinned::PaintedBands,
93    progress::ProgressSlot,
94    projection::{Coverage, HeldOrder, PendingWork},
95    scroll::{GridScrollHandle, LineAnchor, ScrollReset},
96    selection::{PointerTarget, Press, SelectionModel},
97    summary::SummaryTexts,
98    tooltip::TooltipState,
99};
100pub use self::{
101    change::{ChangePaint, ChangePainter, ChangePalette, DirectionalChanges, UniformChanges},
102    chooser::{
103        ColumnChooserContext, ColumnChooserFactory, ColumnChooserPanel, PopoverColumnChooser,
104    },
105    columns::{
106        CellContent, ColumnAlign, ColumnBand, ColumnZone, GridColumn, GridSchema, HeaderLabel,
107        MIN_COLUMN_WIDTH, ViewColumnIx,
108    },
109    drag::{DragPayload, DropPlace, DropSource, DropTarget, RowDrag, RowDragContext},
110    edit::{
111        CellEditor, EditCancelReason, EditError, EditId, EditInput, EditMessageContext, EditOrigin,
112        EditState, EditValidateContext, EditableContext, EditorCell, EditorField, EditorMark,
113        EditorOpen, EditorStart,
114    },
115    editors::{
116        CellEditHandle, CheckboxEditor, DateEditor, NumberEditor, NumberKind, SelectEditor,
117        SelectOption, TextEditor,
118    },
119    events::{
120        ExpandTarget, GroupOrigin, LayoutOrigin, LayoutPart, LayoutParts, LiveGridEvent,
121        SelectionOrigin, SortOrigin,
122    },
123    export::{EmptyExport, ExportHeader, ExportJob, ExportOutcome, ExportProgress, ExportRequest},
124    groups::{CaptionTag, GroupCaptionContext},
125    handle::{BandInfo, ColumnInfo, GridHandleEvent, LiveGridHandle, WeakLiveGridHandle},
126    images::{AssetImageSource, CellImage, CellImageSource, CellImages, ImageFit},
127    link::{LinkOpener, OpenInBrowser},
128    menu::{GridMenuContext, GridTarget},
129    progress::ProgressContext,
130    projection::FlushOutcome,
131    selection::{FocusedCell, GridSelection, ScopedSelection, SelectionMode},
132    stats::{GridStats, GridTuning},
133    style::{
134        AggregateLine, AggregateStyleContext, CellChange, CellStyle, CellStyleContext,
135        LiveGridDelegate,
136    },
137    tooltip::{CellTooltip, CellTooltipContext, HeaderTooltipContext},
138    widgets::CellElementContext,
139};
140use crate::{
141    actions::{CELL_CONTENT_KEY, KEY_CONTEXT},
142    element::GridBody,
143    engine::{GroupPath, Projection, ProjectionEngine, Rebuild, ViewSpec},
144    model::{ColumnIx, ColumnSet, GridColumns as _, GridRow},
145    policy::{
146        AutofitPolicy, BackgroundRunner, BandedMove, ColumnMovePolicy, ContextMenuGesture,
147        ExpandGesture, FocusCaptions, LiveReorder, ProjectionScope, ReorderPolicy,
148        SelectionGesture, SelectionPolicy, SelectionScope, SortCycle, StandardContextMenuGesture,
149        StandardExpandGesture, StandardSelectionGesture, StandardSortCycle, TaskRunner,
150        VisibleRowsAutofit,
151    },
152    quick_filter::{ContainsAllTerms, QuickFilterMatcher},
153    store::{GridStore, GridWriter, PinnedEdge, StoreOptions, StoreSnapshot},
154    text::{TextCaches, TextStats},
155};
156
157type ColumnOf<D> = <<D as LiveGridDelegate>::Row as GridRow>::Column;
158type KeyOf<D> = <<D as LiveGridDelegate>::Row as GridRow>::Key;
159
160const CELL_PADDING: Pixels = px(6.);
161
162/// The hash of a row key: the integer of element ids made from a row's
163/// identity, such as the tooltip div of a hovered cell
164/// (`NamedInteger(column id, key_hash)`) and the accessibility row of a
165/// data row (`NamedInteger("live-grid-row", key_hash)`). A pinned row's key
166/// is of its band's key space: `pinned::pinned_key_hash` hashes the band
167/// with it. `FxHasher`: fast, and stable within the process, which is all
168/// an element id needs.
169pub(crate) fn key_hash<K: Hash + ?Sized>(key: &K) -> u64 {
170    let mut hasher = rustc_hash::FxHasher::default();
171    key.hash(&mut hasher);
172    hasher.finish()
173}
174
175/// The hash of a group's path in element ids: a caption's accessibility row
176/// (`NamedInteger("live-grid-group-row", ..)`), its tooltip divs and its
177/// focus. Tagged, so it never equals a data row's `key_hash`, as
178/// `pinned_key_hash` is.
179pub(crate) fn group_hash(path: &GroupPath) -> u64 {
180    key_hash(&("live-grid-group", path))
181}
182
183/// The hash of a group footer's path in element ids: its accessibility row
184/// (`NamedInteger("live-grid-group-footer-row", ..)`) and its tooltip divs.
185pub(crate) fn footer_hash(path: &GroupPath) -> u64 {
186    key_hash(&("live-grid-group-footer", path))
187}
188
189/// The hash of the totals row of a band in element ids: its accessibility
190/// row (`NamedInteger("live-grid-totals-row", ..)`) and its tooltip divs.
191pub(crate) fn totals_hash(edge: PinnedEdge) -> u64 {
192    key_hash(&(
193        "live-grid-totals",
194        match edge {
195            PinnedEdge::Top => "top",
196            PinnedEdge::Bottom => "bottom",
197        },
198    ))
199}
200
201/// The state and view of a live grid.
202pub struct LiveGridState<D: LiveGridDelegate> {
203    delegate: D,
204    store: GridStore<D::Row>,
205    snapshot: Arc<StoreSnapshot<D::Row>>,
206    projection: Arc<Projection>,
207    view: ViewSpec<D::Row>,
208    engine: Arc<dyn ProjectionEngine<D::Row>>,
209    tuning: GridTuning,
210    pending: PendingWork,
211    rebuild_task: Option<Task<()>>,
212    rebuild_timer: Option<Task<()>>,
213    last_rebuild_started: Option<Instant>,
214    /// The pending work comes from a user action (a new view, a new data
215    /// set): its result skips the reorder hold.
216    pending_user_action: bool,
217    /// The pending work comes from a new view (sort, filter, quick filter,
218    /// grouping): its result is shown from the top, or with a painted
219    /// focused line on its screen line.
220    pending_scroll_reset: ScrollReset,
221    /// Counts the edits of the view's expansion.
222    expansion_revision: ExpansionRevision,
223    /// The expansion the shown projection's lines are laid out for.
224    shown_revision: ExpansionRevision,
225    /// Values aggregates read changed since the last job that recounted
226    /// them; a held order does not hold them.
227    aggregates_changed: bool,
228    /// The caption or tree row the user toggled last: it keeps its screen
229    /// line when the lines of the new expansion are shown.
230    expand_anchor: Option<LineAnchor>,
231    /// How a press expands or collapses a caption or a tree row.
232    expand_gesture: Box<dyn ExpandGesture>,
233    /// The texts of captions and aggregates, by locale.
234    caption_texts: CaptionTexts,
235    /// The band of the totals row, if shown, and its label by locale.
236    totals: Option<PinnedEdge>,
237    summary_texts: SummaryTexts,
238    reorder: Box<dyn ReorderPolicy>,
239    runner: Box<dyn TaskRunner>,
240    sort_cycle: Box<dyn SortCycle>,
241    quick_filter_matcher: Arc<dyn QuickFilterMatcher>,
242    /// The columns the quick filter searches; `None`: the visible ones.
243    quick_filter_columns: Option<ColumnSet>,
244    /// The quick filter text, trimmed; empty when the filter is off.
245    quick_filter_text: SharedString,
246    held: Option<HeldOrder>,
247    pointer_inside: bool,
248    /// The store version of the latest removal: a projection built before it
249    /// may still hold removed rows.
250    last_removal_version: u64,
251    columns: ColumnLayout<ColumnOf<D>>,
252    /// Saved layouts: view id, codec, merge, schema defaults.
253    layout: layout::LayoutSlot<D::Row>,
254    column_move: Box<dyn ColumnMovePolicy>,
255    autofit: Box<dyn AutofitPolicy>,
256    /// Columns to autofit in the next painted frame, and who asked.
257    pending_autofit: Option<(ColumnSet, LayoutOrigin)>,
258    /// The column that column commands act on.
259    current_column: Option<ColumnIx>,
260    header: HeaderState,
261    scroll_row: usize,
262    scroll_offset: Pixels,
263    scroll_x: Pixels,
264    row_height: Pixels,
265    body_bounds: Bounds<Pixels>,
266    /// What the last frame painted, one entry per line of the data rows:
267    /// hit tests use what is on screen, not the projection, which may still
268    /// hold removed rows.
269    painted: Vec<PaintedLine>,
270    /// The pinned rows painted in the last frame, band by band.
271    painted_pinned: PaintedBands<D::Row>,
272    /// The coverage of the order shown or held, and the flushes waiting
273    /// for it.
274    coverage: Coverage,
275    /// The view's progress and the store's progress as shown.
276    progress: ProgressSlot,
277    /// The scroll position as the scrollbars see it.
278    scroll_handle: GridScrollHandle,
279    /// The selection, the focused cell and the anchor.
280    selection: SelectionModel<KeyOf<D>, ColumnOf<D>>,
281    selection_scope: Box<dyn SelectionScope<D::Row>>,
282    /// Which lines take the selection; what a command over a line acts on.
283    selection_policy: Box<dyn SelectionPolicy<D::Row>>,
284    selection_gesture: Box<dyn SelectionGesture>,
285    context_menu_gesture: Box<dyn ContextMenuGesture>,
286    /// What the last mouse-down on the body hit: the context menu's target.
287    pointer_target: Option<PointerTarget<KeyOf<D>>>,
288    /// The primary-button press in progress.
289    press: Option<Press<KeyOf<D>, ColumnOf<D>>>,
290    /// The row of the first press of a click series: a double click
291    /// confirms it.
292    press_series: Option<KeyOf<D>>,
293    /// The press on the grid that ends in a `Click` if it is released
294    /// without a drag.
295    click: Option<PendingClick<KeyOf<D>, ColumnOf<D>>>,
296    /// Scrolls the rows while a drag-selection is above or below them.
297    drag_scroll: AutoScroll,
298    /// The open context menu.
299    menu: Option<OpenMenu<KeyOf<D>, ColumnOf<D>>>,
300    /// The pointer over the body and the header, and the hovered cell's
301    /// tooltip.
302    tooltip: TooltipState,
303    /// The last frame showed keyboard focus (focus-visible).
304    #[cfg(any(test, feature = "test-support"))]
305    focus_visible: bool,
306    /// The grid's accessible name, from `LiveGrid::accessibility_label`.
307    accessibility_label: Option<SharedString>,
308    /// Plan the accessibility tree while the window's accessibility is off
309    /// ([`Self::set_a11y_forced`]).
310    #[cfg(any(test, feature = "test-support"))]
311    a11y_forced: bool,
312    /// The accessibility plan of the last frame, for tests.
313    #[cfg(any(test, feature = "test-support"))]
314    last_a11y: Option<std::rc::Rc<A11yPlan>>,
315    text_cache: TextCaches,
316    /// How highlighted changes paint cells.
317    change_paint: ChangePaint,
318    /// A test's start of cells: the column, the indent and an icon.
319    #[cfg(any(test, feature = "test-support"))]
320    test_cell_lead: Option<(ColumnIx, Pixels, Option<SharedString>)>,
321    /// A test's cell host on every cell of a column.
322    #[cfg(any(test, feature = "test-support"))]
323    test_cell_host: Option<frame::TestCellHost>,
324    /// What the last frame painted, in order.
325    #[cfg(any(test, feature = "test-support"))]
326    last_paint_order: Vec<&'static str>,
327    /// The icons the body painted in the last frame.
328    #[cfg(any(test, feature = "test-support"))]
329    painted_icons: Vec<(Bounds<Pixels>, SharedString, gpui_kit::Hsla)>,
330    /// The images the body painted in the last frame.
331    #[cfg(any(test, feature = "test-support"))]
332    painted_images: Vec<frame::PaintedImage>,
333    /// The caption tags the body painted in the last frame.
334    #[cfg(any(test, feature = "test-support"))]
335    painted_pills: Vec<(Bounds<Pixels>, gpui_kit::Hsla)>,
336    fade: Option<(u32, Task<()>)>,
337    stats: GridStats,
338    focus_handle: FocusHandle,
339    // The host whose conventions the gestures follow (`App::platform_info`).
340    platform: PlatformInfo,
341    // Copy: the exporters and the copy being written.
342    copy: copy::CopySlot<D::Row>,
343    // The column chooser.
344    column_chooser: chooser::ChooserSlot,
345    // The group panel.
346    group_panel: group_panel::GroupPanelState,
347    // Editing: the editors and edit seams, the open edit, the commits
348    // waiting, and the elements in cells.
349    edit_setup: edit::EditSetup<D::Row>,
350    edit: edit::EditSlot<KeyOf<D>, ColumnOf<D>>,
351    pending_edits: pending::PendingEdits<KeyOf<D>, ColumnOf<D>>,
352    widgets: widgets::WidgetSlot<KeyOf<D>, ColumnOf<D>>,
353    links: link::LinkSlot,
354    // Where the images of image cells come from.
355    images: images::CellImages,
356    // Row drags.
357    drag: drag::DragSlot<D>,
358    _pull: Task<()>,
359}
360
361impl<D: LiveGridDelegate> LiveGridState<D> {
362    /// A grid over `store`. Several grids may share one store.
363    pub fn new(
364        schema: GridSchema<ColumnOf<D>>,
365        delegate: D,
366        store: GridStore<D::Row>,
367        cx: &mut Context<Self>,
368    ) -> Self {
369        let subscription = store.subscribe();
370        let snapshot = store.snapshot();
371        let pull = cx.spawn(async move |this, cx| {
372            while subscription.changed().await {
373                let (snapshot, changes) = subscription.take();
374                let Ok(interval) = this.update(cx, |state, cx| {
375                    state.apply_snapshot(snapshot, changes, cx);
376                    state.tuning.pull_interval
377                }) else {
378                    break;
379                };
380                cx.background_executor().timer(interval).await;
381            }
382        });
383        Self {
384            delegate,
385            progress: ProgressSlot::new(snapshot.progress()),
386            snapshot,
387            store,
388            projection: Arc::new(Projection::default()),
389            view: ViewSpec::new(),
390            engine: Arc::new(Rebuild::default()),
391            tuning: GridTuning::default(),
392            pending: PendingWork::Rebuild { expand: false },
393            rebuild_task: None,
394            rebuild_timer: None,
395            last_rebuild_started: None,
396            pending_user_action: true,
397            pending_scroll_reset: ScrollReset::Keep,
398            expansion_revision: ExpansionRevision::default(),
399            shown_revision: ExpansionRevision::default(),
400            aggregates_changed: false,
401            expand_anchor: None,
402            expand_gesture: Box::new(StandardExpandGesture),
403            caption_texts: CaptionTexts::default(),
404            totals: None,
405            summary_texts: SummaryTexts::default(),
406            reorder: Box::new(LiveReorder),
407            runner: Box::new(BackgroundRunner),
408            sort_cycle: Box::new(StandardSortCycle),
409            quick_filter_matcher: Arc::new(ContainsAllTerms),
410            quick_filter_columns: None,
411            quick_filter_text: SharedString::default(),
412            held: None,
413            pointer_inside: false,
414            last_removal_version: 0,
415            // Reads the schema before `columns` takes it.
416            layout: layout::LayoutSlot::new(&schema),
417            columns: {
418                let mut columns = ColumnLayout::new(schema);
419                columns.normalize(&BandedMove);
420                columns
421            },
422            column_move: Box::new(BandedMove),
423            autofit: Box::new(VisibleRowsAutofit),
424            pending_autofit: None,
425            current_column: None,
426            header: HeaderState::default(),
427            scroll_row: 0,
428            scroll_offset: px(0.),
429            scroll_x: px(0.),
430            // gpui-kit default size (md); `LiveGrid` sets the size it is given.
431            row_height: ComponentSize::default().table_row_height(),
432            body_bounds: Bounds::default(),
433            painted: Vec::new(),
434            painted_pinned: PaintedBands::default(),
435            coverage: Coverage::default(),
436            scroll_handle: GridScrollHandle::default(),
437            selection: SelectionModel::new(SelectionMode::default()),
438            selection_scope: Box::new(ProjectionScope),
439            selection_policy: Box::new(FocusCaptions),
440            selection_gesture: Box::new(StandardSelectionGesture),
441            context_menu_gesture: Box::new(StandardContextMenuGesture),
442            pointer_target: None,
443            press: None,
444            press_series: None,
445            click: None,
446            drag_scroll: AutoScroll::default(),
447            menu: None,
448            tooltip: TooltipState::default(),
449            #[cfg(any(test, feature = "test-support"))]
450            focus_visible: false,
451            accessibility_label: None,
452            #[cfg(any(test, feature = "test-support"))]
453            a11y_forced: false,
454            #[cfg(any(test, feature = "test-support"))]
455            last_a11y: None,
456            text_cache: TextCaches::default(),
457            change_paint: ChangePaint::default(),
458            #[cfg(any(test, feature = "test-support"))]
459            test_cell_lead: None,
460            #[cfg(any(test, feature = "test-support"))]
461            test_cell_host: None,
462            #[cfg(any(test, feature = "test-support"))]
463            last_paint_order: Vec::new(),
464            #[cfg(any(test, feature = "test-support"))]
465            painted_icons: Vec::new(),
466            #[cfg(any(test, feature = "test-support"))]
467            painted_images: Vec::new(),
468            #[cfg(any(test, feature = "test-support"))]
469            painted_pills: Vec::new(),
470            fade: None,
471            stats: GridStats::default(),
472            // The grid is one Tab stop; Tab leaves it.
473            focus_handle: cx.focus_handle().tab_stop(true),
474            platform: cx.platform_info(),
475            copy: copy::CopySlot::default(),
476            column_chooser: chooser::ChooserSlot::default(),
477            group_panel: group_panel::GroupPanelState::default(),
478            edit_setup: edit::EditSetup::default(),
479            edit: edit::EditSlot::default(),
480            pending_edits: pending::PendingEdits::default(),
481            widgets: widgets::WidgetSlot::default(),
482            links: link::LinkSlot::default(),
483            images: images::CellImages::default(),
484            drag: drag::DragSlot::default(),
485            _pull: pull,
486        }
487    }
488
489    /// A grid with its own store.
490    pub fn new_standalone(
491        schema: GridSchema<ColumnOf<D>>,
492        delegate: D,
493        options: StoreOptions,
494        cx: &mut Context<Self>,
495    ) -> Self {
496        let store = GridStore::new(options, cx);
497        Self::new(schema, delegate, store, cx)
498    }
499
500    /// Sets the view (filter, sort, grouping or tree, aggregates). The grid
501    /// owns the quick filter and the expansion: those of `view` are replaced
502    /// by the grid's own ([`Self::set_quick_filter`],
503    /// [`Self::with_expand_depth`]). The sort and the grouping of a layout
504    /// given to [`Self::with_layout`], before or after, replace those of
505    /// `view`.
506    pub fn with_view(mut self, view: ViewSpec<D::Row>) -> Self {
507        let quick_filter = self.view.quick_filter().cloned();
508        let expansion = self.view.expansion().clone();
509        self.view = view
510            .with_quick_filter(quick_filter)
511            .with_expansion(expansion);
512        // The default layout keeps this sort and grouping.
513        self.layout.set_view(&self.view);
514        self.apply_initial_layout()
515    }
516
517    /// Sets the projection engine (default [`Rebuild`]).
518    pub fn with_engine(mut self, engine: impl ProjectionEngine<D::Row>) -> Self {
519        self.engine = Arc::new(engine);
520        self
521    }
522
523    /// Sets the timing knobs.
524    pub fn with_tuning(mut self, tuning: GridTuning) -> Self {
525        self.tuning = tuning;
526        self
527    }
528
529    /// Sets when a new display order replaces the shown one (default
530    /// [`LiveReorder`]; see also `HoldReorder` and `ManualReorder`).
531    pub fn with_reorder_policy(mut self, policy: impl ReorderPolicy) -> Self {
532        self.reorder = Box::new(policy);
533        self
534    }
535
536    /// Sets where background jobs run (default [`BackgroundRunner`]).
537    pub fn with_task_runner(mut self, runner: impl TaskRunner) -> Self {
538        self.runner = Box::new(runner);
539        self
540    }
541
542    /// Sets how a header click changes the sort (default
543    /// [`StandardSortCycle`]).
544    pub fn with_sort_cycle(mut self, cycle: impl SortCycle) -> Self {
545        self.sort_cycle = Box::new(cycle);
546        self
547    }
548
549    /// Sets how quick filter text matches rows (default
550    /// [`ContainsAllTerms`]).
551    pub fn with_quick_filter_matcher(mut self, matcher: impl QuickFilterMatcher) -> Self {
552        self.quick_filter_matcher = Arc::new(matcher);
553        self.recompile_quick_filter();
554        self
555    }
556
557    /// Sets the columns the quick filter searches (default: the visible
558    /// columns, frozen and scrolled out of view included). Hiding a column
559    /// does not change an explicit set.
560    pub fn with_quick_filter_columns(
561        mut self,
562        columns: impl IntoIterator<Item = ColumnOf<D>>,
563    ) -> Self {
564        let set = columns
565            .into_iter()
566            .fold(ColumnSet::EMPTY, |mut set, column| {
567                set.insert(column.ix());
568                set
569            });
570        self.quick_filter_columns = Some(set);
571        self.recompile_quick_filter();
572        self
573    }
574
575    /// Sets the row height (from the [`crate::LiveGrid`] size).
576    pub(crate) fn set_row_height(&mut self, row_height: Pixels) {
577        if self.row_height != row_height {
578            self.row_height = row_height;
579            self.clamp_scroll();
580        }
581    }
582
583    /// Sets the accessible name (from the [`crate::LiveGrid`] label).
584    pub(crate) fn set_accessibility_label(&mut self, label: Option<SharedString>) {
585        self.accessibility_label = label;
586    }
587
588    /// Plans the accessibility tree even when the window's accessibility is
589    /// off, so headless tests can check the planned elements: the frame
590    /// plans the rows and the focused cell, prepaints their elements and
591    /// builds the nodes GPUI would publish (it publishes none: the window's
592    /// accessibility is off). Takes effect with the next frame.
593    #[cfg(any(test, feature = "test-support"))]
594    pub fn set_a11y_forced(&mut self, forced: bool) {
595        self.a11y_forced = forced;
596    }
597
598    /// The description the last planned accessibility tree gives the
599    /// focused cell: the column title, then the expansion state, the trend
600    /// ("rising", "falling") and the tooltip text. `None` without a plan or
601    /// a painted focused cell. For tests, with [`Self::set_a11y_forced`].
602    #[cfg(any(test, feature = "test-support"))]
603    pub fn a11y_focus_description(&self) -> Option<&str> {
604        self.last_a11y.as_ref()?.focus_description()
605    }
606
607    /// Gives every cell of `column` in the data rows a start, as group
608    /// captions and tree rows have: the text begins `indent` further in
609    /// with that much less room, and `icon` (an icon path) sits in the
610    /// indent's last 20 px. For tests of the frame. Takes effect with the
611    /// next frame.
612    #[cfg(any(test, feature = "test-support"))]
613    pub fn set_test_cell_lead(
614        &mut self,
615        column: ColumnOf<D>,
616        indent: Pixels,
617        icon: Option<SharedString>,
618    ) {
619        self.test_cell_lead = Some((column.ix(), indent, icon));
620    }
621
622    /// Gives every cell of `column` in the painted data and pinned rows a
623    /// cell host: a real element over the cell, after a tree row's indent,
624    /// made by `build` from the host's div, whose id is
625    /// `NamedChild("live-grid-cell", column id)` in the id scope of the row's
626    /// element (`NamedInteger("live-grid-row", key hash)`). The body paints
627    /// no text in those cells. For tests of the cell host mechanism; `None`
628    /// removes it. Takes effect with the next frame.
629    #[cfg(any(test, feature = "test-support"))]
630    pub fn set_test_cell_host(
631        &mut self,
632        column: Option<ColumnOf<D>>,
633        build: impl Fn(gpui_kit::Stateful<gpui_kit::Div>) -> gpui_kit::Stateful<gpui_kit::Div> + 'static,
634    ) {
635        self.test_cell_host = column.map(|column| {
636            let build: std::rc::Rc<
637                dyn Fn(gpui_kit::Stateful<gpui_kit::Div>) -> gpui_kit::Stateful<gpui_kit::Div>,
638            > = std::rc::Rc::new(build);
639            (column.ix(), build)
640        });
641    }
642
643    /// What the body painted in the last frame, in order: `regions` (the
644    /// cells' backgrounds, lines, text and icons), `dividers`, `tooltip`
645    /// (the hovered cell's div), `rows` (row elements: accessibility rows
646    /// and cell hosts) and `outlines` (the focused cell's), each when there
647    /// was one. For tests.
648    #[cfg(any(test, feature = "test-support"))]
649    pub fn last_paint_order(&self) -> &[&'static str] {
650        &self.last_paint_order
651    }
652
653    #[cfg(any(test, feature = "test-support"))]
654    pub(crate) fn set_last_paint_order(&mut self, order: Vec<&'static str>) {
655        self.last_paint_order = order;
656    }
657
658    /// Records how long the last frame's row elements took to lay out and
659    /// prepaint, when it had cell hosts.
660    pub(crate) fn set_last_hosts_prepaint(&mut self, elapsed: std::time::Duration) {
661        self.stats.last_hosts_prepaint = elapsed;
662    }
663
664    /// Whether this frame builds the accessibility tree of the body: only
665    /// while a screen reader or another client is listening (or forced in
666    /// tests), so the grid costs nothing for accessibility otherwise.
667    fn is_a11y_planned(&self, window: &Window) -> bool {
668        #[cfg(any(test, feature = "test-support"))]
669        if self.a11y_forced {
670            return true;
671        }
672        window.is_a11y_active()
673    }
674
675    /// The root's key context: [`KEY_CONTEXT`], with
676    /// [`CELL_CONTENT_KEY`] set to what the focused data cell's column
677    /// paints, so a key binding can tell a control from text.
678    fn root_key_context(&self) -> KeyContext {
679        let mut context = KeyContext::default();
680        context.add(KEY_CONTEXT);
681        let content = self
682            .selection
683            .focus()
684            .filter(|focus| focus.row().is_some())
685            .map(|focus| self.columns.column(focus.column().ix()).content);
686        if self.is_link_focused() {
687            context.set(CELL_CONTENT_KEY, "link");
688        } else if let Some(content) = content {
689            context.set(CELL_CONTENT_KEY, content.key_value());
690        }
691        context
692    }
693
694    /// How the accessibility tree numbers rows now: the header, the top
695    /// band, the rows of the shown projection, the bottom band, with
696    /// the totals row as the outermost row of its band.
697    fn a11y_numbering(&self) -> RowNumbering {
698        RowNumbering::new(
699            self.snapshot.pinned_rows(PinnedEdge::Top).len(),
700            self.projection.len(),
701            self.snapshot.pinned_rows(PinnedEdge::Bottom).len(),
702        )
703        .with_totals(self.totals)
704    }
705
706    /// The store.
707    pub fn store(&self) -> &GridStore<D::Row> {
708        &self.store
709    }
710
711    /// A writer for producers on any thread.
712    pub fn writer(&self) -> GridWriter<D::Row> {
713        self.store.writer()
714    }
715
716    /// The snapshot currently shown.
717    pub fn snapshot(&self) -> &Arc<StoreSnapshot<D::Row>> {
718        &self.snapshot
719    }
720
721    /// The display order currently shown.
722    pub fn projection(&self) -> &Arc<Projection> {
723        &self.projection
724    }
725
726    /// Profiling counters.
727    pub fn stats(&self) -> GridStats {
728        // The cycles of the tree shown.
729        self.stats.with_tree_cycles(self.projection.tree_cycles())
730    }
731
732    /// Text cache counters.
733    pub fn text_stats(&self) -> TextStats {
734        self.text_cache.stats()
735    }
736}
737
738impl<D: LiveGridDelegate> EventEmitter<LiveGridEvent<KeyOf<D>, ColumnOf<D>>> for LiveGridState<D> {}
739
740impl<D: LiveGridDelegate> Focusable for LiveGridState<D> {
741    fn focus_handle(&self, _: &App) -> FocusHandle {
742        self.focus_handle.clone()
743    }
744}
745
746impl<D: LiveGridDelegate> Render for LiveGridState<D> {
747    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
748        self.close_stale_menu(window, cx);
749        // A row drag whose release the grid did not see.
750        self.settle_row_drag(cx);
751        self.apply_scroll_request();
752        self.ensure_projection(cx);
753        let a11y = self.is_a11y_planned(window);
754        let header_tooltip = self.header_tooltip(window, cx);
755        // The drag ghosts' text style: the one the grid inherits here.
756        let ghost_text = GhostTextStyle::capture(window);
757        let header = self.render_header(header_tooltip, &ghost_text, a11y, cx);
758        // The group panel, if `LiveGrid` shows it.
759        let group_panel = self.render_group_panel(window, cx);
760        let scrollbars = self.render_scrollbars();
761        let progress = self.render_progress_overlay(window, cx);
762        let menu = self.render_menu(window);
763        // The column chooser's layer, as the menu's.
764        let column_chooser = self.render_column_chooser(window, cx);
765        // The root is the `Grid` node, a `TreeGrid` for a grouped view or a
766        // tree, and keeps the focus; the focused cell claims the active
767        // descendant under it. The counts are of the whole grid, not of what
768        // is painted.
769        let role = root_role(self.projection.is_grouped() || self.projection.is_tree());
770        let row_count = self.a11y_numbering().row_count();
771        let column_count = self.columns.visible_set().len();
772        let multiselectable = !self.selection.mode().is_single();
773        let theme = cx.theme();
774        let root = div()
775            .id("live-grid")
776            .test_support()
777            .track_focus(&self.focus_handle)
778            .role(role)
779            .when_some(self.accessibility_label.clone(), |this, label| {
780                this.aria_label(label)
781            })
782            .aria_row_count(row_count)
783            .aria_column_count(column_count)
784            // A div has no `aria_*` for it: set on the node itself, and only
785            // while the tree is built (the closure is a boxed allocation).
786            .when(a11y && multiselectable, |this| {
787                this.a11y_synthetic_children(|builder| builder.parent_node().set_multiselectable())
788            })
789            .key_context(self.root_key_context())
790            .on_action(cx.listener(Self::on_autofit_columns))
791            .on_action(cx.listener(Self::on_autofit_column))
792            .on_action(cx.listener(Self::on_hide_column))
793            .on_action(cx.listener(Self::on_show_all_columns))
794            .on_action(cx.listener(Self::on_freeze_column_left))
795            .on_action(cx.listener(Self::on_freeze_column_right))
796            .on_action(cx.listener(Self::on_unfreeze_column))
797            .on_action(cx.listener(Self::on_move_column_left))
798            .on_action(cx.listener(Self::on_move_column_right))
799            .on_action(cx.listener(Self::on_reset_layout))
800            .on_action(cx.listener(Self::on_show_context_menu))
801            .on_action(cx.listener(Self::on_show_column_chooser))
802            .on_action(cx.listener(Self::on_sort_ascending))
803            .on_action(cx.listener(Self::on_sort_descending))
804            .on_action(cx.listener(Self::on_clear_sort))
805            .on_action(cx.listener(Self::on_clear_all_sorting))
806            .map(|this| Self::bind_selection_actions(this, cx))
807            // Expanding and collapsing.
808            .map(|this| Self::bind_disclosure_actions(this, cx))
809            // Copy.
810            .on_action(cx.listener(Self::on_copy))
811            .on_action(cx.listener(Self::on_copy_all))
812            // The grouping Actions and chip drags.
813            .map(|this| Self::bind_group_panel(this, cx))
814            // Editing and elements in cells.
815            .map(|this| Self::bind_edit_actions(this, cx))
816            .map(|this| Self::bind_cell_actions(this, cx))
817            .map(|this| Self::bind_link_actions(this, cx))
818            // Header drags drop anywhere on the grid, header or body.
819            .on_drag_move(cx.listener(Self::on_columns_drag_move))
820            .on_drag_move(cx.listener(Self::on_resize_drag_move))
821            .on_drop(cx.listener(Self::on_columns_drop))
822            .size_full()
823            .flex()
824            .flex_col()
825            .overflow_hidden()
826            .bg(theme.table)
827            .text_color(theme.foreground)
828            // The group panel, above the header.
829            .children(group_panel)
830            .child(header)
831            // The rows' wrapper, the source of row drags.
832            .child(self.render_rows(GridBody::new(cx.entity()), ghost_text, cx))
833            .child(scrollbars)
834            // Over the body, under the header; no hitbox of its own.
835            .children(progress);
836        // The menu layer is a sibling of the grid root, outside its key
837        // context: keys pressed in the menu (Space, Page Down, arrows a menu
838        // passes on) must not move the grid's selection. Its items dispatch
839        // to the grid's focus all the same (`action_context`).
840        div()
841            .size_full()
842            .child(root)
843            .children(menu)
844            .children(column_chooser)
845    }
846}
847
848impl<D: LiveGridDelegate> LiveGridState<D> {
849    /// The scrollbars over the data rows (`gpui_kit::base::Scrollbar`, as
850    /// gpui-kit's `DataTable`): vertical at their right edge, between the
851    /// pinned bands, which do not scroll; horizontal at their bottom edge,
852    /// under the scrolling zone. An overlay scrollbar takes the presses on
853    /// it, so the bands stay clear of both and a pinned row is clickable
854    /// across its height. Rendered by this view, so a thumb drag repaints
855    /// it.
856    fn render_scrollbars(&self) -> impl IntoElement {
857        let geometry = self
858            .columns
859            .geometry(self.body_bounds.size.width, self.scroll_x);
860        let scrolling = geometry.zone(ColumnZone::Scrolling);
861        let (left, width) = (scrolling.x, scrolling.width);
862        let bands = self.body_bands();
863        let top_band = bands.band(PinnedEdge::Top).size.height;
864        let bottom_band = bands.band(PinnedEdge::Bottom).size.height;
865        div()
866            .absolute()
867            // Below the group panel and header.
868            .top(self.body_top())
869            .left_0()
870            .right_0()
871            .bottom_0()
872            .child(
873                div()
874                    .absolute()
875                    .top(top_band)
876                    .right_0()
877                    .bottom(bottom_band)
878                    .w(Scrollbar::width())
879                    .child(
880                        Scrollbar::vertical(&self.scroll_handle)
881                            .viewport_from_layout()
882                            .max_fps(60),
883                    ),
884            )
885            .child(
886                div()
887                    .absolute()
888                    .left(left)
889                    .bottom(bottom_band)
890                    .w(width)
891                    .h(Scrollbar::width())
892                    .child(Scrollbar::horizontal(&self.scroll_handle).viewport_from_layout()),
893            )
894    }
895}