Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
tabular_data_preview: Extract table component from the preview pane (#63752)
Oleksandr Kholiavko93c87da195cd
diff --git a/crates/tabular_data_preview/src/parser.rs b/crates/tabular_data_preview/src/parser.rsindex 9c691d03b36..d272d088c49 100644--- a/crates/tabular_data_preview/src/parser.rs+++ b/crates/tabular_data_preview/src/parser.rs@@ -78,6 +78,8 @@ impl TabularDataPreviewPane {) {let editor = self.active_editor_state.editor.clone();self.is_parsing = true;+ self.table+ .update(cx, |table, cx| table.set_loading(true, cx));self.parsing_task = Some(self.parse_in_background(wait_for_debounce, editor, cx));}@@ -148,17 +150,14 @@ impl TabularDataPreviewPane {let parse_end_time: Instant = Instant::now();log::debug!("Parsed data in {}ms", parse_duration.as_millis());view.update(cx, move |view, cx| {- view.performance_metrics- .timings- .insert("Parsing", (parse_duration, Instant::now()));-view.last_parse_end_time = Some(parse_end_time);view.is_parsing = false;let parsed_contents = match parsed_contents {Ok(contents) => contents,Err(error) => {view.parse_error = Some(format!("{error:#}").into());- view.filter_sort_task = None;+ view.table+ .update(cx, |table, cx| table.set_loading(false, cx));cx.notify();return;}@@ -166,11 +165,14 @@ impl TabularDataPreviewPane {log::debug!("Parsed {} rows", parsed_contents.rows.len());view.parse_error = None;- view.engine.set_contents(parsed_contents);- view.list_state- .reset_with_uniform_height(0, view.row_height);- view.sync_column_widths(cx);- view.apply_filter_sort(cx);+ view.table.update(cx, |table, cx| {+ table+ .performance_metrics+ .timings+ .insert("Parsing", (parse_duration, Instant::now()));+ // `set_contents` recomputes filters/widths/mapping and clears the loading state.+ table.set_contents(parsed_contents, cx);+ });cx.notify();})})diff --git a/crates/tabular_data_preview/src/renderer/performance_metrics_overlay.rs b/crates/tabular_data_preview/src/renderer/performance_metrics_overlay.rsindex 4d0b5bf4139..7e4af61a274 100644--- a/crates/tabular_data_preview/src/renderer/performance_metrics_overlay.rs+++ b/crates/tabular_data_preview/src/renderer/performance_metrics_overlay.rs@@ -5,13 +5,11 @@use ui::{ActiveTheme, Context, IntoElement, ParentElement, Styled, StyledTypography, div};-use crate::{PerformanceMetrics, TabularDataPreviewPane};+use crate::{PerformanceMetrics, TableView};-impl TabularDataPreviewPane {+impl TableView {/// Renders a semi-transparent performance metrics overlay in the bottom-right corner.- ////// Shows parsing duration for debugging and performance monitoring.- /// The overlay is positioned absolutely and styled with reduced opacity.pub(crate) fn render_performance_metrics_overlay(&mut self,cx: &mut Context<Self>,diff --git a/crates/tabular_data_preview/src/renderer/preview_view.rs b/crates/tabular_data_preview/src/renderer/preview_view.rsindex 505b18aea6b..e60a4e36e00 100644--- a/crates/tabular_data_preview/src/renderer/preview_view.rs+++ b/crates/tabular_data_preview/src/renderer/preview_view.rs@@ -1,20 +1,10 @@-use std::time::Instant;-use ui::{SpinnerLabel, div, prelude::*};-use crate::TabularDataPreviewPane;+use crate::TableView;use super::settings::settings_popover_menu;-impl TabularDataPreviewPane {- fn is_ready_to_render_content(&self) -> bool {- !self.is_parsing- && self.parse_error.is_none()- && (self.engine.contents.number_of_cols > 0 || !self.engine.contents.rows.is_empty())- }-}--impl Render for TabularDataPreviewPane {+impl Render for TableView {fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {let theme = cx.theme();let row_height = window.pixel_snap(window.line_height());@@ -26,14 +16,14 @@ impl Render for TabularDataPreviewPane {// item's prior size as a hint rather than dropping straight to a fresh guess.self.list_state.remeasure();}- let render_prep_start = Instant::now();+ let render_prep_start = std::time::Instant::now();let table_with_settings = v_flex().size_full().bg(theme.colors().editor_background).track_focus(&self.focus_handle).child({- let is_parsing = self.is_parsing;- if !self.is_ready_to_render_content() {+ let is_loading = self.is_loading;+ if is_loading || self.engine.contents.number_of_cols == 0 {v_flex().size_full().child(@@ -54,7 +44,7 @@ impl Render for TabularDataPreviewPane {.text_ui(cx).font_buffer(cx).text_color(cx.theme().colors().text_muted)- .when(is_parsing, |div| {+ .when(is_loading, |div| {div.child(h_flex().gap_2()@@ -62,26 +52,16 @@ impl Render for TabularDataPreviewPane {.child("Loading…"),)})- .when(!is_parsing, |div| {- if let Some(error) = &self.parse_error {- div.p_4()- .text_color(cx.theme().status().error)- .child(error.clone())- } else {- div.child("No data to display")- }- }),+ .when(!is_loading, |div| div.child("No data to display")),).into_any_element()} else {- self.create_table(&self.column_widths.widths, cx)+ self.create_table(&self.column_widths, cx)}});-- let render_prep_duration = render_prep_start.elapsed();self.performance_metrics.timings.insert("render_prep",- (render_prep_duration, std::time::Instant::now()),+ (render_prep_start.elapsed(), std::time::Instant::now()),);let div = div()diff --git a/crates/tabular_data_preview/src/renderer/render_table.rs b/crates/tabular_data_preview/src/renderer/render_table.rsindex 7ed0841f4bc..f2a2ea2ad67 100644--- a/crates/tabular_data_preview/src/renderer/render_table.rs+++ b/crates/tabular_data_preview/src/renderer/render_table.rs@@ -4,39 +4,23 @@ use std::ops::Range;use ui::{ColumnWidthConfig, ResizableColumnsState, Table, UncheckedTableRow, div, prelude::*};use crate::{- TabularDataPreviewPane,+ TableView,settings::RowRenderMechanism,types::{AnyColumn, DisplayCellId, DisplayRow},};-impl TabularDataPreviewPane {- /// Creates a new table.- /// Column number is derived from the `ResizableColumnsState` entity.+impl TableView {pub(crate) fn create_table(&self,current_widths: &Entity<ResizableColumnsState>,cx: &mut Context<Self>,) -> AnyElement {- self.create_table_inner(- self.engine.d2d_mapping().visible_row_count(),- current_widths,- cx,- )- }-- fn create_table_inner(- &self,- row_count: usize,- current_widths: &Entity<ResizableColumnsState>,- cx: &mut Context<Self>,- ) -> AnyElement {+ let row_count = self.engine.d2d_mapping().visible_row_count();let cols = current_widths.read(cx).cols();- // Create headers array with interactive elementslet mut headers = Vec::with_capacity(cols);headers.push(self.create_row_identifier_header(cx));- // Add the actual data headers with sort buttonsfor i in 0..(cols - 1) {let header_text = self.engine@@ -66,24 +50,22 @@ impl TabularDataPreviewPane {table.variable_row_height_list(row_count, self.list_state.clone(), {cx.processor(move |this, display_row: usize, _window, cx| {this.performance_metrics.rendered_indices.push(display_row);-- let display_row = DisplayRow(display_row);+ // The mapping may be transiently stale while a filter/sort task is in-flight. Return an empty row rather than panickingSelf::render_single_table_row(this,cols,- display_row,+ DisplayRow(display_row),row_identifier_text_color,this.row_height,cx,)- .unwrap_or_else(|| panic!("Expected to render a table row"))+ .unwrap_or_default()})})}RowRenderMechanism::UniformList => {table.uniform_list("tabular-data-table", row_count, {cx.processor(move |this, range: Range<usize>, _window, cx| {- // Record all display indices in the range for performance metricsthis.performance_metrics.rendered_indices.extend(range.clone());@@ -113,12 +95,12 @@ impl TabularDataPreviewPane {////// Used both by UniformList and VariableRowHeightListfn render_single_table_row(- this: &TabularDataPreviewPane,+ this: &TableView,cols: usize,display_row: DisplayRow,row_identifier_text_color: gpui::Hsla,row_height: Pixels,- cx: &Context<TabularDataPreviewPane>,+ cx: &Context<TableView>,) -> Option<UncheckedTableRow<AnyElement>> {// Get the actual row index from our sorted indiceslet data_row = this.engine.d2d_mapping().get_data_row(display_row)?;@@ -147,7 +129,7 @@ impl TabularDataPreviewPane {.overflow_hidden()},)- .child(TabularDataPreviewPane::create_selectable_cell(+ .child(TableView::create_selectable_cell(display_cell_id,cell_content,this.settings.vertical_alignment,diff --git a/crates/tabular_data_preview/src/renderer/row_identifiers.rs b/crates/tabular_data_preview/src/renderer/row_identifiers.rsindex bf1c69c6655..27bce1d9bde 100644--- a/crates/tabular_data_preview/src/renderer/row_identifiers.rs+++ b/crates/tabular_data_preview/src/renderer/row_identifiers.rs@@ -1,5 +1,5 @@use crate::{- TabularDataPreviewPane,+ TableView,settings::RowIdentifiers,types::{DataRow, DisplayRow, LineNumber},};@@ -46,7 +46,7 @@ impl LineNumber {}}-impl TabularDataPreviewPane {+impl TableView {/// Calculate the optimal width for the row identifier column (line numbers or row numbers).////// This ensures the column is wide enough to display the largest identifier comfortably,@@ -105,7 +105,7 @@ impl TabularDataPreviewPane {pub(crate) fn create_row_identifier_header(&self,- cx: &mut Context<'_, TabularDataPreviewPane>,+ cx: &mut Context<'_, TableView>,) -> AnyElement {let has_line_numbers = !self.engine.contents.line_numbers.is_empty();@@ -156,20 +156,21 @@ impl TabularDataPreviewPane {&self,display_row: DisplayRow,data_row: DataRow,- cx: &Context<'_, TabularDataPreviewPane>,+ cx: &Context<'_, TableView>,) -> Option<AnyElement> {let row_identifier: SharedString = match self.settings.numbering_type {- RowIdentifiers::SrcLines => self- .engine- .contents- .line_numbers- .get(*data_row)?- .display_string(if self.settings.multiline_cells_effectively_enabled() {- RowIdentDisplayMode::Vertical- } else {- RowIdentDisplayMode::Horizontal- })- .into(),+ // Fall back to a sequential row number when there is no source line for this row (e.g.+ // content that did not originate from a text buffer, such as a database result set).+ RowIdentifiers::SrcLines => match self.engine.contents.line_numbers.get(*data_row) {+ Some(line) => line+ .display_string(if self.settings.multiline_cells_effectively_enabled() {+ RowIdentDisplayMode::Vertical+ } else {+ RowIdentDisplayMode::Horizontal+ })+ .into(),+ None => (*display_row + 1).to_string().into(),+ },RowIdentifiers::RowNum => (*display_row + 1).to_string().into(),};diff --git a/crates/tabular_data_preview/src/renderer/settings.rs b/crates/tabular_data_preview/src/renderer/settings.rsindex 81b20d080fb..1e09735c15c 100644--- a/crates/tabular_data_preview/src/renderer/settings.rs+++ b/crates/tabular_data_preview/src/renderer/settings.rs@@ -5,8 +5,8 @@ use ui::{};use crate::{- TabularDataPreviewPane,- settings::{FilterSortOrder, TabularDataPreviewSettings, VerticalAlignment},+ TableView,+ settings::{FilterSortOrder, TableViewSettings, VerticalAlignment},};///// Settings related /////@@ -18,8 +18,8 @@ fn toggle_entry(label: &'static str,description: Option<&'static str>,selected: bool,- view_entity: &Entity<TabularDataPreviewPane>,- set: impl Fn(&mut TabularDataPreviewSettings) + 'static,+ view_entity: &Entity<TableView>,+ set: impl Fn(&mut TableViewSettings) + 'static,) -> ContextMenu {let view_entity = view_entity.clone();let entry = ContextMenuEntry::new(label)@@ -40,9 +40,7 @@ fn toggle_entry(menu.item(entry)}-pub(crate) fn settings_popover_menu(- view_entity: Entity<TabularDataPreviewPane>,-) -> PopoverMenu<ContextMenu> {+pub(crate) fn settings_popover_menu(view_entity: Entity<TableView>) -> PopoverMenu<ContextMenu> {PopoverMenu::new("table-settings-menu").trigger_with_tooltip(IconButton::new("table-settings-trigger", IconName::Filter)@@ -118,8 +116,8 @@ pub(crate) fn settings_popover_menu(#[cfg(feature = "dev-tools")]fn append_dev_only_entries(menu: ContextMenu,- view_entity: &Entity<TabularDataPreviewPane>,- settings: &TabularDataPreviewSettings,+ view_entity: &Entity<TableView>,+ settings: &TableViewSettings,) -> ContextMenu {use crate::settings::RowRenderMechanism;diff --git a/crates/tabular_data_preview/src/renderer/table_cell.rs b/crates/tabular_data_preview/src/renderer/table_cell.rsindex 1150f079cb8..4cb59d898ee 100644--- a/crates/tabular_data_preview/src/renderer/table_cell.rs+++ b/crates/tabular_data_preview/src/renderer/table_cell.rs@@ -3,7 +3,7 @@use gpui::{AnyElement, ClipboardItem, ElementId, MouseButton, StatefulInteractiveElement};use ui::{Color, Divider, Label, LabelSize, SharedString, Tooltip, div, prelude::*};-use crate::{TabularDataPreviewPane, settings::VerticalAlignment, types::DisplayCellId};+use crate::{TableView, settings::VerticalAlignment, types::DisplayCellId};/// Adds a right-click-to-copy handler and a tooltip showing `text` plus `hint`/// (e.g. "Right click to copy content") to a `Stateful` element.@@ -30,13 +30,13 @@ pub(crate) fn with_copy_on_right_click<E: StatefulInteractiveElement>(}))}-impl TabularDataPreviewPane {+impl TableView {/// Create selectable table cell with mouse event handlers.pub fn create_selectable_cell(display_cell_id: DisplayCellId,cell_content: SharedString,vertical_alignment: VerticalAlignment,- cx: &Context<TabularDataPreviewPane>,+ cx: &Context<TableView>,) -> AnyElement {create_table_cell(display_cell_id, cell_content, vertical_alignment, cx)// Mouse events handlers will be here@@ -49,7 +49,7 @@ fn create_table_cell(display_cell_id: DisplayCellId,cell_content: SharedString,vertical_alignment: VerticalAlignment,- cx: &Context<'_, TabularDataPreviewPane>,+ cx: &Context<'_, TableView>,) -> gpui::Stateful<Div> {let cell = div().id(ElementId::NamedInteger(diff --git a/crates/tabular_data_preview/src/renderer/table_header.rs b/crates/tabular_data_preview/src/renderer/table_header.rsindex 172a290c97a..1636f584433 100644--- a/crates/tabular_data_preview/src/renderer/table_header.rs+++ b/crates/tabular_data_preview/src/renderer/table_header.rs@@ -18,7 +18,7 @@ use ui::{};use crate::{- TabularDataPreviewPane,+ TableView,renderer::table_cell::with_copy_on_right_click,settings::FilterSortOrder,table_data_engine::{@@ -46,7 +46,7 @@ enum ColumnFilterListEntry {struct ColumnFilterDelegate {col: AnyColumn,- view: Entity<TabularDataPreviewPane>,+ view: Entity<TableView>,/// Row order frozen at open time (available entries sorted per the/// column's `FilterSortOrder`, then entries hidden by other columns'/// filters). Kept stable so toggling a value doesn't reshuffle the list@@ -67,7 +67,7 @@ struct ColumnFilterDelegate {impl ColumnFilterDelegate {fn new(col: AnyColumn,- view: Entity<TabularDataPreviewPane>,+ view: Entity<TableView>,sort_order: FilterSortOrder,column_filters: Arc<Vec<(FilterEntry, FilterEntryState)>>,cx: &mut Context<Picker<Self>>,@@ -519,12 +519,12 @@ impl PickerDelegate for ColumnFilterDelegate {}}-impl TabularDataPreviewPane {+impl TableView {/// Create header for data, which is orderable with text on the left and sort button on the rightpub(crate) fn create_header_element_with_sort_button(&self,header_text: SharedString,- cx: &mut Context<'_, TabularDataPreviewPane>,+ cx: &mut Context<'_, TableView>,col_idx: AnyColumn,) -> AnyElement {let has_active_filter = self.engine.has_active_filters(col_idx);@@ -600,11 +600,7 @@ impl TabularDataPreviewPane {.into_any_element()}- fn create_sort_button(- &self,- cx: &mut Context<'_, TabularDataPreviewPane>,- col_idx: AnyColumn,- ) -> Button {+ fn create_sort_button(&self, cx: &mut Context<'_, TableView>, col_idx: AnyColumn) -> Button {Button::new(ElementId::NamedInteger("sort-button".into(), col_idx.get() as u64),match self.engine.applied_sorting {@@ -649,14 +645,14 @@ impl TabularDataPreviewPane {}),};this.engine.applied_sorting = new_sorting;- this.apply_sort(cx);+ this.apply_filter_sort(cx);cx.notify();}))}fn create_filter_button(&self,- cx: &mut Context<'_, TabularDataPreviewPane>,+ cx: &mut Context<'_, TableView>,col: AnyColumn,) -> PopoverMenu<Picker<ColumnFilterDelegate>> {let has_active_filters = self.engine.has_active_filters(col);diff --git a/crates/tabular_data_preview/src/settings.rs b/crates/tabular_data_preview/src/settings.rsindex 652e9c271f2..418332eb114 100644--- a/crates/tabular_data_preview/src/settings.rs+++ b/crates/tabular_data_preview/src/settings.rs@@ -36,7 +36,7 @@ pub enum FilterSortOrder {}#[derive(Clone, Default)]-pub(crate) struct TabularDataPreviewSettings {+pub(crate) struct TableViewSettings {pub(crate) rendering_with: RowRenderMechanism,pub(crate) vertical_alignment: VerticalAlignment,pub(crate) numbering_type: RowIdentifiers,@@ -47,7 +47,7 @@ pub(crate) struct TabularDataPreviewSettings {pub(crate) multiline_cells_enabled: bool,}-impl TabularDataPreviewSettings {+impl TableViewSettings {/// `multiline_cells_enabled` only makes sense with `VariableList`, which/// supports per-row heights; `UniformList` requires every row to share one/// height, so multiline is never honored there regardless of the setting.diff --git a/crates/tabular_data_preview/src/table_view.rs b/crates/tabular_data_preview/src/table_view.rsnew file mode 100644index 00000000000..f6ae9d94f3f--- /dev/null+++ b/crates/tabular_data_preview/src/table_view.rs@@ -0,0 +1,214 @@+//! The reusable tabular-data viewer component.+//!+//! `TableView` owns the [`TableDataEngine`] (client-side filter/sort + display-to-data mapping)+//! and all of the grid rendering over `ui::Table`.+//!+//! It is deliberately source-agnostic: it renders whatever [`TableLikeContent`] it is handed+//! via [`TableView::set_contents`], whether that content comes from the CSV parser or from some+//! other producer (e.g. a database result set).++use std::{+ collections::HashMap,+ time::{Duration, Instant},+};++use gpui::{App, AppContext, Entity, FocusHandle, Focusable, ListAlignment, Task};+use ui::{+ AbsoluteLength, ResizableColumnsState, SharedString, TableInteractionState,+ TableResizeBehavior, prelude::*,+};++use crate::{+ settings::TableViewSettings,+ table_data_engine::{DisplayToDataMapping, TableDataEngine},+ types::{AnyColumn, TableLikeContent},+};++#[derive(Debug, Default)]+pub struct PerformanceMetrics {+ /// Map of timing metrics with their duration and measurement time.+ pub timings: HashMap<&'static str, (Duration, Instant)>,+ /// List of display indices that were rendered in the current frame.+ pub rendered_indices: Vec<usize>,+}++impl PerformanceMetrics {+ pub fn record<F, R>(&mut self, name: &'static str, mut f: F) -> R+ where+ F: FnMut() -> R,+ {+ let start_time = Instant::now();+ let ret = f();+ let duration = start_time.elapsed();+ self.timings.insert(name, (duration, Instant::now()));+ ret+ }++ /// Displays all metrics sorted A-Z in format: `{name}: {took}ms {ago}s ago`+ pub fn display(&self) -> String {+ let mut metrics = self.timings.iter().collect::<Vec<_>>();+ metrics.sort_by_key(|&(name, _)| *name);+ metrics+ .iter()+ .map(|(name, (duration, time))| {+ let took = duration.as_secs_f32() * 1000.;+ let ago = time.elapsed().as_secs();+ format!("{name}: {took:.3}ms {ago}s ago")+ })+ .collect::<Vec<_>>()+ .join("\n")+ }++ /// Get timing for a specific metric+ pub fn get_timing(&self, name: &str) -> Option<Duration> {+ self.timings.get(name).map(|(duration, _)| *duration)+ }+}++pub struct TableView {+ pub(crate) engine: TableDataEngine,+ pub(crate) focus_handle: FocusHandle,+ pub(crate) table_interaction_state: Entity<TableInteractionState>,+ pub(crate) column_widths: Entity<ResizableColumnsState>,+ /// Background task computing the display-to-data mapping after a filter/sort change.+ /// Stored here so that a new change cancels the previous in-flight computation.+ pub(crate) filter_sort_task: Option<Task<()>>,+ pub(crate) settings: TableViewSettings,+ /// Performance metrics for debugging and monitoring grid operations.+ pub(crate) performance_metrics: PerformanceMetrics,+ pub(crate) list_state: gpui::ListState,+ /// Cached row height, refreshed from the actual text line height on every render.+ /// Used to size not-yet-rendered rows for the scrollbar without a full `.measure_all()`+ /// pass, so it tracks the real row height instead of a hardcoded guess.+ pub(crate) row_height: Pixels,+ /// Whether the producer feeding this view is currently computing content. While set, the grid+ /// shows a loading indicator instead of the (stale or empty) table.+ pub(crate) is_loading: bool,+}++impl TableView {+ pub fn new(window: &Window, cx: &mut Context<Self>) -> Self {+ let contents = TableLikeContent::default();+ let table_interaction_state = cx.new(|cx| {+ TableInteractionState::new(cx).with_custom_scrollbar(ui::Scrollbars::for_settings::<+ editor::EditorSettingsScrollbarProxy,+ >())+ });+ let row_height = window.pixel_snap(window.line_height());++ Self {+ engine: TableDataEngine::default(),+ focus_handle: cx.focus_handle(),+ table_interaction_state,+ column_widths: cx.new(|_cx| {+ ResizableColumnsState::new(+ 1,+ vec![AbsoluteLength::Pixels(px(150.))],+ vec![TableResizeBehavior::Resizable],+ )+ }),+ filter_sort_task: None,+ settings: TableViewSettings::default(),+ performance_metrics: PerformanceMetrics::default(),+ list_state: gpui::ListState::new(contents.rows.len(), ListAlignment::Top, px(1.))+ .with_uniform_item_height(row_height),+ row_height,+ is_loading: false,+ }+ }++ /// Replace the data shown by the grid. Recomputes filter menus and column widths, kicks off the+ /// display-to-data recomputation, and clears the loading state.+ pub fn set_contents(&mut self, contents: TableLikeContent, cx: &mut Context<Self>) {+ self.engine.set_contents(contents);+ // The old mapping may reference rows removed by this change. Clear it immediately+ // rather than leaving the list showing stale rows until the background task below+ // recomputes the mapping.+ self.list_state+ .reset_with_uniform_height(0, self.row_height);+ self.sync_column_widths(cx);+ self.is_loading = false;+ self.apply_filter_sort(cx);+ }++ /// Toggle the loading indicator (shown while a producer computes new content).+ pub fn set_loading(&mut self, is_loading: bool, cx: &mut Context<Self>) {+ self.is_loading = is_loading;+ cx.notify();+ }++ pub(crate) fn sync_column_widths(&self, cx: &mut Context<Self>) {+ // plus 1 for the row identifier column+ let cols = self.engine.contents.headers.cols() + 1;+ let line_number_width = self.calculate_row_identifier_column_width();++ let mut widths: Vec<AbsoluteLength> = vec![AbsoluteLength::Pixels(px(150.)); cols];+ widths[0] = AbsoluteLength::Pixels(px(line_number_width));++ let mut resize_behaviors = vec![TableResizeBehavior::Resizable; cols];+ resize_behaviors[0] = TableResizeBehavior::None;++ self.column_widths.update(cx, |state, _cx| {+ if state.cols() != cols {+ *state = ResizableColumnsState::new(cols, widths, resize_behaviors);+ } else {+ state.set_column_configuration(+ 0,+ AbsoluteLength::Pixels(px(line_number_width)),+ TableResizeBehavior::None,+ );+ }+ });+ }++ pub fn clear_filters(&mut self, col: AnyColumn, cx: &mut Context<Self>) {+ self.engine.clear_filters_for_col(col);+ self.apply_filter_sort(cx);+ }++ pub fn toggle_filter(+ &mut self,+ col: AnyColumn,+ value: Option<SharedString>,+ cx: &mut Context<Self>,+ ) {+ if let Err(err) = self.engine.toggle_filter(col, value) {+ log::error!("Failed to toggle filter: {err}");+ return;+ }+ self.apply_filter_sort(cx);+ }++ /// Spawns a background task to recompute the display-to-data mapping after a filter or sort+ /// change. Storing the task cancels any previous in-flight computation automatically.+ pub(crate) fn apply_filter_sort(&mut self, cx: &mut Context<Self>) {+ let contents = self.engine.contents.clone();+ let filter_stack = self.engine.filter_stack.clone();+ let sorting = self.engine.applied_sorting;++ self.filter_sort_task = Some(cx.spawn(async move |this, cx| {+ let mapping = cx+ .background_spawn(async move {+ DisplayToDataMapping::compute(&contents, &filter_stack, sorting)+ })+ .await;++ this.update(cx, |view, cx| {+ view.engine.set_d2d_mapping(mapping);+ let visible_rows = view.engine.d2d_mapping().visible_row_count();+ // Uses the row height measured on the last render. Cheaper than a full+ // `.measure_all()` pass; exact row heights are re-measured on scrolling.+ view.list_state+ .reset_with_uniform_height(visible_rows, view.row_height);+ cx.notify();+ })+ .ok();+ }));+ }+}++impl Focusable for TableView {+ fn focus_handle(&self, _cx: &App) -> FocusHandle {+ self.focus_handle.clone()+ }+}diff --git a/crates/tabular_data_preview/src/tabular_data_preview.rs b/crates/tabular_data_preview/src/tabular_data_preview.rsindex 9b72d6f15aa..be05244dfea 100644--- a/crates/tabular_data_preview/src/tabular_data_preview.rs+++ b/crates/tabular_data_preview/src/tabular_data_preview.rs@@ -1,52 +1,36 @@use editor::{Editor, EditorEvent};-use gpui::{- AppContext, Entity, EventEmitter, FocusHandle, Focusable, ListAlignment, Task, actions,-};-use std::{- collections::HashMap,- time::{Duration, Instant},-};--use crate::table_data_engine::{DisplayToDataMapping, TableDataEngine};-use ui::{- AbsoluteLength, ResizableColumnsState, SharedString, TableInteractionState,- TableResizeBehavior, prelude::*,-};+use gpui::{AppContext, Entity, EventEmitter, FocusHandle, Focusable, Task, actions};++use ui::{SharedString, prelude::*};use workspace::{Item, Pane, Workspace};-use crate::{parser::EditorState, settings::TabularDataPreviewSettings, types::TableLikeContent};+use crate::parser::EditorState;++pub use crate::table_view::{PerformanceMetrics, TableView};mod parser;mod renderer;mod settings;mod table_data_engine;-mod types;+mod table_view;+pub mod types;actions!(tabular_data, [OpenPreview, OpenPreviewToTheSide]);+/// Editor-backed adapter: watches an [`Editor`], parses its buffer into a [`crate::types::TableLikeContent`],+/// and feeds the result to an embedded [`TableView`] that owns all grid rendering.pub struct TabularDataPreviewPane {- pub(crate) engine: TableDataEngine,-- pub(crate) focus_handle: FocusHandle,+ /// The reusable tabular viewer this adapter drives.+ pub(crate) table: Entity<TableView>,active_editor_state: EditorState,- pub(crate) table_interaction_state: Entity<TableInteractionState>,- pub(crate) column_widths: ColumnWidths,pub(crate) parsing_task: Option<Task<anyhow::Result<()>>>,pub(crate) is_parsing: bool,pub(crate) parse_error: Option<SharedString>,- /// Background task computing the display-to-data mapping after a filter/sort change.- /// Stored here so that a new change cancels the previous in-flight computation.- pub(crate) filter_sort_task: Option<Task<()>>,- pub(crate) settings: TabularDataPreviewSettings,- /// Performance metrics for debugging and monitoring tabular data operations.- pub(crate) performance_metrics: PerformanceMetrics,- pub(crate) list_state: gpui::ListState,- /// Cached row height, refreshed from the actual text line height on every render.- /// Used to size not-yet-rendered rows for the scrollbar without a full `.measure_all()`- /// pass, so it tracks the real row height instead of a hardcoded guess.- pub(crate) row_height: Pixels,/// Time when the last parsing operation ended, used for smart debouncingpub(crate) last_parse_end_time: Option<std::time::Instant>,+ /// Forwards the table's notifications so observers of this pane (e.g. `cx.condition` in+ /// tests, or anything watching for the mapping/list-state to settle) see them too.+ _table_subscription: gpui::Subscription,}pub fn init(cx: &mut App) {@@ -57,30 +41,6 @@ pub fn init(cx: &mut App) {}impl TabularDataPreviewPane {- pub(crate) fn sync_column_widths(&self, cx: &mut Context<Self>) {- // plus 1 for the row identifier column- let cols = self.engine.contents.headers.cols() + 1;- let line_number_width = self.calculate_row_identifier_column_width();-- let mut widths: Vec<AbsoluteLength> = vec![AbsoluteLength::Pixels(px(150.)); cols];- widths[0] = AbsoluteLength::Pixels(px(line_number_width));-- let mut resize_behaviors = vec![TableResizeBehavior::Resizable; cols];- resize_behaviors[0] = TableResizeBehavior::None;-- self.column_widths.widths.update(cx, |state, _cx| {- if state.cols() != cols {- *state = ResizableColumnsState::new(cols, widths, resize_behaviors);- } else {- state.set_column_configuration(- 0,- AbsoluteLength::Pixels(px(line_number_width)),- TableResizeBehavior::None,- );- }- });- }-pub fn register(workspace: &mut Workspace) {workspace.register_action_renderer(|div, _, _, cx| {div.on_action(cx.listener(|workspace, _: &OpenPreview, window, cx| {@@ -157,13 +117,6 @@ impl TabularDataPreviewPane {}fn new(editor: &Entity<Editor>, window: &Window, cx: &mut Context<Workspace>) -> Entity<Self> {- let contents = TableLikeContent::default();- let table_interaction_state = cx.new(|cx| {- TableInteractionState::new(cx).with_custom_scrollbar(ui::Scrollbars::for_settings::<- editor::EditorSettingsScrollbarProxy,- >())- });-cx.new(|cx| {let subscription = cx.subscribe(editor,@@ -177,26 +130,20 @@ impl TabularDataPreviewPane {},);- let row_height = window.pixel_snap(window.line_height());+ let table = cx.new(|cx| TableView::new(window, cx));+ let table_subscription = cx.observe(&table, |_, _, cx| cx.notify());+let mut view = TabularDataPreviewPane {- focus_handle: cx.focus_handle(),active_editor_state: EditorState {editor: editor.clone(),_subscription: subscription,},- table_interaction_state,- column_widths: ColumnWidths::new(cx, 1),+ table,parsing_task: None,is_parsing: false,parse_error: None,- filter_sort_task: None,- performance_metrics: PerformanceMetrics::default(),- list_state: gpui::ListState::new(contents.rows.len(), ListAlignment::Top, px(1.))- .with_uniform_item_height(row_height),- row_height,- settings: TabularDataPreviewSettings::default(),last_parse_end_time: None,- engine: TableDataEngine::default(),+ _table_subscription: table_subscription,};view.parse_from_active_editor(false, cx);@@ -207,54 +154,6 @@ impl TabularDataPreviewPane {pub(crate) fn editor_state(&self) -> &EditorState {&self.active_editor_state}- pub(crate) fn apply_sort(&mut self, cx: &mut Context<Self>) {- self.apply_filter_sort(cx);- }-- pub fn clear_filters(&mut self, col: types::AnyColumn, cx: &mut Context<Self>) {- self.engine.clear_filters_for_col(col);- self.apply_filter_sort(cx);- }-- pub fn toggle_filter(- &mut self,- col: types::AnyColumn,- value: Option<SharedString>,- cx: &mut Context<Self>,- ) {- if let Err(err) = self.engine.toggle_filter(col, value) {- log::error!("Failed to toggle filter: {err}");- return;- }- self.apply_filter_sort(cx);- }-- /// Spawns a background task to recompute the display-to-data mapping after a filter or sort- /// change. Storing the task cancels any previous in-flight computation automatically.- pub(crate) fn apply_filter_sort(&mut self, cx: &mut Context<Self>) {- let contents = self.engine.contents.clone();- let filter_stack = self.engine.filter_stack.clone();- let sorting = self.engine.applied_sorting;-- self.filter_sort_task = Some(cx.spawn(async move |this, cx| {- let mapping = cx- .background_spawn(async move {- DisplayToDataMapping::compute(&contents, &filter_stack, sorting)- })- .await;-- this.update(cx, |view, cx| {- view.engine.set_d2d_mapping(mapping);- let visible_rows = view.engine.d2d_mapping().visible_row_count();- // Uses the row height measured on the last render. Cheaper than a full- // `.measure_all()` pass; exact row heights are re-measured on scrolling.- view.list_state- .reset_with_uniform_height(visible_rows, view.row_height);- cx.notify();- })- .ok();- }));- }pub fn resolve_active_item_as_tabular_data_editor(workspace: &Workspace,@@ -272,8 +171,25 @@ impl TabularDataPreviewPane {}impl Focusable for TabularDataPreviewPane {- fn focus_handle(&self, _cx: &App) -> FocusHandle {- self.focus_handle.clone()+ fn focus_handle(&self, cx: &App) -> FocusHandle {+ self.table.read(cx).focus_handle(cx)+ }+}++impl Render for TabularDataPreviewPane {+ fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ div().size_full().child(match &self.parse_error {+ Some(error) => div()+ .size_full()+ .flex()+ .items_center()+ .justify_center()+ .p_4()+ .text_color(cx.theme().status().error)+ .child(error.clone())+ .into_any_element(),+ None => self.table.clone().into_any_element(),+ })}}@@ -305,65 +221,6 @@ impl Item for TabularDataPreviewPane {}}-#[derive(Debug, Default)]-pub struct PerformanceMetrics {- /// Map of timing metrics with their duration and measurement time.- pub timings: HashMap<&'static str, (Duration, Instant)>,- /// List of display indices that were rendered in the current frame.- pub rendered_indices: Vec<usize>,-}-impl PerformanceMetrics {- pub fn record<F, R>(&mut self, name: &'static str, mut f: F) -> R- where- F: FnMut() -> R,- {- let start_time = Instant::now();- let ret = f();- let duration = start_time.elapsed();- self.timings.insert(name, (duration, Instant::now()));- ret- }-- /// Displays all metrics sorted A-Z in format: `{name}: {took}ms {ago}s ago`- pub fn display(&self) -> String {- let mut metrics = self.timings.iter().collect::<Vec<_>>();- metrics.sort_by_key(|&(name, _)| *name);- metrics- .iter()- .map(|(name, (duration, time))| {- let took = duration.as_secs_f32() * 1000.;- let ago = time.elapsed().as_secs();- format!("{name}: {took:.3}ms {ago}s ago")- })- .collect::<Vec<_>>()- .join("\n")- }-- /// Get timing for a specific metric- pub fn get_timing(&self, name: &str) -> Option<Duration> {- self.timings.get(name).map(|(duration, _)| *duration)- }-}--/// Holds state of column widths for a table component in the tabular data preview.-pub(crate) struct ColumnWidths {- pub widths: Entity<ResizableColumnsState>,-}--impl ColumnWidths {- pub(crate) fn new(cx: &mut Context<TabularDataPreviewPane>, cols: usize) -> Self {- Self {- widths: cx.new(|_cx| {- ResizableColumnsState::new(- cols,- vec![AbsoluteLength::Pixels(px(150.)); cols],- vec![ui::TableResizeBehavior::Resizable; cols],- )- }),- }- }-}-#[cfg(test)]mod tests {use super::*;@@ -453,8 +310,15 @@ mod tests {let Some(preview) = preview else {anyhow::bail!("preview did not open");};- cx.condition(&preview, |preview, _| {- !preview.is_parsing && preview.engine.d2d_mapping().visible_row_count() == 2+ cx.condition(&preview, |preview, cx| {+ !preview.is_parsing+ && preview+ .table+ .read(cx)+ .engine+ .d2d_mapping()+ .visible_row_count()+ == 2}).await;@@ -462,13 +326,14 @@ mod tests {cx.observe(&preview, |preview, cx| {let preview = preview.read(cx);if !preview.is_parsing && preview.parse_error.is_none() {- let mapping = preview.engine.d2d_mapping();- assert_eq!(preview.list_state.item_count(), mapping.visible_row_count());+ let table = preview.table.read(cx);+ let mapping = table.engine.d2d_mapping();+ assert_eq!(table.list_state.item_count(), mapping.visible_row_count());for display_row in 0..mapping.visible_row_count() {assert!(mapping.get_data_row(DisplayRow(display_row))- .and_then(|data_row| preview.engine.contents.get_row(data_row))+ .and_then(|data_row| table.engine.contents.get_row(data_row)).is_some(),"display mapping points to a deleted row");@@ -489,10 +354,11 @@ mod tests {editor.update_in(cx, |editor, window, cx| {editor.set_text(text, window, cx);});- cx.condition(&preview, |preview, _| {+ cx.condition(&preview, |preview, cx| {+ let table = preview.table.read(cx);!preview.is_parsing- && preview.engine.contents.rows.len() == expected_rows- && preview.engine.d2d_mapping().visible_row_count() == expected_rows+ && table.engine.contents.rows.len() == expected_rows+ && table.engine.d2d_mapping().visible_row_count() == expected_rows}).await;}@@ -541,25 +407,45 @@ mod tests {let Some(preview) = preview else {anyhow::bail!("preview did not open");};- cx.condition(&preview, |preview, _| {- !preview.is_parsing && preview.engine.d2d_mapping().visible_row_count() == 2+ cx.condition(&preview, |preview, cx| {+ !preview.is_parsing+ && preview+ .table+ .read(cx)+ .engine+ .d2d_mapping()+ .visible_row_count()+ == 2}).await;preview.update(cx, |preview, cx| {- preview.engine.applied_sorting = Some(AppliedSorting {- col_idx: AnyColumn(0),- direction: SortDirection::Asc,+ preview.table.update(cx, |table, cx| {+ table.engine.applied_sorting = Some(AppliedSorting {+ col_idx: AnyColumn(0),+ direction: SortDirection::Asc,+ });+ table.toggle_filter(AnyColumn(0), Some(r#""Ada""#.into()), cx);});- preview.toggle_filter(AnyColumn(0), Some(r#""Ada""#.into()), cx);});- cx.condition(&preview, |preview, _| {- preview.engine.d2d_mapping().visible_row_count() == 1+ cx.condition(&preview, |preview, cx| {+ preview+ .table+ .read(cx)+ .engine+ .d2d_mapping()+ .visible_row_count()+ == 1}).await;- preview.read_with(cx, |preview, _| {+ preview.read_with(cx, |preview, cx| {assert_eq!(- preview.engine.d2d_mapping().get_data_row(DisplayRow(0)),+ preview+ .table+ .read(cx)+ .engine+ .d2d_mapping()+ .get_data_row(DisplayRow(0)),Some(DataRow(1)));});@@ -583,15 +469,22 @@ mod tests {editor.update_in(cx, |editor, window, cx| {editor.set_text("{\"name\":\"Ada\"}\n{\"name\":\"Grace\"}", window, cx);});- cx.condition(&preview, |preview, _| {+ cx.condition(&preview, |preview, cx| {!preview.is_parsing&& preview.parse_error.is_none()- && preview.engine.d2d_mapping().get_data_row(DisplayRow(0)) == Some(DataRow(0))+ && preview+ .table+ .read(cx)+ .engine+ .d2d_mapping()+ .get_data_row(DisplayRow(0))+ == Some(DataRow(0))}).await;- preview.read_with(cx, |preview, _| {- assert!(preview.engine.has_active_filters(AnyColumn(0)));- assert!(preview.engine.applied_sorting.is_some());+ preview.read_with(cx, |preview, cx| {+ let table = preview.table.read(cx);+ assert!(table.engine.has_active_filters(AnyColumn(0)));+ assert!(table.engine.applied_sorting.is_some());});editor.update_in(cx, |editor, window, cx| {@@ -601,15 +494,17 @@ mod tests {cx,);});- cx.condition(&preview, |preview, _| {+ cx.condition(&preview, |preview, cx| {+ let table = preview.table.read(cx);!preview.is_parsing- && preview.engine.contents.number_of_cols == 2- && preview.engine.d2d_mapping().visible_row_count() == 2+ && table.engine.contents.number_of_cols == 2+ && table.engine.d2d_mapping().visible_row_count() == 2}).await;- preview.read_with(cx, |preview, _| {- assert!(!preview.engine.has_active_filters(AnyColumn(0)));- assert!(preview.engine.applied_sorting.is_none());+ preview.read_with(cx, |preview, cx| {+ let table = preview.table.read(cx);+ assert!(!table.engine.has_active_filters(AnyColumn(0)));+ assert!(table.engine.applied_sorting.is_none());assert!(preview.parse_error.is_none());});Ok(())