## **Description:** **Context:** This PR introduces an initial CSV preview feature for Zed, building upon two previously merged infrastructure PRs: - [#46341](https://github.com/zed-industries/zed/pull/46341) - Data table dynamic column support (removed const generics) - [#46190](https://github.com/zed-industries/zed/pull/46190) - Variable row height mode for data tables This implementation is based on the [original draft PR #44344](https://github.com/zed-industries/zed/pull/44344), which has been carefully decomposed into smaller, reviewable pieces. --- #### **Features Included:** **Core Infrastructure:** - Live CSV parsing with smart debouncing (200ms cooldown) - Performance monitoring with built-in timing metrics (not displayed in UI yet) - Automatic file change detection and re-parsing - Support for quoted fields, multiline cells, and escaped characters **Table Display:** - Variable row height rendering with fallback to uniform mode (switchable via settings) - Draggable column resizing (reusing existing data table infrastructure) - Row identifiers supporting both source line numbers and sequential row numbers - Configurable font rendering (UI font vs monospace) - Tooltips showing full cell content on hover **Interactive Features:** - Column sorting (ascending/descending) with visual indicators **Settings Panel:** - Toggle between variable/uniform row rendering - Font type selection (UI/monospace) - Row identifier type configuration - Debug information display - Multiline cell rendering options --- #### **Features Intentionally Removed for This PR:** To reduce complexity and review scope, the following features were temporarily reverted and will be reintroduced in subsequent PRs: - ❌ Settings pannel with performance metrics overlay - ❌ Cell selection (single, multiple, and range selections) - ❌ Keyboard navigation with arrow keys and selection extension - ❌ Copy functionality supporting CSV, TSV, and Markdown table formats - ❌ Inline cell editing with file persistence - ❌ Viewport following for large datasets - ❌ Column filtering and search capabilities These removals were done via "time-machine" commits that cleanly nuked vertical slices of functionality from the complete implementation. --- **Technical Implementation:** The feature is organized into a dedicated `csv_preview` crate with the following structure: ``` crates/csv_preview/ ├── src/ │ ├── csv_preview.rs # Main view and coordination logic │ ├── parser.rs # CSV parsing and editor integration │ ├── settings.rs # Configuration types and defaults │ ├── table_data_engine.rs # Data transformation logic │ ├── renderer/ # UI rendering modules │ │ ├── preview_view.rs # Main render implementation │ │ ├── render_table.rs # Table component assembly │ │ ├── table_cell.rs # Individual cell rendering │ │ ├── table_header.rs # Header with sorting controls │ │ └── row_identifiers.rs # Line number column │ └── types/ # Core data structures │ ├── table_like_content.rs │ ├── coordinates.rs # Display vs data coordinate systems │ └── table_cell.rs ``` **Key architectural decisions:** - **Dual coordinate system**: Separates data indices from display indices to support sorting/filtering - **Component reuse**: Leverages existing `data_table` infrastructure from the keymap editor --- **Integration:** - Registers `csv::OpenPreview` action (currently without default keybindings) - Follows the same workspace integration pattern as `markdown_preview` and `svg_preview` - Automatically detects `.csv` file extensions - Tab integration with appropriate icons and naming --- **Code Structure Note:** Some code structures, types, and documentation may appear redundant or over-engineered in this initial implementation. This is intentional - the feature was developed as a complete system and then decomposed by functionality rather than being built incrementally. The "extra" infrastructure supports features that were removed for this PR but will be reintroduced in subsequent ones. This approach was chosen over extensive refactoring because: 1. The complete feature took 200+ commits to develop with significant rewrites 2. Clean extraction of vertical slices was more feasible than rebuilding incrementally 3. The end state will utilize all these components, making current "redundancy" temporary I apologize for any inconvenience this may cause during review, but the alternative would have required significant refactoring effort just to make intermediate states "prettier," which seemed counterproductive. --- **Future Work:** This lays the groundwork for upcoming PRs that will reintroduce the removed features: - Cell selection and keyboard navigation - Copy functionality with multiple output formats - Inline editing capabilities with undo/redo - Column filtering and search - TSV and other delimiter support - Improved horizontal scrolling behavior - Settings persistence **Testing:** Includes test fixtures demonstrating multiline cell handling, various column counts, and edge cases. --- **Release Notes:** - N/A This is feature flagged --------- Co-authored-by: Anthony Eid <anthony@zed.dev>
91 lines
3.0 KiB
Rust
91 lines
3.0 KiB
Rust
//! This module defines core operations and config of tabular data view (CSV table)
|
|
//! It operates in 2 coordinate systems:
|
|
//! - `DataCellId` - indices of src data cells
|
|
//! - `DisplayCellId` - indices of data after applied transformations like sorting/filtering, which is used to render cell on the screen
|
|
//!
|
|
//! It's designed to contain core logic of operations without relying on `CsvPreviewView`, context or window handles.
|
|
|
|
use std::{collections::HashMap, sync::Arc};
|
|
|
|
use ui::table_row::TableRow;
|
|
|
|
use crate::{
|
|
table_data_engine::sorting_by_column::{AppliedSorting, sort_data_rows},
|
|
types::{DataRow, DisplayRow, TableCell, TableLikeContent},
|
|
};
|
|
|
|
pub mod sorting_by_column;
|
|
|
|
#[derive(Default)]
|
|
pub(crate) struct TableDataEngine {
|
|
pub applied_sorting: Option<AppliedSorting>,
|
|
d2d_mapping: DisplayToDataMapping,
|
|
pub contents: TableLikeContent,
|
|
}
|
|
|
|
impl TableDataEngine {
|
|
pub(crate) fn d2d_mapping(&self) -> &DisplayToDataMapping {
|
|
&self.d2d_mapping
|
|
}
|
|
|
|
pub(crate) fn apply_sort(&mut self) {
|
|
self.d2d_mapping
|
|
.apply_sorting(self.applied_sorting, &self.contents.rows);
|
|
self.d2d_mapping.merge_mappings();
|
|
}
|
|
|
|
/// Applies sorting and filtering to the data and produces display to data mapping
|
|
pub(crate) fn calculate_d2d_mapping(&mut self) {
|
|
self.d2d_mapping
|
|
.apply_sorting(self.applied_sorting, &self.contents.rows);
|
|
self.d2d_mapping.merge_mappings();
|
|
}
|
|
}
|
|
|
|
/// Relation of Display (rendered) rows to Data (src) rows with applied transformations
|
|
/// Transformations applied:
|
|
/// - sorting by column
|
|
#[derive(Debug, Default)]
|
|
pub struct DisplayToDataMapping {
|
|
/// All rows sorted, regardless of applied filtering. Applied every time sorting changes
|
|
pub sorted_rows: Vec<DataRow>,
|
|
/// Filtered and sorted rows. Computed cheaply from `sorted_mapping` and `filtered_out_rows`
|
|
pub mapping: Arc<HashMap<DisplayRow, DataRow>>,
|
|
}
|
|
|
|
impl DisplayToDataMapping {
|
|
/// Get the data row for a given display row
|
|
pub fn get_data_row(&self, display_row: DisplayRow) -> Option<DataRow> {
|
|
self.mapping.get(&display_row).copied()
|
|
}
|
|
|
|
/// Get the number of filtered rows
|
|
pub fn visible_row_count(&self) -> usize {
|
|
self.mapping.len()
|
|
}
|
|
|
|
/// Computes sorting
|
|
fn apply_sorting(&mut self, sorting: Option<AppliedSorting>, rows: &[TableRow<TableCell>]) {
|
|
let data_rows: Vec<DataRow> = (0..rows.len()).map(DataRow).collect();
|
|
|
|
let sorted_rows = if let Some(sorting) = sorting {
|
|
sort_data_rows(&rows, data_rows, sorting)
|
|
} else {
|
|
data_rows
|
|
};
|
|
|
|
self.sorted_rows = sorted_rows;
|
|
}
|
|
|
|
/// Take pre-computed sorting and filtering results, and apply them to the mapping
|
|
fn merge_mappings(&mut self) {
|
|
self.mapping = Arc::new(
|
|
self.sorted_rows
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(display, data)| (DisplayRow(display), *data))
|
|
.collect(),
|
|
);
|
|
}
|
|
}
|