Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/csv_preview/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ path = "src/csv_preview.rs"

[dependencies]
anyhow.workspace = true
itertools.workspace = true
feature_flags.workspace = true
gpui.workspace = true
editor.workspace = true
Expand Down
70 changes: 54 additions & 16 deletions crates/csv_preview/src/csv_preview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::{
time::{Duration, Instant},
};

use crate::table_data_engine::TableDataEngine;
use crate::table_data_engine::{DisplayToDataMapping, TableDataEngine};
use ui::{
AbsoluteLength, ResizableColumnsState, SharedString, TableInteractionState,
TableResizeBehavior, prelude::*,
Expand Down Expand Up @@ -41,6 +41,10 @@ pub struct CsvPreviewView {
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,
/// 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: CsvPreviewSettings,
/// Performance metrics for debugging and monitoring CSV operations.
pub(crate) performance_metrics: PerformanceMetrics,
Expand Down Expand Up @@ -178,9 +182,11 @@ impl CsvPreviewView {
table_interaction_state,
column_widths: ColumnWidths::new(cx, 1),
parsing_task: None,
is_parsing: false,
filter_sort_task: None,
performance_metrics: PerformanceMetrics::default(),
list_state: gpui::ListState::new(contents.rows.len(), ListAlignment::Top, px(1.))
.measure_all(),
.with_uniform_item_height(px(24.)),
settings: CsvPreviewSettings::default(),
last_parse_end_time: None,
engine: TableDataEngine::default(),
Expand All @@ -194,22 +200,54 @@ impl CsvPreviewView {
pub(crate) fn editor_state(&self) -> &EditorState {
&self.active_editor_state
}
pub(crate) fn apply_sort(&mut self) {
self.performance_metrics.record("Sort", || {
self.engine.apply_sort();
});
pub(crate) fn apply_sort(&mut self, cx: &mut Context<Self>) {
self.apply_filter_sort(cx);
}

/// Update ordered indices when ordering or content changes
pub(crate) fn apply_filter_sort(&mut self) {
self.performance_metrics.record("Filter&sort", || {
self.engine.calculate_d2d_mapping();
});
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);
}

// Update list state with filtered row count
let visible_rows = self.engine.d2d_mapping().visible_row_count();
self.list_state =
gpui::ListState::new(visible_rows, ListAlignment::Top, px(100.)).measure_all();
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();
// Approximation of single csv table row height. Will be re-measured on scrolling.
// This cheap solution allow to render scrollbar with fraction of a cost compared to `.measure_all()` call
let approximate_height = px(24.);
view.list_state
.reset_with_uniform_height(visible_rows, approximate_height);
cx.notify();
})
.ok();
}));
}

