fix(database): select the matching cell when navigating into a CSV file shown as Data (#8067)

Find in Files, Go to Line and other navigation into a CSV file on its Data tab moved the caret in the hidden Text editor only. The table now maps the revealed offset to its record and field the way the CSV parser reads the file (quotes, CRLF, blank lines, header row), scrolls to that cell wherever local sorting put it, selects it and takes the focus; a row hidden by a filter is left alone.

Fixes #8043
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-04 23:11:43 +08:00
1 джерело 551328c901
коміт 4a41b14992
7 files changed
+142 -3

No files matched your search

+13 -2
Переглянути файл
@@ -8,8 +8,8 @@ import clsx from "clsx";
import { editorsFor } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { Checkbox, Tabs, T } from "@/ui";
import type { CsvTable } from "./csv";
import { useCsvModes, useCsvVersions, type CsvMode } from "./csvModes";
import { csvCellAt, type CsvTable } from "./csv";
import { useCsvModes, useCsvReveals, useCsvVersions, type CsvMode } from "./csvModes";
import { DataView, type DataPanel } from "./DataView";
import styles from "./Database.module.css";
@@ -22,6 +22,16 @@ function CsvData({ path }: { path: string }) {
const [failed, setFailed] = useState(false);
const [panel, setPanel] = useState<DataPanel | null>(null);
const [searchOpen, setSearchOpen] = useState(false);
// A navigation into the text while the table is shown (Find in Files, Go to Line) selects its cell.
const reveal = useCsvReveals((s) => s[path]);
const [shownFrom] = useState(() => useCsvReveals.getState()[path]?.seq ?? 0);
const revealCell = useMemo(() => {
if (!table || !reveal || reveal.seq <= shownFrom) return null;
const text = editorsFor(path)[0]?.view.state.doc.toString();
const cell = text == null ? null : csvCellAt(text, table.delimiter, reveal.offset);
const row = cell ? cell.record - (table.header ? 1 : 0) : -1;
return cell && row >= 0 && cell.col < table.columns.length ? { row, col: cell.col } : null;
}, [table, reveal, path, shownFrom]);
useEffect(() => {
const text = editorsFor(path)[0]?.view.state.doc.toString();
@@ -67,6 +77,7 @@ function CsvData({ path }: { path: string }) {
onPanelChange={setPanel}
searchOpen={searchOpen}
onSearchOpenChange={setSearchOpen}
revealCell={revealCell}
aria-label={tx("Table view of the file")}
/>
</div>
+11
Переглянути файл
@@ -208,6 +208,8 @@ export interface DataViewProps extends Pick<
searchOpen?: boolean;
onSearchOpenChange?: (open: boolean) => void;
revealColumn?: GridProps["revealColumn"];
/** A new object selects that cell of the loaded rows, wherever sorting put it; nothing when a filter hides it. */
revealCell?: { row: number; col: number } | null;
"aria-label"?: string;
}
@@ -261,6 +263,14 @@ export function DataView(props: DataViewProps) {
return base.filter((r) => rowMatches(r, columns.length, value, test));
}, [shaped, test, search.filterRows, rowCount, columns.length, value]);
const at = (r: number) => (order ? order[r]! : r);
const { revealCell } = props;
const gridReveal = useMemo(() => {
if (!revealCell) return null;
const row = order ? order.indexOf(revealCell.row) : revealCell.row;
return row < 0 ? null : { row, col: revealCell.col };
// A new request only, not a reshaped table.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [revealCell]);
const shown = order ? order.length : rowCount;
const extractor = props.extractor;
const copySelectedCells =
@@ -324,6 +334,7 @@ export function DataView(props: DataViewProps) {
currentMatch={currentMatch}
onFind={onSearchOpenChange && openSearch}
revealColumn={props.revealColumn}
revealCell={gridReveal}
aria-label={props["aria-label"]}
columns={columns}
rowCount={shown}
+36
Переглянути файл
@@ -1239,3 +1239,39 @@ describe("the data view's context menu (DataGrip)", () => {
expect(writeText).toHaveBeenCalledExactlyOnceWith("WHERE city = 'Beijing'");
});
});
describe("revealing a cell", () => {
it("selects the cell a navigation asks for, each request once", () => {
const rows = [
["Alice", "London"],
["Bob", "Tokyo"],
["Charlie", "Paris"],
];
const props = {
columns: [
{ name: "name", type: "" },
{ name: "city", type: "" },
],
rowCount: rows.length,
value: (r: number, c: number) => rows[r]![c]!,
panel: null,
onPanelChange: () => {},
};
const selected = () =>
screen
.getAllByRole("gridcell")
.filter((c) => c.getAttribute("aria-selected") === "true")
.map((c) => c.textContent);
const { rerender } = render(<DataView {...props} revealCell={null} />);
expect(selected()).toEqual([]);
rerender(<DataView {...props} revealCell={{ row: 1, col: 1 }} />);
expect(selected()).toEqual(["Tokyo"]);
fireEvent.mouseDown(
screen.getAllByRole("gridcell").find((c) => c.textContent === "Alice")!,
{ button: 0 },
);
expect(selected()).toEqual(["Alice"]);
rerender(<DataView {...props} revealCell={{ row: 2, col: 1 }} />);
expect(selected()).toEqual(["Paris"]);
});
});
+20
Переглянути файл
@@ -109,6 +109,8 @@ export interface GridProps {
onFind?: () => void;
/** Go to Column: a new object selects that column's cell in the current row, scrolls to it and focuses the grid. */
revealColumn?: { col: number } | null;
/** A new object selects that cell, scrolls to it and focuses the grid (a navigation into the text behind it). */
revealCell?: { row: number; col: number } | null;
/** Horizontal scroll offset to restore on mount, when a caller keeps view state across mounts. */
initialScrollLeft?: number;
/** Reports horizontal scroll changes to a caller that keeps view state across mounts. */
@@ -298,6 +300,24 @@ export function Grid(props: GridProps) {
// Runs once per request.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [revealColumn]);
const { revealCell } = props;
// Focused once the cell is selected: focusing with no selection yet selects the first cell.
const focusRevealed = useRef(false);
useEffect(() => {
if (!revealCell || revealCell.row >= rowCount) return;
const { row, col } = revealCell;
setSel({ r0: row, c0: col, r1: row, c1: col });
focusRevealed.current = true;
virtualizer.scrollToIndex(row, { align: "center" });
scrollColumnIntoView(col);
// Runs once per request.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [revealCell]);
useEffect(() => {
if (!focusRevealed.current || !sel) return;
focusRevealed.current = false;
scrollRef.current?.focus({ preventScroll: true });
}, [sel]);
const totalWidth = useMemo(() => numberWidth + widths.reduce((a, b) => a + b, 0), [numberWidth, widths]);
const template = `${numberWidth}px ${widths.map((w) => `${w}px`).join(" ")}`;
// Retried as columns are measured, until the content is wide enough to reach the offset.
+23 -1
Переглянути файл
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { detectDelimiter, looksLikeHeader, parseCsv } from "./csv";
import { csvCellAt, detectDelimiter, looksLikeHeader, parseCsv } from "./csv";
const BOM = String.fromCharCode(0xfeff);
@@ -56,3 +56,25 @@ describe("csv", () => {
expect([forced.header, forced.rows.length]).toEqual([false, 2]);
});
});
describe("csvCellAt", () => {
const text = 'name,age,city\nAlice,20,London\n\nBob,25,"Tokyo, ""JP"""\r\nCharlie,30,"Paris\nFR"\n';
const at = (needle: string) => csvCellAt(text, ",", text.indexOf(needle));
it("finds the record and field of an offset as parseCsv reads them", () => {
const { rows } = parseCsv(text, "x.csv");
expect(at("city")).toEqual({ record: 0, col: 2 });
expect(at("London")).toEqual({ record: 1, col: 2 });
// The blank line is skipped; quoted delimiters, doubled quotes and CRLF stay inside one field.
expect(at("Bob")).toEqual({ record: 2, col: 0 });
expect(at("JP")).toEqual({ record: 2, col: 2 });
expect(rows[1]![2]).toBe('Tokyo, "JP"');
// A line break inside quotes doesn't end the record.
expect(at("FR")).toEqual({ record: 3, col: 2 });
expect(rows[2]![2]).toBe("Paris\nFR");
});
it("is null on a blank line", () => {
expect(csvCellAt(text, ",", text.indexOf("\n\n") + 1)).toBeNull();
});
});
+33
Переглянути файл
@@ -65,3 +65,36 @@ export function parseCsv(text: string, path: string, header?: boolean): CsvTable
for (const r of rows) while (r.length < width) r.push("");
return { delimiter, header: named, columns, rows };
}
/**
* The record and field the text offset `at` falls in, counted the way `parseCsv` reads the file
* (blank lines skipped, the header row included); null on a blank line.
*/
export function csvCellAt(text: string, delimiter: string, at: number): { record: number; col: number } | null {
let record = 0;
let col = 0;
let length = 0;
let quoted = false;
let i = text.charCodeAt(0) === 0xfeff ? 1 : 0;
for (; i < text.length && i < at; i++) {
const ch = text[i]!;
if (quoted) {
if (ch !== '"') length++;
else if (text[i + 1] === '"') {
length++;
i++;
} else quoted = false;
} else if (ch === '"' && length === 0) quoted = true;
else if (ch === delimiter) {
col++;
length = 0;
} else if (ch === "\n" || ch === "\r") {
if (ch === "\r" && text[i + 1] === "\n") i++;
if (col > 0 || length > 0) record++;
col = 0;
length = 0;
} else length++;
}
const blank = !quoted && col === 0 && length === 0 && (at >= text.length || text[at] === "\n" || text[at] === "\r");
return blank ? null : { record, col };
}
+6
Переглянути файл
@@ -9,6 +9,10 @@ export type CsvMode = "text" | "data";
export const useCsvModes = create<Record<string, CsvMode | undefined>>(() => ({}));
export const useCsvSourceHidden = (tabId: string) => useCsvModes((s) => s[tabId] === "data");
/** The last caret a navigation placed in each CSV file's text (Find in Files, Go to Line…). */
export const useCsvReveals = create<Record<string, { offset: number; seq: number } | undefined>>(() => ({}));
let revealSeq = 0;
/** Bumped when a CSV file's text changes. */
export const useCsvVersions = create<Record<string, number | undefined>>(() => ({}));
const bump = (path: string) => useCsvVersions.setState((s) => ({ [path]: (s[path] ?? 0) + 1 }));
@@ -27,6 +31,8 @@ export function registerCsvLiveSource(): () => void {
bump(ctx.path);
}
update(u: ViewUpdate) {
if (u.transactions.some((tr) => tr.isUserEvent("select.reveal")))
useCsvReveals.setState({ [ctx.path]: { offset: u.state.selection.main.head, seq: ++revealSeq } });
if (!u.docChanged) return;
clearTimeout(this.timer);
this.timer = setTimeout(() => bump(ctx.path), TEXT_DELAY);