Skip to content

armgit / zed

Public Imported from GitHub
0

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: Single-cell focus and arrow navigation with reveal (1/8) (#64916)

Oleksandr Kholiavko3fec4830142a
diff --git a/Cargo.lock b/Cargo.lock
index 492307a40fb..a39082d6797 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -18128,6 +18128,8 @@ dependencies = [
"picker",
"project",
"proptest",
+ "schemars 1.0.4",
+ "serde",
"serde_json",
"text",
"ui",
diff --git a/assets/keymaps/default-linux.json b/assets/keymaps/default-linux.json
index 8f05d55e2ac..5d7aa8f5833 100644
--- a/assets/keymaps/default-linux.json
+++ b/assets/keymaps/default-linux.json
@@ -1677,4 +1677,13 @@
"shift-tab": "skill_creator::FocusPreviousField",
},
},
+ {
+ "context": "TableView",
+ "bindings": {
+ "up": ["tabular_data::MoveFocusedCell", { "direction": "up" }],
+ "down": ["tabular_data::MoveFocusedCell", { "direction": "down" }],
+ "left": ["tabular_data::MoveFocusedCell", { "direction": "left" }],
+ "right": ["tabular_data::MoveFocusedCell", { "direction": "right" }],
+ },
+ },
]
diff --git a/assets/keymaps/default-macos.json b/assets/keymaps/default-macos.json
index 38ce1ab5aad..f084301b614 100644
--- a/assets/keymaps/default-macos.json
+++ b/assets/keymaps/default-macos.json
@@ -1770,4 +1770,14 @@
"shift-tab": "skill_creator::FocusPreviousField",
},
},
+ {
+ "context": "TableView",
+ "use_key_equivalents": true,
+ "bindings": {
+ "up": ["tabular_data::MoveFocusedCell", { "direction": "up" }],
+ "down": ["tabular_data::MoveFocusedCell", { "direction": "down" }],
+ "left": ["tabular_data::MoveFocusedCell", { "direction": "left" }],
+ "right": ["tabular_data::MoveFocusedCell", { "direction": "right" }],
+ },
+ },
]
diff --git a/assets/keymaps/default-windows.json b/assets/keymaps/default-windows.json
index 02f8b066023..0f2a06b6cee 100644
--- a/assets/keymaps/default-windows.json
+++ b/assets/keymaps/default-windows.json
@@ -1691,4 +1691,14 @@
"shift-tab": "skill_creator::FocusPreviousField",
},
},
+ {
+ "context": "TableView",
+ "use_key_equivalents": true,
+ "bindings": {
+ "up": ["tabular_data::MoveFocusedCell", { "direction": "up" }],
+ "down": ["tabular_data::MoveFocusedCell", { "direction": "down" }],
+ "left": ["tabular_data::MoveFocusedCell", { "direction": "left" }],
+ "right": ["tabular_data::MoveFocusedCell", { "direction": "right" }],
+ },
+ },
]
diff --git a/crates/tabular_data_preview/Cargo.toml b/crates/tabular_data_preview/Cargo.toml
index 6fa37648b52..d61635bbfc4 100644
--- a/crates/tabular_data_preview/Cargo.toml
+++ b/crates/tabular_data_preview/Cargo.toml
@@ -18,7 +18,9 @@ ui.workspace = true
workspace.workspace = true
log.workspace = true
indexmap.workspace = true
+serde.workspace = true
serde_json.workspace = true
+schemars.workspace = true
text.workspace = true
[dev-dependencies]
diff --git a/crates/tabular_data_preview/src/renderer/preview_view.rs b/crates/tabular_data_preview/src/renderer/preview_view.rs
index e60a4e36e00..b76c4f1f8b1 100644
--- a/crates/tabular_data_preview/src/renderer/preview_view.rs
+++ b/crates/tabular_data_preview/src/renderer/preview_view.rs
@@ -18,9 +18,11 @@ impl Render for TableView {
}
let render_prep_start = std::time::Instant::now();
let table_with_settings = v_flex()
+ .key_context("TableView")
.size_full()
.bg(theme.colors().editor_background)
.track_focus(&self.focus_handle)
+ .on_action(cx.listener(Self::move_focused_cell))
.child({
let is_loading = self.is_loading;
if is_loading || self.engine.contents.number_of_cols == 0 {
diff --git a/crates/tabular_data_preview/src/renderer/render_table.rs b/crates/tabular_data_preview/src/renderer/render_table.rs
index f2a2ea2ad67..f24bcb5e162 100644
--- a/crates/tabular_data_preview/src/renderer/render_table.rs
+++ b/crates/tabular_data_preview/src/renderer/render_table.rs
@@ -1,12 +1,12 @@
use crate::types::TableCell;
-use gpui::{AnyElement, Entity};
+use gpui::{AnyElement, Entity, Hsla};
use std::ops::Range;
use ui::{ColumnWidthConfig, ResizableColumnsState, Table, UncheckedTableRow, div, prelude::*};
use crate::{
TableView,
settings::RowRenderMechanism,
- types::{AnyColumn, DisplayCellId, DisplayRow},
+ types::{AnyColumn, DataCellId, DisplayCellId, DisplayRow},
};
impl TableView {
@@ -98,7 +98,7 @@ impl TableView {
this: &TableView,
cols: usize,
display_row: DisplayRow,
- row_identifier_text_color: gpui::Hsla,
+ row_identifier_text_color: Hsla,
row_height: Pixels,
cx: &Context<TableView>,
) -> Option<UncheckedTableRow<AnyElement>> {
@@ -117,6 +117,18 @@ impl TableView {
let cell_content = table_cell.display_value().cloned().unwrap_or_default();
let display_cell_id = DisplayCellId::new(display_row, col);
+ let data_cell_id = DataCellId::new(data_row, col);
+
+ let is_focus_cell = this
+ .selection
+ .as_ref()
+ .is_some_and(|selection| selection.focus == data_cell_id);
+
+ let cell_bg = if is_focus_cell {
+ Some(cx.theme().colors().element_selected)
+ } else {
+ None
+ };
let cell = div()
.size_full()
@@ -139,6 +151,7 @@ impl TableView {
elements.push(
div()
.size_full()
+ .when_some(cell_bg, |div, color| div.bg(color))
.when(this.settings.show_debug_info, |parent| {
parent.child(div().text_color(row_identifier_text_color).child(
match table_cell {
diff --git a/crates/tabular_data_preview/src/table_data_engine.rs b/crates/tabular_data_preview/src/table_data_engine.rs
index b803439d6d4..2a3b40e2b3c 100644
--- a/crates/tabular_data_preview/src/table_data_engine.rs
+++ b/crates/tabular_data_preview/src/table_data_engine.rs
@@ -108,6 +108,19 @@ impl DisplayToDataMapping {
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()
diff --git a/crates/tabular_data_preview/src/table_view.rs b/crates/tabular_data_preview/src/table_view.rs
index f6ae9d94f3f..3bcc7cd5e51 100644
--- a/crates/tabular_data_preview/src/table_view.rs
+++ b/crates/tabular_data_preview/src/table_view.rs
@@ -12,18 +12,47 @@ use std::{
time::{Duration, Instant},
};
-use gpui::{App, AppContext, Entity, FocusHandle, Focusable, ListAlignment, Task};
+use gpui::{
+ App, AppContext, Entity, FocusHandle, Focusable, ListAlignment, ListState, Point, Task, Window,
+};
use ui::{
AbsoluteLength, ResizableColumnsState, SharedString, TableInteractionState,
TableResizeBehavior, prelude::*,
};
use crate::{
+ MoveFocusedCell, NavigationDirection,
settings::TableViewSettings,
table_data_engine::{DisplayToDataMapping, TableDataEngine},
- types::{AnyColumn, TableLikeContent},
+ types::{AnyColumn, DataCellId, DisplayRow, TableLikeContent},
};
+/// The keyboard cursor: which cell is currently focused for navigation.
+/// Both fields are stored in data-space so the selection survives sort/filter changes.
+/// In single-cell navigation, `anchor == focus`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct CellSelection {
+ pub anchor: DataCellId,
+ pub focus: DataCellId,
+}
+
+impl CellSelection {
+ pub fn new(anchor: DataCellId, focus: DataCellId) -> Self {
+ Self { anchor, focus }
+ }
+
+ pub fn single_cell(cell: DataCellId) -> Self {
+ Self {
+ anchor: cell,
+ focus: cell,
+ }
+ }
+
+ pub fn is_single_cell(&self) -> bool {
+ self.anchor == self.focus
+ }
+}
+
#[derive(Debug, Default)]
pub struct PerformanceMetrics {
/// Map of timing metrics with their duration and measurement time.
@@ -76,7 +105,7 @@ pub struct TableView {
pub(crate) settings: TableViewSettings,
/// Performance metrics for debugging and monitoring grid operations.
pub(crate) performance_metrics: PerformanceMetrics,
- pub(crate) list_state: gpui::ListState,
+ pub(crate) list_state: 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.
@@ -84,6 +113,8 @@ pub struct TableView {
/// 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,
+ /// The keyboard navigation cursor. `None` until the user first navigates.
+ pub(crate) selection: Option<CellSelection>,
}
impl TableView {
@@ -111,9 +142,10 @@ impl TableView {
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),
+ .with_uniform_item_height(row_height + px(1.0)),
row_height,
is_loading: false,
+ selection: None,
}
}
@@ -125,7 +157,7 @@ impl TableView {
// 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);
+ .reset_with_uniform_height(0, self.row_height + px(1.0));
self.sync_column_widths(cx);
self.is_loading = false;
self.apply_filter_sort(cx);
@@ -199,12 +231,130 @@ impl TableView {
// 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);
+ .reset_with_uniform_height(visible_rows, view.row_height + px(1.0));
cx.notify();
})
.ok();
}));
}
+
+ #[inline]
+ pub(crate) fn is_selection_enabled(&self) -> bool {
+ cfg!(any(test, debug_assertions))
+ }
+
+ pub(crate) fn move_focused_cell(
+ &mut self,
+ action: &MoveFocusedCell,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if !self.is_selection_enabled() {
+ return;
+ }
+
+ let row_count = self.engine.d2d_mapping().visible_row_count();
+ let column_count = self.engine.contents.number_of_cols;
+
+ if row_count == 0 || column_count == 0 {
+ return;
+ }
+
+ let current_pos = self.selection.as_ref().and_then(|selection| {
+ self.engine
+ .d2d_mapping()
+ .get_display_row(selection.focus.row)
+ .map(|r| (r.0, selection.focus.col.0))
+ });
+
+ let (new_row, new_column) = match current_pos {
+ Some(pos) => self.compute_move(pos, action.direction),
+ None => (0, 0),
+ };
+
+ let Some(new_data_row) = self.engine.d2d_mapping().get_data_row(DisplayRow(new_row)) else {
+ return;
+ };
+ let new_cell = DataCellId::new(new_data_row, AnyColumn(new_column));
+ self.selection = Some(CellSelection::single_cell(new_cell));
+
+ self.scroll_to_reveal_row(new_row, action.direction);
+ self.scroll_to_reveal_column(new_column, window, cx);
+ cx.notify();
+ }
+
+ pub(crate) fn scroll_to_reveal_row(&self, row: usize, direction: NavigationDirection) {
+ let row_count = self.engine.d2d_mapping().visible_row_count();
+ if row_count == 0 {
+ return;
+ }
+
+ match direction {
+ NavigationDirection::Down => {
+ // When moving down, reveal row + 1 (if not already at the end) so that the focused
+ // cell isn't obscured by the bottom border or horizontal scrollbar overlay.
+ let reveal_row = (row + 1).min(row_count.saturating_sub(1));
+ self.list_state.scroll_to_reveal_item(reveal_row);
+ }
+ NavigationDirection::Up => {
+ // When moving up, reveal row - 1 (if not at top) for top peek cushion.
+ let reveal_row = row.saturating_sub(1);
+ self.list_state.scroll_to_reveal_item(reveal_row);
+ }
+ NavigationDirection::Left | NavigationDirection::Right => {
+ self.list_state.scroll_to_reveal_item(row);
+ }
+ }
+ }
+
+ pub(crate) fn compute_move(
+ &self,
+ current: (usize, usize),
+ direction: NavigationDirection,
+ ) -> (usize, usize) {
+ let row_count = self.engine.d2d_mapping().visible_row_count();
+ let column_count = self.engine.contents.number_of_cols;
+ let (row, column) = current;
+
+ match direction {
+ NavigationDirection::Up => (row.saturating_sub(1), column),
+ NavigationDirection::Down => ((row + 1).min(row_count.saturating_sub(1)), column),
+ NavigationDirection::Left => (row, column.saturating_sub(1)),
+ NavigationDirection::Right => (row, (column + 1).min(column_count.saturating_sub(1))),
+ }
+ }
+
+ pub(crate) fn scroll_to_reveal_column(&self, column_index: usize, window: &Window, cx: &App) {
+ let handle = self
+ .table_interaction_state
+ .read(cx)
+ .horizontal_scroll_handle
+ .clone();
+
+ let widths_state = self.column_widths.read(cx);
+ let total_cols = widths_state.cols();
+ if total_cols <= 1 || column_index + 2 > total_cols {
+ return;
+ }
+
+ let rem_size = window.rem_size();
+ let peek_padding = px(20.0);
+
+ let left_px = widths_state.pinned_width(column_index + 1, rem_size)
+ - widths_state.pinned_width(1, rem_size);
+ let right_px = widths_state.pinned_width(column_index + 2, rem_size)
+ - widths_state.pinned_width(1, rem_size);
+
+ let scroll_x = -handle.offset().x;
+ let viewport_width = handle.bounds().size.width;
+
+ if left_px < scroll_x {
+ handle.set_offset(Point::new(-left_px, px(0.)));
+ } else if right_px + peek_padding > scroll_x + viewport_width {
+ let target = (right_px + peek_padding) - viewport_width;
+ handle.set_offset(Point::new(-target, px(0.)));
+ }
+ }
}
impl Focusable for TableView {
@@ -212,3 +362,114 @@ impl Focusable for TableView {
self.focus_handle.clone()
}
}
+
+#[cfg(test)]
+mod tests {
+ use gpui::{Action, TestAppContext, VisualTestContext};
+
+ use super::*;
+ use crate::types::{DataRow, TableCell, TableLikeContent};
+ use ui::table_row::TableRow;
+
+ fn setup_test_view(
+ cx: &mut TestAppContext,
+ rows: usize,
+ cols: usize,
+ ) -> (Entity<TableView>, &mut VisualTestContext) {
+ cx.update(|cx| {
+ workspace::AppState::test(cx);
+ editor::init(cx);
+ });
+
+ cx.add_window_view(|window, cx| {
+ let mut view = TableView::new(window, cx);
+ let mut contents = TableLikeContent::default();
+ contents.number_of_cols = cols;
+ contents.headers = TableRow::from_vec(
+ (0..cols)
+ .map(|i| TableCell::Generated(format!("col_{i}").into()))
+ .collect(),
+ cols,
+ );
+ for _ in 0..rows {
+ let cells: Vec<TableCell> = (0..cols)
+ .map(|_| TableCell::Generated("val".into()))
+ .collect();
+ contents.rows.push(TableRow::from_vec(cells, cols));
+ }
+ view.set_contents(contents, cx);
+ view.engine.set_d2d_mapping(DisplayToDataMapping::compute(
+ &view.engine.contents,
+ &view.engine.filter_stack,
+ view.engine.applied_sorting,
+ ));
+ view
+ })
+ }
+
+ fn dispatch<A: Action>(view: &Entity<TableView>, action: &A, cx: &mut VisualTestContext) {
+ cx.update(|window, cx| {
+ let focus_handle = view.read(cx).focus_handle(cx);
+ focus_handle.focus(window, cx);
+ focus_handle.dispatch_action(action, window, cx);
+ });
+ }
+
+ fn selection_cells(
+ view: &Entity<TableView>,
+ cx: &VisualTestContext,
+ ) -> Option<(DataCellId, DataCellId)> {
+ view.read_with(cx, |this, _| {
+ let selection = this.selection.as_ref()?;
+ Some((selection.anchor, selection.focus))
+ })
+ }
+
+ #[gpui::test]
+ fn test_compute_move_directions(cx: &mut TestAppContext) {
+ let (view, cx) = setup_test_view(cx, 10, 5);
+
+ use NavigationDirection as Nav;
+ view.read_with(cx, |this, _| {
+ assert_eq!(this.compute_move((0, 0), Nav::Down), (1, 0));
+ assert_eq!(this.compute_move((0, 0), Nav::Right), (0, 1));
+ assert_eq!(this.compute_move((0, 0), Nav::Up), (0, 0));
+ assert_eq!(this.compute_move((0, 0), Nav::Left), (0, 0));
+ assert_eq!(this.compute_move((9, 4), Nav::Down), (9, 4));
+ assert_eq!(this.compute_move((9, 4), Nav::Right), (9, 4));
+ });
+ }
+
+ #[gpui::test]
+ fn test_move_focused_cell_action(cx: &mut TestAppContext) {
+ let (view, cx) = setup_test_view(cx, 10, 5);
+ let cell = |row, column| DataCellId::new(DataRow(row), AnyColumn(column));
+
+ // 1. First move initializes focus at (0, 0)
+ dispatch(
+ &view,
+ &MoveFocusedCell {
+ direction: NavigationDirection::Down,
+ },
+ cx,
+ );
+ assert_eq!(selection_cells(&view, cx), Some((cell(0, 0), cell(0, 0))));
+
+ // 2. Step Down and Right -> single cell focus at (1, 1)
+ dispatch(
+ &view,
+ &MoveFocusedCell {
+ direction: NavigationDirection::Down,
+ },
+ cx,
+ );
+ dispatch(
+ &view,
+ &MoveFocusedCell {
+ direction: NavigationDirection::Right,
+ },
+ cx,
+ );
+ assert_eq!(selection_cells(&view, cx), Some((cell(1, 1), cell(1, 1))));
+ }
+}
diff --git a/crates/tabular_data_preview/src/tabular_data_preview.rs b/crates/tabular_data_preview/src/tabular_data_preview.rs
index be05244dfea..b431f2dcd77 100644
--- a/crates/tabular_data_preview/src/tabular_data_preview.rs
+++ b/crates/tabular_data_preview/src/tabular_data_preview.rs
@@ -1,12 +1,14 @@
use editor::{Editor, EditorEvent};
-use gpui::{AppContext, Entity, EventEmitter, FocusHandle, Focusable, Task, actions};
+use gpui::{Action, AppContext, Entity, EventEmitter, FocusHandle, Focusable, Task, actions};
+use schemars::JsonSchema;
+use serde::Deserialize;
use ui::{SharedString, prelude::*};
use workspace::{Item, Pane, Workspace};
use crate::parser::EditorState;
-pub use crate::table_view::{PerformanceMetrics, TableView};
+pub use crate::table_view::{CellSelection, PerformanceMetrics, TableView};
mod parser;
mod renderer;
@@ -17,6 +19,22 @@ pub mod types;
actions!(tabular_data, [OpenPreview, OpenPreviewToTheSide]);
+#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum NavigationDirection {
+ #[default]
+ Up,
+ Down,
+ Left,
+ Right,
+}
+
+#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
+#[action(namespace = tabular_data)]
+pub struct MoveFocusedCell {
+ pub direction: NavigationDirection,
+}
+
/// 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 {
diff --git a/crates/tabular_data_preview/src/types/coordinates.rs b/crates/tabular_data_preview/src/types/coordinates.rs
index b1a5b55799a..bc33c3a6a8e 100644
--- a/crates/tabular_data_preview/src/types/coordinates.rs
+++ b/crates/tabular_data_preview/src/types/coordinates.rs
@@ -104,6 +104,23 @@ impl From<AnyColumn> for usize {
}
///// Cells /////
+/// Original data-space cell position. Survives sort/filter changes because it refers to the
+/// source data row, not the visual row index.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct DataCellId {
+ pub row: DataRow,
+ pub col: AnyColumn,
+}
+
+impl DataCellId {
+ pub fn new(row: impl Into<DataRow>, col: impl Into<AnyColumn>) -> Self {
+ Self {
+ row: row.into(),
+ col: col.into(),
+ }
+ }
+}
+
/// Visual cell position in rendered table.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DisplayCellId {