pub fn resolve_active_item_as_csv_editor(
Expand Down Expand Up @@ -301,7 +339,7 @@ impl PerformanceMetrics {
.map(|(name, (duration, time))| {
let took = duration.as_secs_f32() * 1000.;
let ago = time.elapsed().as_secs();
format!("{name}: {took:.2}ms {ago}s ago")
format!("{name}: {took:.3}ms {ago}s ago")
})
.collect::<Vec<_>>()
.join("\n")
Expand Down
9 changes: 7 additions & 2 deletions crates/csv_preview/src/parser.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::sync::Arc;

use crate::{
CsvPreviewView,
types::TableLikeContent,
Expand All @@ -23,6 +25,7 @@ impl CsvPreviewView {
cx: &mut Context<Self>,
) {
let editor = self.active_editor_state.editor.clone();
self.is_parsing = true;
self.parsing_task = Some(self.parse_csv_in_background(wait_for_debounce, editor, cx));
}

Expand Down Expand Up @@ -80,11 +83,13 @@ impl CsvPreviewView {
.insert("Parsing", (parse_duration, Instant::now()));

log::debug!("Parsed {} rows", parsed_csv.rows.len());
view.engine.contents = parsed_csv;
view.engine.contents = Arc::new(parsed_csv);
view.engine.calculate_available_filters();
view.sync_column_widths(cx);
view.last_parse_end_time = Some(parse_end_time);

view.apply_filter_sort();
view.is_parsing = false;
view.apply_filter_sort(cx);
cx.notify();
})
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl CsvPreviewView {

let children = div()
.absolute()
.top_24()
.bottom_8()
.right_4()
.px_3()
.py_2()
Expand Down
16 changes: 12 additions & 4 deletions crates/csv_preview/src/renderer/preview_view.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::time::Instant;

use ui::{div, prelude::*};
use ui::{SpinnerLabel, div, prelude::*};

use crate::CsvPreviewView;

Expand All @@ -11,12 +11,12 @@ impl Render for CsvPreviewView {
let render_prep_start = Instant::now();
let table_with_settings = v_flex()
.size_full()
.p_4()
.bg(theme.colors().editor_background)
.track_focus(&self.focus_handle)
.child(self.render_settings_panel(window, cx))
.child({
if self.engine.contents.number_of_cols == 0 {
let is_parsing = self.is_parsing;
if is_parsing || self.engine.contents.number_of_cols == 0 {
div()
.flex()
.items_center()
Expand All @@ -25,7 +25,15 @@ impl Render for CsvPreviewView {
.text_ui(cx)
.font_buffer(cx)
.text_color(cx.theme().colors().text_muted)
.child("No CSV content to display")
.when(is_parsing, |div| {
div.child(
h_flex()
.gap_2()
.child(SpinnerLabel::new())
.child("Loading…"),
)
})
.when(!is_parsing, |div| div.child("No CSV content to display"))
.into_any_element()
} else {
self.create_table(&self.column_widths.widths, cx)
Expand Down
1 change: 1 addition & 0 deletions crates/csv_preview/src/renderer/row_identifiers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ impl CsvPreviewView {
.px_1()
.border_b_1()
.border_color(cx.theme().colors().border_variant)
.bg(cx.theme().colors().panel_background)
.h_full()
.text_ui(cx)
// Row identifiers are always centered
Expand Down
54 changes: 53 additions & 1 deletion crates/csv_preview/src/renderer/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ use ui::{
IntoElement as _, ParentElement as _, Styled as _, Tooltip, Window, div, h_flex,
};

use crate::{CsvPreviewView, settings::VerticalAlignment};
use crate::{
CsvPreviewView,
settings::{FilterSortOrder, VerticalAlignment},
};

///// Settings related /////
impl CsvPreviewView {
Expand All @@ -18,6 +21,11 @@ impl CsvPreviewView {
VerticalAlignment::Center => "Center",
};

let current_filter_sort_text = match self.settings.filter_sort_order {
FilterSortOrder::AlphaThenCount => "A-Z, then Count",
FilterSortOrder::CountThenAlpha => "Count, then A-Z",
};

let view = cx.entity();
let alignment_dropdown_menu = ContextMenu::build(window, cx, |menu, _window, _cx| {
menu.entry("Top", None, {
Expand All @@ -40,6 +48,28 @@ impl CsvPreviewView {
})
});

let filter_sort_dropdown_menu =
ContextMenu::build(window, cx, |menu, _window, _cx| {
menu.entry("A-Z, then Count", None, {
let view = view.clone();
move |_window, cx| {
view.update(cx, |this, cx| {
this.settings.filter_sort_order = FilterSortOrder::AlphaThenCount;
cx.notify();
});
}
})
.entry("Count, then A-Z", None, {
let view = view.clone();
move |_window, cx| {
view.update(cx, |this, cx| {
this.settings.filter_sort_order = FilterSortOrder::CountThenAlpha;
cx.notify();
});
}
})
});

let panel = h_flex()
.gap_4()
.p_2()
Expand Down Expand Up @@ -68,6 +98,28 @@ impl CsvPreviewView {
"Choose vertical text alignment within cells",
)),
),
)
.child(
h_flex()
.gap_2()
.items_center()
.child(
div()
.text_sm()
.text_color(cx.theme().colors().text_muted)
.child("Filter Sort:"),
)
.child(
DropdownMenu::new(
ElementId::Name("filter-sort-order-dropdown".into()),
current_filter_sort_text,
filter_sort_dropdown_menu,
)
.trigger_size(ButtonSize::Compact)
.trigger_tooltip(Tooltip::text(
"Choose how filter values are sorted in the filter menu",
)),
),
);

#[cfg(feature = "dev-tools")]
Expand Down
Loading
Loading