Files
zed/crates/tabular_data_preview/src/table_data_engine.rs
T
Oleksandr Kholiavko 3fec483014 tabular_data_preview: Single-cell focus and arrow navigation with reveal (1/8) (#64916)
## Overview

Part **1 of 8** in a series adding full keyboard/mouse navigation, cell
selection, multi-format clipboard copying, and keyboard-driven
sorting/filtering to `tabular_data_preview`.

Split into small, isolated PRs for review safety. The feature is gated
to debug/test builds (`cfg!(any(test, debug_assertions))`) until PR 6
(copying + context menus) to avoid exposing selection without copy
support.

---

### Full Series Roadmap

**1/8 (This PR):** Single-cell focus & arrow navigation with viewport
reveal
**2/8:** Range selection (`Shift+Arrows`), edge jumps
(`Cmd/Ctrl+Arrows`, `Home/End`), and page jumps (`PageUp/Down`)
**3/8:** Mouse selection, Shift+Click extension, and drag-to-select
**4/8:** Select All (`Cmd/Ctrl+A`) across datasets
**5/8:** Multi-format copy engine (TSV, CSV, Markdown, JSON Lines) &
`CopySelected`
**6/8:** Context menu, copy format settings, toasts, and release
enablement
**7/8:** Row selection via row gutter click/drag
**8/8:** Keyboard sorting (`Alt+S`), filter popover (`Alt+F`), and
filter clear (`Cmd/Ctrl+Alt+Backspace`)


NOTE, that all work is done & running on my machine end to end. The
split is just code review organization buerocracy.

<summary>
👇 Demo of fully ready feature👇 
</summary>
<details>


https://github.com/user-attachments/assets/696554f9-ca3e-4b74-83d1-948292668334



https://github.com/user-attachments/assets/5ef5f1f1-4f15-4b01-b825-de592d8a1972



https://github.com/user-attachments/assets/40c0e57f-da7a-440a-9ee6-48af8abe116e


</details>

---

### Changes in this PR (1/8)

1. **Data-Space Coordinates (`CellSelection`):** Coordinates anchor to
`DataCellId { row: DataRow, col: AnyColumn }` so selection survives
background sorting/filtering without shifting rows.
2. **Single-Cell Navigation (`tabular_data::MoveFocusedCell`):** Arrow
navigation (`Up`/`Down`/`Left`/`Right`), initializing focus at `(0, 0)`
on first movement.
3. **Viewport Auto-Scroll & Peek Cushion:** Auto-scrolls focused cells
with a 20px horizontal peek buffer and 1-row vertical context cushion.
4. **Focus & Outline:** Renders focused cell border
(`theme.colors().border_focused`) and binds `"context": "TableView"`.
5. **Debug Gating:** Hidden in release builds via
`is_selection_enabled()` until copying lands in PR 6.

---

Release Notes:

- N/A

---------

Co-authored-by: Christopher Biscardi <chris@christopherbiscardi.com>
2026-10-03 01:03:39 +00:00

158 lines
5.4 KiB
Rust

//! This module defines core operations and config of the tabular data view
//! 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 `TabularDataPreviewPane`, context or window handles.
use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
use ui::table_row::TableRow;
use crate::{
table_data_engine::{
filtering_by_column::{FilterEntry, FilterStack, calculate_available_filters, retain_rows},
sorting_by_column::{AppliedSorting, sort_data_rows},
},
types::{AnyColumn, DataRow, DisplayRow, TableCell, TableLikeContent},
};
pub mod filtering_by_column;
pub mod sorting_by_column;
#[derive(Default)]
pub(crate) struct TableDataEngine {
pub filter_stack: FilterStack,
/// Pre-computed unique values per column, used to populate filter menus
all_filters: HashMap<AnyColumn, Vec<FilterEntry>>,
pub applied_sorting: Option<AppliedSorting>,
d2d_mapping: DisplayToDataMapping,
pub contents: Arc<TableLikeContent>,
}
impl TableDataEngine {
pub(crate) fn set_contents(&mut self, contents: TableLikeContent) {
if self
.contents
.headers
.as_slice()
.iter()
.map(TableCell::display_value)
.ne(contents
.headers
.as_slice()
.iter()
.map(TableCell::display_value))
{
// Filters and sorting use column indexes, which may now name different fields.
self.filter_stack = FilterStack::default();
self.applied_sorting = None;
}
self.contents = Arc::new(contents);
// The previous mapping can reference rows removed by an edit. Keep it empty
// until the background filter/sort task builds a mapping for the new contents.
self.d2d_mapping = DisplayToDataMapping::default();
self.calculate_available_filters();
}
pub(crate) fn d2d_mapping(&self) -> &DisplayToDataMapping {
&self.d2d_mapping
}
pub(crate) fn set_d2d_mapping(&mut self, mapping: DisplayToDataMapping) {
self.d2d_mapping = mapping;
}
/// Recomputes the unique filter entries for every column from the current table data.
/// Must be called after content changes (e.g. after parsing).
pub fn calculate_available_filters(&mut self) {
self.all_filters =
calculate_available_filters(&self.contents.rows, self.contents.number_of_cols);
}
}
/// Relation of Display (rendered) rows to Data (src) rows with applied transformations
/// Transformations applied:
/// - sorting by column
/// - filtering by column values
#[derive(Debug, Default)]
pub struct DisplayToDataMapping {
/// All rows sorted, regardless of applied filtering. Recomputed every time sorting changes
pub sorted_rows: Vec<DataRow>,
/// Rows that survive the active filters. Recomputed every time filters change
pub retained_rows: HashSet<DataRow>,
/// Merged result: sorted rows intersected with retained rows
pub mapping: Arc<HashMap<DisplayRow, DataRow>>,
}
impl DisplayToDataMapping {
/// Computes the full display-to-data mapping from owned inputs.
/// Intended to be called from a background thread.
pub(crate) fn compute(
contents: &Arc<TableLikeContent>,
filter_stack: &FilterStack,
sorting: Option<AppliedSorting>,
) -> Self {
let mut mapping = Self::default();
mapping.apply_sorting(sorting, &contents.rows);
mapping.apply_filtering(filter_stack, &contents.rows);
mapping.merge_mappings();
mapping
}
/// 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 display row for a given data row
pub fn get_display_row(&self, data_row: DataRow) -> Option<DisplayRow> {
self.mapping
.iter()
.find_map(|(&display_row, &mapped_data_row)| {
if mapped_data_row == data_row {
Some(display_row)
} else {
None
}
})
}
/// 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;
}
fn apply_filtering(&mut self, filter_stack: &FilterStack, rows: &[TableRow<TableCell>]) {
self.retained_rows = retain_rows(rows, filter_stack, None);
}
/// Merges pre-computed sorting and filtering into the final display mapping
fn merge_mappings(&mut self) {
self.mapping = Arc::new(
self.sorted_rows
.iter()
.filter(|data_row| self.retained_rows.contains(data_row))
.enumerate()
.map(|(display, data)| (DisplayRow(display), *data))
.collect(),
);
}
}