From 3a40014e292dfcef4891cec4a96e02c3ae2c855e Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Sat, 2 May 2026 11:17:52 -0700 Subject: [PATCH] feat(editor): add CSV/TSV table viewer (#1361) Adds a virtualized read-only table view for .csv/.tsv files, reusing the markdown view-mode toggle (source/rich) with a Table icon override. Hand-rolled RFC 4180 parser handles BOM, quoted fields, CRLF, and preserves trailing quoted empty fields. Co-authored-by: Orca --- .../src/components/editor/CsvViewer.tsx | 186 ++++++++++++++++++ .../src/components/editor/EditorContent.tsx | 13 ++ .../src/components/editor/EditorPanel.tsx | 5 +- .../components/editor/MarkdownViewToggle.tsx | 24 ++- .../src/components/editor/csv-parse.test.ts | 86 ++++++++ .../src/components/editor/csv-parse.ts | 128 ++++++++++++ .../editor/markdown-preview-controls.ts | 5 + src/renderer/src/lib/language-detect.ts | 4 +- 8 files changed, 444 insertions(+), 7 deletions(-) create mode 100644 src/renderer/src/components/editor/CsvViewer.tsx create mode 100644 src/renderer/src/components/editor/csv-parse.test.ts create mode 100644 src/renderer/src/components/editor/csv-parse.ts diff --git a/src/renderer/src/components/editor/CsvViewer.tsx b/src/renderer/src/components/editor/CsvViewer.tsx new file mode 100644 index 000000000..deccaf47f --- /dev/null +++ b/src/renderer/src/components/editor/CsvViewer.tsx @@ -0,0 +1,186 @@ +import React, { useMemo, useRef } from 'react' +import { useVirtualizer } from '@tanstack/react-virtual' +import { detectCsvDelimiter, parseCsv } from './csv-parse' + +type CsvViewerProps = { + content: string + filePath: string +} + +const ROW_HEIGHT = 28 +const OVERSCAN = 12 +const MIN_COL_PX = 80 +const MAX_COL_PX = 320 +const ROW_NUMBER_COL_PX = 48 +const CHAR_PX = 7 + +// Why: CsvViewer is the table counterpart to source-mode Monaco for .csv/.tsv +// files. Row virtualization via @tanstack/react-virtual keeps large files +// (100k+ rows) responsive. We use CSS grid with a shared grid-template-columns +// rather than a , because absolutely-positioned virtualized rows break +// a table's column-width synchronization — the header would size itself +// independently of the body, leaving values squashed together. +export default function CsvViewer({ content, filePath }: CsvViewerProps): React.JSX.Element { + const scrollRef = useRef(null) + + const parsed = useMemo(() => { + const delimiter = detectCsvDelimiter(filePath, content) + return parseCsv(content, delimiter) + }, [content, filePath]) + + // Why: memoize header/body split so their references stay stable across + // renders that don't change content. A top-level rest-destructure would + // slice the full rows array (100k+ on large files) on every render and + // produce a new `bodyRows` reference, invalidating the downstream + // `columnWidths`/`gridTemplate` memos below. + const { headerRow, bodyRows } = useMemo(() => { + if (parsed.rows.length === 0) { + return { headerRow: [] as string[], bodyRows: [] as string[][] } + } + const [head, ...rest] = parsed.rows + return { headerRow: head ?? [], bodyRows: rest } + }, [parsed]) + const columnCount = parsed.maxColumns + const header = useMemo(() => { + const out = [...(headerRow ?? [])] + while (out.length < columnCount) { + out.push('') + } + return out + }, [headerRow, columnCount]) + + // Why: size each column to its widest-seen value (sampled) so headers and + // body cells stay aligned. We cap sampling to the first 200 rows to avoid + // scanning huge files; uncommon long values clip with ellipsis rather than + // blowing out the viewport width. + const columnWidths = useMemo(() => { + const widths = Array.from({ length: columnCount }).fill(MIN_COL_PX) + const consider = (cell: string | undefined, idx: number): void => { + if (!cell) { + return + } + const w = Math.min(MAX_COL_PX, Math.max(MIN_COL_PX, cell.length * CHAR_PX + 24)) + if (w > widths[idx]!) { + widths[idx] = w + } + } + header.forEach(consider) + const sampleLimit = Math.min(bodyRows.length, 200) + for (let i = 0; i < sampleLimit; i += 1) { + const row = bodyRows[i]! + for (let c = 0; c < columnCount; c += 1) { + consider(row[c], c) + } + } + return widths + }, [header, bodyRows, columnCount]) + + const gridTemplate = useMemo( + () => `${ROW_NUMBER_COL_PX}px ${columnWidths.map((w) => `${w}px`).join(' ')}`, + [columnWidths] + ) + + const virtualizer = useVirtualizer({ + count: bodyRows.length, + getScrollElement: () => scrollRef.current, + estimateSize: () => ROW_HEIGHT, + overscan: OVERSCAN, + getItemKey: (index) => index + }) + + if (parsed.rows.length === 0) { + return ( +
+ Empty file +
+ ) + } + + const virtualRows = virtualizer.getVirtualItems() + const totalHeight = virtualizer.getTotalSize() + + return ( +
+
+
+
+
+ # +
+ {header.map((cell, idx) => ( +
+ + {cell} + +
+ ))} +
+
+ {virtualRows.map((vr) => { + const row = bodyRows[vr.index] ?? [] + return ( +
+
+ {vr.index + 1} +
+ {Array.from({ length: columnCount }).map((_, colIdx) => ( +
+ {row[colIdx] ?? ''} +
+ ))} +
+ ) + })} +
+
+
+
+ {bodyRows.length.toLocaleString()} rows + {columnCount} columns +
+
+ ) +} diff --git a/src/renderer/src/components/editor/EditorContent.tsx b/src/renderer/src/components/editor/EditorContent.tsx index fd1f17d70..35f92f5c9 100644 --- a/src/renderer/src/components/editor/EditorContent.tsx +++ b/src/renderer/src/components/editor/EditorContent.tsx @@ -1,3 +1,7 @@ +/* eslint-disable max-lines -- Why: this component is the central dispatcher +that maps (language, viewMode, binary, conflict) onto the correct editor +surface. Splitting the branches across files would force the view-mode state +machine to live behind indirection that obscures the exhaustive conditionals. */ import React, { lazy } from 'react' import { detectLanguage } from '@/lib/language-detect' import { useAppStore } from '@/store' @@ -19,6 +23,7 @@ const MarkdownPreview = lazy(() => import('./MarkdownPreview')) const ImageViewer = lazy(() => import('./ImageViewer')) const ImageDiffViewer = lazy(() => import('./ImageDiffViewer')) const MermaidViewer = lazy(() => import('./MermaidViewer')) +const CsvViewer = lazy(() => import('./CsvViewer')) const richMarkdownSizeEncoder = new TextEncoder() // Why: encodeInto() with a pre-allocated buffer avoids creating a new @@ -42,6 +47,7 @@ export function EditorContent({ resolvedLanguage, isMarkdown, isMermaid, + isCsv, mdViewMode, sideBySide, pendingEditorReveal, @@ -58,6 +64,7 @@ export function EditorContent({ resolvedLanguage: string isMarkdown: boolean isMermaid: boolean + isCsv: boolean mdViewMode: MarkdownViewMode sideBySide: boolean pendingEditorReveal: { @@ -349,6 +356,12 @@ export function EditorContent({ content={editBuffers[activeFile.id] ?? fc.content} filePath={activeFile.filePath} /> + ) : isCsv && mdViewMode === 'rich' ? ( + ) : ( renderMonacoEditor(fc) )} diff --git a/src/renderer/src/components/editor/EditorPanel.tsx b/src/renderer/src/components/editor/EditorPanel.tsx index 51d479317..a7c733c8b 100644 --- a/src/renderer/src/components/editor/EditorPanel.tsx +++ b/src/renderer/src/components/editor/EditorPanel.tsx @@ -23,7 +23,7 @@ import { } from '@/components/ui/dropdown-menu' import { CLOSE_ALL_CONTEXT_MENUS_EVENT } from '../tab-bar/SortableTab' import type { MarkdownViewMode, OpenFile } from '@/store/slices/editor' -import MarkdownViewToggle from './MarkdownViewToggle' +import MarkdownViewToggle, { CSV_VIEW_MODE_METADATA } from './MarkdownViewToggle' import { EditorContent } from './EditorContent' import { scrollTopCache, cursorPositionCache, diffViewStateCache } from '@/lib/scroll-cache' import type { GitDiffResult } from '../../../../shared/types' @@ -828,6 +828,7 @@ function EditorPanelInner({ const isMarkdown = resolvedLanguage === 'markdown' const isMermaid = resolvedLanguage === 'mermaid' + const isCsv = resolvedLanguage === 'csv' || resolvedLanguage === 'tsv' // Why: "Open Preview to the Side" only applies to edit-mode tabs whose // language has a registered renderer. Diff tabs already have their own // toggle set and there is no clear semantic for previewing a diff. @@ -1042,6 +1043,7 @@ function EditorPanelInner({ mode={mdViewMode} modes={markdownViewModes} onChange={(mode) => setMarkdownViewMode(activeFile.id, mode)} + metadataOverride={isCsv ? CSV_VIEW_MODE_METADATA : undefined} /> )} {hasViewModeToggle && isMarkdown && ( @@ -1088,6 +1090,7 @@ function EditorPanelInner({ resolvedLanguage={resolvedLanguage} isMarkdown={isMarkdown} isMermaid={isMermaid} + isCsv={isCsv} mdViewMode={mdViewMode} sideBySide={sideBySide} pendingEditorReveal={pendingEditorReveal} diff --git a/src/renderer/src/components/editor/MarkdownViewToggle.tsx b/src/renderer/src/components/editor/MarkdownViewToggle.tsx index f9bdedaca..40fb610e5 100644 --- a/src/renderer/src/components/editor/MarkdownViewToggle.tsx +++ b/src/renderer/src/components/editor/MarkdownViewToggle.tsx @@ -1,9 +1,11 @@ import React from 'react' -import { Code, Eye, Pencil } from 'lucide-react' +import { Code, Eye, Pencil, Table as TableIcon, type LucideIcon } from 'lucide-react' import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' import type { MarkdownViewMode } from '@/store/slices/editor' -const VIEW_MODE_METADATA = { +type ViewModeMetadata = { label: string; icon: LucideIcon } + +const DEFAULT_VIEW_MODE_METADATA: Record = { source: { label: 'Source', icon: Code @@ -16,18 +18,30 @@ const VIEW_MODE_METADATA = { label: 'Preview', icon: Eye } -} as const +} + +// Why: CSV/TSV files reuse the 'rich' view mode slot but the rendered surface +// is a read-only table, not an editor. The Pencil icon implies editability, +// which we don't offer, so callers can override the per-mode presentation. +export const CSV_VIEW_MODE_METADATA: Partial> = { + rich: { + label: 'Table', + icon: TableIcon + } +} type MarkdownViewToggleProps = { mode: MarkdownViewMode modes: readonly MarkdownViewMode[] onChange: (mode: MarkdownViewMode) => void + metadataOverride?: Partial> } export default function MarkdownViewToggle({ mode, modes, - onChange + onChange, + metadataOverride }: MarkdownViewToggleProps): React.JSX.Element { return ( {modes.map((viewMode) => { - const metadata = VIEW_MODE_METADATA[viewMode] + const metadata = metadataOverride?.[viewMode] ?? DEFAULT_VIEW_MODE_METADATA[viewMode] const Icon = metadata.icon return ( { + it('parses basic rows', () => { + const { rows, maxColumns } = parseCsv('a,b,c\n1,2,3\n') + expect(rows).toEqual([ + ['a', 'b', 'c'], + ['1', '2', '3'] + ]) + expect(maxColumns).toBe(3) + }) + + it('handles quoted fields with delimiters and escaped quotes', () => { + const { rows } = parseCsv('name,note\n"Doe, Jane","she said ""hi"""\n') + expect(rows).toEqual([ + ['name', 'note'], + ['Doe, Jane', 'she said "hi"'] + ]) + }) + + it('handles CRLF and embedded newlines inside quotes', () => { + const { rows } = parseCsv('a,b\r\n"x\ny",z\r\n') + expect(rows).toEqual([ + ['a', 'b'], + ['x\ny', 'z'] + ]) + }) + + it('tracks the widest row for ragged data', () => { + const { rows, maxColumns } = parseCsv('a,b\n1,2,3\n') + expect(rows).toEqual([ + ['a', 'b'], + ['1', '2', '3'] + ]) + expect(maxColumns).toBe(3) + }) + + it('preserves a final row without trailing newline', () => { + const { rows } = parseCsv('a,b\n1,2') + expect(rows).toEqual([ + ['a', 'b'], + ['1', '2'] + ]) + }) + + it('parses TSV when delimiter is tab', () => { + const { rows } = parseCsv('a\tb\n1\t2\n', '\t') + expect(rows).toEqual([ + ['a', 'b'], + ['1', '2'] + ]) + }) + + it('strips a leading UTF-8 BOM from the first header cell', () => { + const { rows } = parseCsv('\uFEFFa,b,c\n1,2,3\n') + expect(rows).toEqual([ + ['a', 'b', 'c'], + ['1', '2', '3'] + ]) + }) + + it('preserves a single quoted empty field at EOF', () => { + const { rows } = parseCsv('""') + expect(rows).toEqual([['']]) + }) +}) + +describe('detectCsvDelimiter', () => { + it('uses tab for .tsv files regardless of content', () => { + expect(detectCsvDelimiter('data.tsv', 'a,b,c')).toBe('\t') + }) + + it('sniffs tab vs comma from the first line', () => { + expect(detectCsvDelimiter('data.csv', 'a\tb\tc\n1\t2\t3')).toBe('\t') + expect(detectCsvDelimiter('data.csv', 'a,b,c\n1,2,3')).toBe(',') + }) + + it('skips leading blank lines when sniffing', () => { + expect(detectCsvDelimiter('x.csv', '\n\na\tb\tc')).toBe('\t') + }) + + it('strips a leading BOM before sniffing', () => { + expect(detectCsvDelimiter('x.csv', '\uFEFFa\tb\tc')).toBe('\t') + }) +}) diff --git a/src/renderer/src/components/editor/csv-parse.ts b/src/renderer/src/components/editor/csv-parse.ts new file mode 100644 index 000000000..9af0332a0 --- /dev/null +++ b/src/renderer/src/components/editor/csv-parse.ts @@ -0,0 +1,128 @@ +export type CsvParseResult = { + rows: string[][] + maxColumns: number +} + +// Why: RFC 4180-compatible CSV parsing with quote handling and CRLF support. +// A hand-rolled parser avoids pulling a new dependency (papaparse) for what is +// a small, well-specified grammar. Inline state machine keeps the hot path +// allocation-light for large files. +export function parseCsv(source: string, delimiter: string = ','): CsvParseResult { + // Why: strip a leading UTF-8 BOM (U+FEFF). Excel and other spreadsheet tools + // prepend a BOM to exported CSVs; without this, the BOM contaminates the + // first header cell and breaks column-name lookups for downstream consumers. + if (source.charCodeAt(0) === 0xfeff) { + source = source.slice(1) + } + + const rows: string[][] = [] + let row: string[] = [] + let field = '' + let inQuotes = false + let maxColumns = 0 + // Why: track whether the current record has produced any content — including + // a quoted-but-empty field like `""`. Without this flag, the EOF flush + // condition `field.length > 0 || row.length > 0` would drop a record whose + // only field was a quoted empty string, since the field is empty and no + // delimiter/newline ever pushed it onto the row. + let recordHasContent = false + + const pushField = (): void => { + row.push(field) + field = '' + } + const pushRow = (): void => { + pushField() + if (row.length > maxColumns) { + maxColumns = row.length + } + rows.push(row) + row = [] + recordHasContent = false + } + + for (let i = 0; i < source.length; i += 1) { + const ch = source[i] + + if (inQuotes) { + if (ch === '"') { + if (source[i + 1] === '"') { + field += '"' + i += 1 + } else { + inQuotes = false + } + } else { + field += ch + } + continue + } + + if (ch === '"' && field === '') { + inQuotes = true + // Why: entering quote mode means this record has real content even if + // the quoted field ends up empty (e.g. the whole file is `""`). + recordHasContent = true + continue + } + if (ch === delimiter) { + pushField() + recordHasContent = true + continue + } + if (ch === '\r') { + if (source[i + 1] === '\n') { + i += 1 + } + pushRow() + continue + } + if (ch === '\n') { + pushRow() + continue + } + field += ch + recordHasContent = true + } + + // Why: don't emit a trailing empty row for files that end with a newline — + // that's just whitespace, not a record. But preserve an in-progress final + // row that lacks a newline. `recordHasContent` covers the edge case where + // the final record is a single quoted empty field (`""`) — the field is + // empty and nothing has been pushed to `row`, but the record is real and + // must not be dropped. + if (field.length > 0 || row.length > 0 || recordHasContent) { + pushRow() + } + + return { rows, maxColumns } +} + +export function detectCsvDelimiter(filePath: string, content: string): string { + if (filePath.toLowerCase().endsWith('.tsv')) { + return '\t' + } + // Why: sniff the first non-empty line for tab vs comma to handle CSVs that + // were saved with a different extension. Semicolons/pipes are out of scope; + // this tool is a viewer, not a general data importer. + // Why: strip a leading UTF-8 BOM so it doesn't get counted as part of the + // first cell's characters (and so BOM-prefixed TSVs still sniff correctly). + let text = content + if (text.charCodeAt(0) === 0xfeff) { + text = text.slice(1) + } + // Why: skip leading blank/whitespace-only lines before sniffing. A file that + // starts with one or more empty lines would otherwise be classified as comma + // (0 tabs vs 0 commas, tie goes to comma), misdetecting blank-leading TSVs. + const lines = text.split(/\r?\n/) + let firstLine = '' + for (const line of lines) { + if (line.trim().length > 0) { + firstLine = line + break + } + } + const tabs = (firstLine.match(/\t/g) ?? []).length + const commas = (firstLine.match(/,/g) ?? []).length + return tabs > commas ? '\t' : ',' +} diff --git a/src/renderer/src/components/editor/markdown-preview-controls.ts b/src/renderer/src/components/editor/markdown-preview-controls.ts index f0d57ac10..78ad2cff6 100644 --- a/src/renderer/src/components/editor/markdown-preview-controls.ts +++ b/src/renderer/src/components/editor/markdown-preview-controls.ts @@ -10,6 +10,7 @@ const MARKDOWN_DIFF_VIEW_MODES = [ 'preview' ] as const satisfies readonly MarkdownViewMode[] const MERMAID_VIEW_MODES = ['source', 'rich'] as const satisfies readonly MarkdownViewMode[] +const CSV_VIEW_MODES = ['source', 'rich'] as const satisfies readonly MarkdownViewMode[] const NO_VIEW_MODES = [] as const satisfies readonly MarkdownViewMode[] export function getMarkdownViewModes(target: MarkdownPreviewTarget): readonly MarkdownViewMode[] { @@ -30,6 +31,10 @@ export function getMarkdownViewModes(target: MarkdownPreviewTarget): readonly Ma return MERMAID_VIEW_MODES } + if ((target.language === 'csv' || target.language === 'tsv') && target.mode === 'edit') { + return CSV_VIEW_MODES + } + return NO_VIEW_MODES } diff --git a/src/renderer/src/lib/language-detect.ts b/src/renderer/src/lib/language-detect.ts index 1e4dd1c48..864cd9a7f 100644 --- a/src/renderer/src/lib/language-detect.ts +++ b/src/renderer/src/lib/language-detect.ts @@ -79,7 +79,9 @@ const EXT_TO_LANGUAGE: Record = { '.astro': 'html', '.tf': 'hcl', '.hcl': 'hcl', - '.prisma': 'graphql' + '.prisma': 'graphql', + '.csv': 'csv', + '.tsv': 'tsv' } const FILENAME_TO_LANGUAGE: Record = {