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 <help@stably.ai>
This commit is contained in:
Jinjing
2026-05-02 11:17:52 -07:00
committed by GitHub
co-authored by Orca
parent 7de1213c54
commit 3a40014e29
8 changed files with 444 additions and 7 deletions
@@ -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 <table>, 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<HTMLDivElement>(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<number>({ 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 (
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
Empty file
</div>
)
}
const virtualRows = virtualizer.getVirtualItems()
const totalHeight = virtualizer.getTotalSize()
return (
<div className="flex h-full min-h-0 flex-col">
<div
ref={scrollRef}
className="relative min-h-0 flex-1 overflow-auto scrollbar-editor font-mono text-xs"
>
<div
role="table"
aria-rowcount={parsed.rows.length}
aria-colcount={columnCount + 1}
className="inline-block min-w-full"
style={{ width: 'max-content' }}
>
<div
role="row"
aria-rowindex={1}
className="sticky top-0 z-10 grid bg-muted/90 backdrop-blur"
style={{ gridTemplateColumns: gridTemplate, height: ROW_HEIGHT }}
>
<div
role="columnheader"
className="sticky left-0 z-20 flex items-center justify-end border-b border-r border-border/60 bg-muted/90 px-2 text-[10px] font-normal text-muted-foreground"
>
#
</div>
{header.map((cell, idx) => (
<div
role="columnheader"
key={idx}
className="flex items-center overflow-hidden border-b border-r border-border/60 px-2 font-medium text-foreground"
>
<span className="truncate" title={cell}>
{cell}
</span>
</div>
))}
</div>
<div style={{ height: totalHeight, position: 'relative' }}>
{virtualRows.map((vr) => {
const row = bodyRows[vr.index] ?? []
return (
<div
role="row"
aria-rowindex={vr.index + 2}
key={vr.key}
data-index={vr.index}
className="group grid hover:bg-accent/40"
style={{
gridTemplateColumns: gridTemplate,
position: 'absolute',
top: 0,
left: 0,
height: ROW_HEIGHT,
transform: `translateY(${vr.start}px)`
}}
>
<div
role="rowheader"
className="sticky left-0 z-[5] flex items-center justify-end border-b border-r border-border/40 bg-background/95 px-2 text-[10px] text-muted-foreground group-hover:bg-accent/40"
>
{vr.index + 1}
</div>
{Array.from({ length: columnCount }).map((_, colIdx) => (
<div
role="cell"
key={colIdx}
className="flex items-center overflow-hidden border-b border-r border-border/40 px-2 text-foreground"
title={row[colIdx] ?? ''}
>
<span className="truncate">{row[colIdx] ?? ''}</span>
</div>
))}
</div>
)
})}
</div>
</div>
</div>
<div className="flex items-center gap-4 border-t border-border/60 px-3 py-1 text-xs text-muted-foreground">
<span>{bodyRows.length.toLocaleString()} rows</span>
<span>{columnCount} columns</span>
</div>
</div>
)
}
@@ -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' ? (
<CsvViewer
key={activeFile.id}
content={editBuffers[activeFile.id] ?? fc.content}
filePath={activeFile.filePath}
/>
) : (
renderMonacoEditor(fc)
)}
@@ -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}
@@ -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<MarkdownViewMode, ViewModeMetadata> = {
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<Record<MarkdownViewMode, ViewModeMetadata>> = {
rich: {
label: 'Table',
icon: TableIcon
}
}
type MarkdownViewToggleProps = {
mode: MarkdownViewMode
modes: readonly MarkdownViewMode[]
onChange: (mode: MarkdownViewMode) => void
metadataOverride?: Partial<Record<MarkdownViewMode, ViewModeMetadata>>
}
export default function MarkdownViewToggle({
mode,
modes,
onChange
onChange,
metadataOverride
}: MarkdownViewToggleProps): React.JSX.Element {
return (
<ToggleGroup
@@ -43,7 +57,7 @@ export default function MarkdownViewToggle({
}}
>
{modes.map((viewMode) => {
const metadata = VIEW_MODE_METADATA[viewMode]
const metadata = metadataOverride?.[viewMode] ?? DEFAULT_VIEW_MODE_METADATA[viewMode]
const Icon = metadata.icon
return (
<ToggleGroupItem
@@ -0,0 +1,86 @@
import { describe, expect, it } from 'vitest'
import { detectCsvDelimiter, parseCsv } from './csv-parse'
describe('parseCsv', () => {
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')
})
})
@@ -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' : ','
}
@@ -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
}
+3 -1
View File
@@ -79,7 +79,9 @@ const EXT_TO_LANGUAGE: Record<string, string> = {
'.astro': 'html',
'.tf': 'hcl',
'.hcl': 'hcl',
'.prisma': 'graphql'
'.prisma': 'graphql',
'.csv': 'csv',
'.tsv': 'tsv'
}
const FILENAME_TO_LANGUAGE: Record<string, string> = {