Skip to content

armgit / ui

Public Imported from GitHub
0
TypeScript

Add opt-in dynamic search to CSV viewer. (#12)

Ashish Viradiyad2b998e6b611
diff --git a/apps/v4/components/csv-viewer-docs.tsx b/apps/v4/components/csv-viewer-docs.tsx
index bbc0dda..8f616f8 100644
--- a/apps/v4/components/csv-viewer-docs.tsx
+++ b/apps/v4/components/csv-viewer-docs.tsx
@@ -3,7 +3,6 @@
import * as React from "react"
import dynamic from "next/dynamic"
-import { Button } from "@/components/ui/button"
import { Spinner } from "@/components/ui/spinner"
import {
DocsSourceCodeBlock,
@@ -39,7 +38,7 @@ const CsvViewer = dynamic(
)
export function CsvViewerPreviewClient() {
- return <CsvViewer data={SAMPLE_CSV} />
+ return <CsvViewer data={SAMPLE_CSV} search />
}
export function CsvViewerDemo() {
@@ -48,7 +47,7 @@ export function CsvViewerDemo() {
data-slot="component-preview"
className="group relative mt-4 mb-12 flex flex-col overflow-hidden rounded-xl border"
>
- <CsvViewer data={SAMPLE_CSV} />
+ <CsvViewer data={SAMPLE_CSV} search />
<DocsViewCodeBlock code={csvViewerUsageCode} />
</div>
)
@@ -63,11 +62,11 @@ INV-1001,Northstar Supply,Approved,4280.50
INV-1002,Bluebird Medical,Needs review,1190.00\`;
export function CsvViewerExample() {
- return <CsvViewer data={data} />;
+ return <CsvViewer data={data} search />;
}`
const csvViewerSourceCode =
- '"use client"\n\nimport * as React from "react"\nimport type * as GlideDataGrid from "@glideapps/glide-data-grid"\nimport type {\n GridCell,\n GridCellKind,\n GridColumn,\n Item,\n Theme,\n} from "@glideapps/glide-data-grid"\n\nimport "@glideapps/glide-data-grid/dist/index.css"\n\nimport {\n MinusSignCircleIcon,\n PlusSignCircleIcon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport Papa from "papaparse"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\n\nconst ZOOM_OPTIONS = [0.75, 1, 1.25, 1.5, 2] as const\n\ntype GlideDataGridModule = typeof GlideDataGrid\ntype CsvViewerProps = {\n className?: string\n data?: string\n}\n\nfunction toDisplayString(value: unknown): string {\n return value === null || value === undefined ? "" : String(value)\n}\n\nfunction normalizeHeaderTitle(header: string, index: number): string {\n const trimmed = header.trim()\n return trimmed.length > 0 ? trimmed : `Column ${index + 1}`\n}\n\nfunction parseDelimitedText(text: string): {\n headers: string[]\n rows: string[][]\n error: string | null\n} {\n const results = Papa.parse<Record<string, unknown>>(text, {\n header: true,\n skipEmptyLines: "greedy",\n })\n\n const objectRows = Array.isArray(results.data)\n ? results.data.filter(\n (row): row is Record<string, unknown> =>\n !!row && typeof row === "object" && !Array.isArray(row)\n )\n : []\n const metaFields = Array.isArray(results.meta.fields)\n ? results.meta.fields.map((field) => String(field))\n : []\n const fieldKeys =\n metaFields.length > 0\n ? metaFields\n : Object.keys(objectRows[0] ?? {}).filter(\n (key) => key !== "__parsed_extra"\n )\n const extraColumnCount = objectRows.reduce((maxCount, row) => {\n const extras = row.__parsed_extra\n return Array.isArray(extras) ? Math.max(maxCount, extras.length) : maxCount\n }, 0)\n const headers = [\n ...fieldKeys.map((field, index) => normalizeHeaderTitle(field, index)),\n ...Array.from(\n { length: extraColumnCount },\n (_, index) => `Extra ${index + 1}`\n ),\n ]\n\n const rows = objectRows.map((row) => {\n const baseValues = fieldKeys.map((fieldKey) =>\n toDisplayString(row[fieldKey])\n )\n const extras = Array.isArray(row.__parsed_extra)\n ? row.__parsed_extra.map((value) => toDisplayString(value))\n : []\n const paddedExtras =\n extras.length >= extraColumnCount\n ? extras.slice(0, extraColumnCount)\n : [\n ...extras,\n ...Array.from(\n { length: extraColumnCount - extras.length },\n () => ""\n ),\n ]\n\n return [...baseValues, ...paddedExtras]\n })\n\n const firstError =\n Array.isArray(results.errors) && results.errors.length > 0\n ? results.errors[0]\n : null\n\n return {\n headers,\n rows,\n error:\n rows.length === 0 && firstError\n ? String(firstError.message ?? "Could not parse CSV file.")\n : null,\n }\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction readIsDarkTheme() {\n return (\n typeof document !== "undefined" &&\n document.documentElement.classList.contains("dark")\n )\n}\n\nfunction useIsDarkTheme() {\n const [isDark, setIsDark] = React.useState(readIsDarkTheme)\n\n React.useEffect(() => {\n if (typeof document === "undefined") return\n\n const updateTheme = () => setIsDark(readIsDarkTheme())\n\n updateTheme()\n\n if (typeof MutationObserver === "undefined") return\n\n const observer = new MutationObserver(updateTheme)\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ["class"],\n })\n\n return () => observer.disconnect()\n }, [])\n\n return isDark\n}\n\nexport function CsvViewer({ className, data }: CsvViewerProps) {\n const inputRef = React.useRef<HTMLInputElement | null>(null)\n const isDark = useIsDarkTheme()\n const [glide, setGlide] = React.useState<GlideDataGridModule | null>(null)\n const [zoom, setZoom] = React.useState<(typeof ZOOM_OPTIONS)[number]>(1)\n const [parsed, setParsed] = React.useState(() =>\n data ? parseDelimitedText(data) : { headers: [], rows: [], error: null }\n )\n const [isPending, setIsPending] = React.useState(false)\n\n React.useEffect(() => {\n if (data) {\n setParsed(parseDelimitedText(data))\n }\n }, [data])\n\n React.useEffect(() => {\n let mounted = true\n\n void import("@glideapps/glide-data-grid").then((module) => {\n if (mounted) {\n setGlide(module)\n }\n })\n\n return () => {\n mounted = false\n }\n }, [])\n\n const columnCount = Math.max(1, parsed.headers.length)\n const scale = React.useCallback(\n (value: number) => Math.round(value * zoom),\n [zoom]\n )\n\n const theme = React.useMemo<Partial<Theme>>(\n () => ({\n accentColor: isDark ? "#60a5fa" : "#2563eb",\n accentLight: isDark ? "#1d4ed826" : "#dbeafe",\n accentFg: "#ffffff",\n textDark: isDark ? "#e5e5e5" : "#171717",\n textMedium: isDark ? "#a3a3a3" : "#525252",\n textLight: isDark ? "#737373" : "#a3a3a3",\n textBubble: isDark ? "#f5f5f5" : "#171717",\n textHeader: isDark ? "#f5f5f5" : "#171717",\n textGroupHeader: isDark ? "#a3a3a3" : "#525252",\n bgCell: isDark ? "#0a0a0a" : "#ffffff",\n bgCellMedium: isDark ? "#171717" : "#fafafa",\n bgHeader: isDark ? "#171717" : "#fafafa",\n bgHeaderHasFocus: isDark ? "#262626" : "#f5f5f5",\n bgHeaderHovered: isDark ? "#262626" : "#f5f5f5",\n borderColor: isDark ? "#262626" : "#e5e5e5",\n horizontalBorderColor: isDark ? "#262626" : "#e5e5e5",\n cellHorizontalPadding: scale(8),\n cellVerticalPadding: Math.max(2, scale(3)),\n headerIconSize: scale(18),\n baseFontStyle: `${scale(13)}px`,\n headerFontStyle: `600 ${scale(13)}px`,\n markerFontStyle: `${scale(11)}px`,\n fontFamily: \'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif\',\n editorFontSize: `${scale(13)}px`,\n }),\n [isDark, scale]\n )\n\n const columns = React.useMemo<GridColumn[]>(\n () =>\n Array.from({ length: columnCount }, (_, index) => ({\n id: `column-${index}`,\n title: parsed.headers[index] ?? `Column ${index + 1}`,\n width: scale(index === 0 ? 180 : 160),\n })),\n [columnCount, parsed.headers, scale]\n )\n\n const getCellContent = React.useCallback(\n ([col, row]: Item): GridCell => {\n const value = parsed.rows[row]?.[col] ?? ""\n const textKind = glide?.GridCellKind.Text as GridCellKind.Text\n\n return {\n kind: textKind,\n data: value,\n displayData: value,\n allowOverlay: true,\n readonly: true,\n }\n },\n [glide, parsed.rows]\n )\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n if (!file) return\n\n setIsPending(true)\n try {\n const text = await file.text()\n setParsed(parseDelimitedText(text))\n } catch (error) {\n setParsed({\n headers: [],\n rows: [],\n error:\n error instanceof Error ? error.message : "Could not read CSV file.",\n })\n } finally {\n event.target.value = ""\n setIsPending(false)\n }\n }\n\n function stepZoom(direction: -1 | 1) {\n const index = ZOOM_OPTIONS.indexOf(zoom)\n const nextIndex = Math.min(\n ZOOM_OPTIONS.length - 1,\n Math.max(0, index + direction)\n )\n setZoom(ZOOM_OPTIONS[nextIndex])\n }\n\n return (\n <div\n className={cn(\n "flex h-[560px] w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n <div className="flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2">\n <TooltipProvider>\n <div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom out"\n disabled={zoom <= ZOOM_OPTIONS[0]}\n onClick={() => stepZoom(-1)}\n >\n <HugeiconsIcon\n icon={MinusSignCircleIcon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={zoom.toString()}\n onValueChange={(value) =>\n setZoom(Number(value) as (typeof ZOOM_OPTIONS)[number])\n }\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoom * 100)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align="end" alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((option) => (\n <SelectItem key={option} value={option.toString()}>\n {Math.round(option * 100)}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom in"\n disabled={zoom >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]}\n onClick={() => stepZoom(1)}\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <input\n ref={inputRef}\n type="file"\n accept=".csv,.tsv,text/csv,text/tab-separated-values"\n className="hidden"\n onChange={handleUpload}\n />\n <ToolbarTooltip label="Upload CSV">\n <Button\n variant="ghost"\n size="icon-sm"\n aria-label="Upload CSV"\n loading={isPending}\n onClick={() => inputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n </TooltipProvider>\n </div>\n <div className="min-h-0 flex-1">\n {parsed.error ? (\n <div className="flex h-full items-center justify-center px-4 text-center text-sm text-destructive">\n {parsed.error}\n </div>\n ) : parsed.rows.length === 0 ? (\n <div className="grid h-full place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs">\n <p className="font-medium">Upload a CSV to preview</p>\n <p className="mt-1 text-muted-foreground">\n Pass delimited text with the <code>data</code> prop or upload a\n CSV file.\n </p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n loading={isPending}\n onClick={() => inputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload CSV\n </Button>\n </div>\n </div>\n ) : !glide ? (\n <div className="grid h-full place-items-center bg-background">\n <Spinner className="size-4" />\n </div>\n ) : (\n <glide.DataEditor\n key={zoom}\n columns={columns}\n rows={parsed.rows.length}\n getCellContent={getCellContent}\n rowMarkers="number"\n rowSelectionMode="multi"\n keybindings={{ search: true }}\n smoothScrollX\n smoothScrollY\n getCellsForSelection\n width="100%"\n height="100%"\n theme={theme}\n rowHeight={scale(34)}\n headerHeight={scale(36)}\n />\n )}\n </div>\n </div>\n )\n}\n'
+ "\"use client\"\n\nimport * as React from \"react\"\nimport type * as GlideDataGrid from \"@glideapps/glide-data-grid\"\nimport type {\n DataEditorRef,\n GridCell,\n GridCellKind,\n GridColumn,\n GridSelection,\n Item,\n Theme,\n} from \"@glideapps/glide-data-grid\"\nimport {\n CompactSelection,\n emptyGridSelection,\n} from \"@glideapps/glide-data-grid\"\n\nimport \"@glideapps/glide-data-grid/dist/index.css\"\n\nimport {\n ArrowLeft01Icon,\n ArrowRight01Icon,\n MinusSignCircleIcon,\n PlusSignCircleIcon,\n Search01Icon,\n Upload01Icon,\n} from \"@hugeicons/core-free-icons\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport Papa from \"papaparse\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport { Input } from \"@/components/ui/input\"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from \"@/components/ui/popover\"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from \"@/components/ui/select\"\nimport { Separator } from \"@/components/ui/separator\"\nimport { Spinner } from \"@/components/ui/spinner\"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from \"@/components/ui/tooltip\"\n\nconst ZOOM_OPTIONS = [0.75, 1, 1.25, 1.5, 2] as const\nconst CSV_SEARCH_BATCH_ROW_COUNT = 500\nconst CSV_SEARCH_DEBOUNCE_MS = 300\n\ntype GlideDataGridModule = typeof GlideDataGrid\ntype CsvViewerProps = {\n className?: string\n data?: string\n search?: boolean\n}\n\ntype CsvSearchResult = {\n col: number\n row: number\n displayValue: string\n columnTitle: string\n}\n\nfunction toDisplayString(value: unknown): string {\n return value === null || value === undefined ? \"\" : String(value)\n}\n\nfunction normalizeHeaderTitle(header: string, index: number): string {\n const trimmed = header.trim()\n return trimmed.length > 0 ? trimmed : `Column ${index + 1}`\n}\n\nfunction columnIndexToA1(col: number) {\n let columnNumber = col + 1\n let columnName = \"\"\n\n while (columnNumber > 0) {\n const remainder = (columnNumber - 1) % 26\n columnName = String.fromCharCode(65 + remainder) + columnName\n columnNumber = Math.floor((columnNumber - 1) / 26)\n }\n\n return columnName\n}\n\nfunction cellAddressToA1(col: number, row: number) {\n return `${columnIndexToA1(col)}${row + 1}`\n}\n\nfunction cellMatchesQuery(displayValue: string, query: string) {\n return displayValue.toLowerCase().includes(query)\n}\n\nfunction createSingleCellSelection(cell: Item): GridSelection {\n const [col, row] = cell\n\n return {\n columns: CompactSelection.empty(),\n rows: CompactSelection.empty(),\n current: {\n cell,\n range: { x: col, y: row, width: 1, height: 1 },\n rangeStack: [],\n },\n }\n}\n\nasync function findCsvSearchResults(\n headers: string[],\n rows: string[][],\n rawQuery: string\n) {\n const query = rawQuery.trim().toLowerCase()\n if (!query) return []\n\n const results: CsvSearchResult[] = []\n const columnCount = Math.max(\n headers.length,\n rows.reduce((maxCount, row) => Math.max(maxCount, row.length), 0)\n )\n\n for (\n let batchStartRow = 0;\n batchStartRow < rows.length;\n batchStartRow += CSV_SEARCH_BATCH_ROW_COUNT\n ) {\n const batchEndRow = Math.min(\n batchStartRow + CSV_SEARCH_BATCH_ROW_COUNT,\n rows.length\n )\n\n for (let row = batchStartRow; row < batchEndRow; row += 1) {\n const rowValues = rows[row] ?? []\n\n for (let col = 0; col < columnCount; col += 1) {\n const displayValue = rowValues[col] ?? \"\"\n if (!cellMatchesQuery(displayValue, query)) continue\n\n results.push({\n col,\n row,\n displayValue,\n columnTitle: headers[col] ?? `Column ${col + 1}`,\n })\n }\n }\n\n if (batchEndRow < rows.length) {\n await new Promise<void>((resolve) => {\n window.setTimeout(resolve, 0)\n })\n }\n }\n\n return results\n}\n\nfunction parseDelimitedText(text: string): {\n headers: string[]\n rows: string[][]\n error: string | null\n} {\n const results = Papa.parse<Record<string, unknown>>(text, {\n header: true,\n skipEmptyLines: \"greedy\",\n })\n\n const objectRows = Array.isArray(results.data)\n ? results.data.filter(\n (row): row is Record<string, unknown> =>\n !!row && typeof row === \"object\" && !Array.isArray(row)\n )\n : []\n const metaFields = Array.isArray(results.meta.fields)\n ? results.meta.fields.map((field) => String(field))\n : []\n const fieldKeys =\n metaFields.length > 0\n ? metaFields\n : Object.keys(objectRows[0] ?? {}).filter(\n (key) => key !== \"__parsed_extra\"\n )\n const extraColumnCount = objectRows.reduce((maxCount, row) => {\n const extras = row.__parsed_extra\n return Array.isArray(extras) ? Math.max(maxCount, extras.length) : maxCount\n }, 0)\n const headers = [\n ...fieldKeys.map((field, index) => normalizeHeaderTitle(field, index)),\n ...Array.from(\n { length: extraColumnCount },\n (_, index) => `Extra ${index + 1}`\n ),\n ]\n\n const rows = objectRows.map((row) => {\n const baseValues = fieldKeys.map((fieldKey) =>\n toDisplayString(row[fieldKey])\n )\n const extras = Array.isArray(row.__parsed_extra)\n ? row.__parsed_extra.map((value) => toDisplayString(value))\n : []\n const paddedExtras =\n extras.length >= extraColumnCount\n ? extras.slice(0, extraColumnCount)\n : [\n ...extras,\n ...Array.from(\n { length: extraColumnCount - extras.length },\n () => \"\"\n ),\n ]\n\n return [...baseValues, ...paddedExtras]\n })\n\n const firstError =\n Array.isArray(results.errors) && results.errors.length > 0\n ? results.errors[0]\n : null\n\n return {\n headers,\n rows,\n error:\n rows.length === 0 && firstError\n ? String(firstError.message ?? \"Could not parse CSV file.\")\n : null,\n }\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className=\"inline-flex\">{children}</span>\n </TooltipTrigger>\n <TooltipContent side=\"bottom\">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction CsvSearchPopover({\n headers,\n rows,\n gridRef,\n dataIdentity,\n controlsDisabled,\n onGridSelectionChange,\n}: {\n headers: string[]\n rows: string[][]\n gridRef: React.RefObject<DataEditorRef | null>\n dataIdentity: string\n controlsDisabled: boolean\n onGridSelectionChange: (selection: GridSelection) => void\n}) {\n const [searchDraft, setSearchDraft] = React.useState(\"\")\n const [searchQuery, setSearchQuery] = React.useState(\"\")\n const [searchResults, setSearchResults] = React.useState<CsvSearchResult[]>(\n []\n )\n const [activeResultIndex, setActiveResultIndex] = React.useState(0)\n const [isSearching, setIsSearching] = React.useState(false)\n const searchRequestIdRef = React.useRef(0)\n const appliedResultKeyRef = React.useRef(\"\")\n const activeResult = searchResults[activeResultIndex] ?? null\n const activeResultKey = activeResult\n ? `${activeResult.row}:${activeResult.col}`\n : \"\"\n const hasActiveQuery = Boolean(searchQuery.trim())\n const resultLabel = isSearching\n ? \"Searching\"\n : !hasActiveQuery\n ? \"No search\"\n : searchResults.length\n ? `${activeResultIndex + 1} / ${searchResults.length}`\n : \"No results\"\n\n const runSearch = React.useCallback(\n (rawQuery: string) => {\n const nextQuery = rawQuery.trim()\n const requestId = searchRequestIdRef.current + 1\n searchRequestIdRef.current = requestId\n appliedResultKeyRef.current = \"\"\n setSearchQuery(nextQuery)\n setActiveResultIndex(0)\n\n if (!nextQuery) {\n setSearchResults([])\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n void findCsvSearchResults(headers, rows, nextQuery)\n .then((nextResults) => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults(nextResults)\n })\n .catch(() => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults([])\n })\n .finally(() => {\n if (searchRequestIdRef.current !== requestId) return\n setIsSearching(false)\n })\n },\n [headers, rows]\n )\n\n React.useEffect(() => {\n const trimmedDraft = searchDraft.trim()\n\n if (!trimmedDraft) {\n runSearch(\"\")\n return\n }\n\n setIsSearching(true)\n const timeoutId = window.setTimeout(() => {\n runSearch(searchDraft)\n }, CSV_SEARCH_DEBOUNCE_MS)\n\n return () => window.clearTimeout(timeoutId)\n }, [runSearch, searchDraft])\n\n const clearSearch = React.useCallback(() => {\n searchRequestIdRef.current += 1\n setSearchDraft(\"\")\n setSearchQuery(\"\")\n setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = \"\"\n onGridSelectionChange(emptyGridSelection)\n }, [onGridSelectionChange])\n\n const goToRelativeResult = React.useCallback(\n (direction: 1 | -1) => {\n if (!searchResults.length) return\n\n setActiveResultIndex((currentIndex) => {\n return (\n (currentIndex + direction + searchResults.length) %\n searchResults.length\n )\n })\n },\n [searchResults.length]\n )\n\n React.useEffect(() => {\n searchRequestIdRef.current += 1\n setSearchDraft(\"\")\n setSearchQuery(\"\")\n setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = \"\"\n onGridSelectionChange(emptyGridSelection)\n }, [dataIdentity, onGridSelectionChange])\n\n React.useEffect(() => {\n if (!activeResult) return\n\n if (appliedResultKeyRef.current === activeResultKey) return\n appliedResultKeyRef.current = activeResultKey\n\n const cell: Item = [activeResult.col, activeResult.row]\n onGridSelectionChange(createSingleCellSelection(cell))\n\n const frame = window.requestAnimationFrame(() => {\n gridRef.current?.scrollTo(\n activeResult.col,\n activeResult.row,\n \"both\",\n 48,\n 48,\n {\n vAlign: \"center\",\n hAlign: \"center\",\n }\n )\n })\n\n return () => window.cancelAnimationFrame(frame)\n }, [activeResult, activeResultKey, gridRef, onGridSelectionChange])\n\n return (\n <Popover>\n <ToolbarTooltip label=\"Search CSV\">\n <PopoverTrigger asChild>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Search CSV\"\n disabled={controlsDisabled}\n >\n <HugeiconsIcon icon={Search01Icon} className=\"size-4\" />\n </Button>\n </PopoverTrigger>\n </ToolbarTooltip>\n <PopoverContent align=\"end\" className=\"w-72\">\n <div className=\"space-y-3\">\n <Input\n placeholder=\"Search CSV\"\n value={searchDraft}\n onChange={(event) => setSearchDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key !== \"Enter\") return\n\n event.preventDefault()\n if (event.shiftKey && searchResults.length) {\n goToRelativeResult(-1)\n } else if (searchResults.length) {\n goToRelativeResult(1)\n } else if (searchDraft.trim()) {\n runSearch(searchDraft)\n }\n }}\n />\n <div className=\"flex items-center justify-between gap-2\">\n <div className=\"min-w-0 text-xs text-muted-foreground\">\n <div className=\"truncate\">\n {searchResults.length ? (\n <>\n <span className=\"text-primary\">{activeResultIndex + 1}</span>\n {` / ${searchResults.length}`}\n </>\n ) : (\n resultLabel\n )}\n </div>\n {activeResult ? (\n <div className=\"mt-0.5 truncate\">\n {activeResult.columnTitle}!{cellAddressToA1(activeResult.col, activeResult.row)}\n </div>\n ) : null}\n </div>\n <div className=\"flex shrink-0 items-center gap-1\">\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"icon-sm\"\n aria-label=\"Previous result\"\n disabled={isSearching || searchResults.length === 0}\n onClick={() => goToRelativeResult(-1)}\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className=\"size-4\" />\n </Button>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"icon-sm\"\n aria-label=\"Next result\"\n disabled={isSearching || searchResults.length === 0}\n onClick={() => goToRelativeResult(1)}\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className=\"size-4\" />\n </Button>\n </div>\n </div>\n <div className=\"flex justify-end\">\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={clearSearch}\n >\n Clear\n </Button>\n </div>\n </div>\n </PopoverContent>\n </Popover>\n )\n}\n\nfunction readIsDarkTheme() {\n return (\n typeof document !== \"undefined\" &&\n document.documentElement.classList.contains(\"dark\")\n )\n}\n\nfunction useIsDarkTheme() {\n const [isDark, setIsDark] = React.useState(readIsDarkTheme)\n\n React.useEffect(() => {\n if (typeof document === \"undefined\") return\n\n const updateTheme = () => setIsDark(readIsDarkTheme())\n\n updateTheme()\n\n if (typeof MutationObserver === \"undefined\") return\n\n const observer = new MutationObserver(updateTheme)\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: [\"class\"],\n })\n\n return () => observer.disconnect()\n }, [])\n\n return isDark\n}\n\nexport function CsvViewer({ className, data, search = false }: CsvViewerProps) {\n const inputRef = React.useRef<HTMLInputElement | null>(null)\n const gridRef = React.useRef<DataEditorRef | null>(null)\n const isDark = useIsDarkTheme()\n const [glide, setGlide] = React.useState<GlideDataGridModule | null>(null)\n const [zoom, setZoom] = React.useState<(typeof ZOOM_OPTIONS)[number]>(1)\n const [gridSelection, setGridSelection] =\n React.useState<GridSelection>(emptyGridSelection)\n const [parsed, setParsed] = React.useState(() =>\n data ? parseDelimitedText(data) : { headers: [], rows: [], error: null }\n )\n const [isPending, setIsPending] = React.useState(false)\n const [dataRevision, setDataRevision] = React.useState(0)\n\n const dataIdentity = React.useMemo(\n () =>\n `${dataRevision}:${parsed.headers.join(\"\\u0001\")}:${parsed.rows.length}:${parsed.error ?? \"\"}`,\n [dataRevision, parsed.error, parsed.headers, parsed.rows.length]\n )\n\n const handleGridSelectionChange = React.useCallback(\n (selection: GridSelection) => {\n setGridSelection(selection)\n },\n []\n )\n\n React.useEffect(() => {\n if (data) {\n setParsed(parseDelimitedText(data))\n setDataRevision((revision) => revision + 1)\n }\n }, [data])\n\n React.useEffect(() => {\n if (!search) {\n setGridSelection(emptyGridSelection)\n }\n }, [search])\n\n React.useEffect(() => {\n let mounted = true\n\n void import(\"@glideapps/glide-data-grid\").then((module) => {\n if (mounted) {\n setGlide(module)\n }\n })\n\n return () => {\n mounted = false\n }\n }, [])\n\n const columnCount = Math.max(1, parsed.headers.length)\n const scale = React.useCallback(\n (value: number) => Math.round(value * zoom),\n [zoom]\n )\n const searchDisabled =\n Boolean(parsed.error) || parsed.rows.length === 0 || isPending\n\n const theme = React.useMemo<Partial<Theme>>(\n () => ({\n accentColor: isDark ? \"#60a5fa\" : \"#2563eb\",\n accentLight: isDark ? \"#1d4ed826\" : \"#dbeafe\",\n accentFg: \"#ffffff\",\n textDark: isDark ? \"#e5e5e5\" : \"#171717\",\n textMedium: isDark ? \"#a3a3a3\" : \"#525252\",\n textLight: isDark ? \"#737373\" : \"#a3a3a3\",\n textBubble: isDark ? \"#f5f5f5\" : \"#171717\",\n textHeader: isDark ? \"#f5f5f5\" : \"#171717\",\n textGroupHeader: isDark ? \"#a3a3a3\" : \"#525252\",\n bgCell: isDark ? \"#0a0a0a\" : \"#ffffff\",\n bgCellMedium: isDark ? \"#171717\" : \"#fafafa\",\n bgHeader: isDark ? \"#171717\" : \"#fafafa\",\n bgHeaderHasFocus: isDark ? \"#262626\" : \"#f5f5f5\",\n bgHeaderHovered: isDark ? \"#262626\" : \"#f5f5f5\",\n borderColor: isDark ? \"#262626\" : \"#e5e5e5\",\n horizontalBorderColor: isDark ? \"#262626\" : \"#e5e5e5\",\n cellHorizontalPadding: scale(8),\n cellVerticalPadding: Math.max(2, scale(3)),\n headerIconSize: scale(18),\n baseFontStyle: `${scale(13)}px`,\n headerFontStyle: `600 ${scale(13)}px`,\n markerFontStyle: `${scale(11)}px`,\n fontFamily: '-apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif',\n editorFontSize: `${scale(13)}px`,\n }),\n [isDark, scale]\n )\n\n const columns = React.useMemo<GridColumn[]>(\n () =>\n Array.from({ length: columnCount }, (_, index) => ({\n id: `column-${index}`,\n title: parsed.headers[index] ?? `Column ${index + 1}`,\n width: scale(index === 0 ? 180 : 160),\n })),\n [columnCount, parsed.headers, scale]\n )\n\n const getCellContent = React.useCallback(\n ([col, row]: Item): GridCell => {\n const value = parsed.rows[row]?.[col] ?? \"\"\n const textKind = glide?.GridCellKind.Text as GridCellKind.Text\n\n return {\n kind: textKind,\n data: value,\n displayData: value,\n allowOverlay: true,\n readonly: true,\n }\n },\n [glide, parsed.rows]\n )\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n if (!file) return\n\n setIsPending(true)\n try {\n const text = await file.text()\n setParsed(parseDelimitedText(text))\n setDataRevision((revision) => revision + 1)\n } catch (error) {\n setParsed({\n headers: [],\n rows: [],\n error:\n error instanceof Error ? error.message : \"Could not read CSV file.\",\n })\n setDataRevision((revision) => revision + 1)\n } finally {\n event.target.value = \"\"\n setIsPending(false)\n }\n }\n\n function stepZoom(direction: -1 | 1) {\n const index = ZOOM_OPTIONS.indexOf(zoom)\n const nextIndex = Math.min(\n ZOOM_OPTIONS.length - 1,\n Math.max(0, index + direction)\n )\n setZoom(ZOOM_OPTIONS[nextIndex])\n }\n\n return (\n <div\n className={cn(\n \"flex h-[560px] w-full flex-col overflow-hidden bg-background\",\n className\n )}\n >\n <div className=\"flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2\">\n <TooltipProvider>\n <div className=\"ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1\">\n <div className=\"flex flex-none items-center gap-1\">\n <ToolbarTooltip label=\"Zoom out\">\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Zoom out\"\n disabled={zoom <= ZOOM_OPTIONS[0]}\n onClick={() => stepZoom(-1)}\n >\n <HugeiconsIcon\n icon={MinusSignCircleIcon}\n className=\"size-4\"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={zoom.toString()}\n onValueChange={(value) =>\n setZoom(Number(value) as (typeof ZOOM_OPTIONS)[number])\n }\n modal={false}\n >\n <SelectTrigger\n size=\"sm\"\n className=\"w-[84px] min-w-[84px]\"\n aria-label=\"Zoom level\"\n >\n <SelectValue>{Math.round(zoom * 100)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align=\"end\" alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((option) => (\n <SelectItem key={option} value={option.toString()}>\n {Math.round(option * 100)}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label=\"Zoom in\">\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Zoom in\"\n disabled={zoom >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]}\n onClick={() => stepZoom(1)}\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n </div>\n {search ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n <CsvSearchPopover\n headers={parsed.headers}\n rows={parsed.rows}\n gridRef={gridRef}\n dataIdentity={dataIdentity}\n controlsDisabled={searchDisabled}\n onGridSelectionChange={handleGridSelectionChange}\n />\n </>\n ) : null}\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n <input\n ref={inputRef}\n type=\"file\"\n accept=\".csv,.tsv,text/csv,text/tab-separated-values\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n <ToolbarTooltip label=\"Upload CSV\">\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Upload CSV\"\n loading={isPending}\n onClick={() => inputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n </div>\n </TooltipProvider>\n </div>\n <div className=\"min-h-0 flex-1\">\n {parsed.error ? (\n <div className=\"flex h-full items-center justify-center px-4 text-center text-sm text-destructive\">\n {parsed.error}\n </div>\n ) : parsed.rows.length === 0 ? (\n <div className=\"grid h-full place-items-center bg-muted/30 p-4\">\n <div className=\"max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs\">\n <p className=\"font-medium\">Upload a CSV to preview</p>\n <p className=\"mt-1 text-muted-foreground\">\n Pass delimited text with the <code>data</code> prop or upload a\n CSV file.\n </p>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n className=\"mt-4\"\n loading={isPending}\n onClick={() => inputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n Upload CSV\n </Button>\n </div>\n </div>\n ) : !glide ? (\n <div className=\"grid h-full place-items-center bg-background\">\n <Spinner className=\"size-4\" />\n </div>\n ) : (\n <glide.DataEditor\n ref={search ? gridRef : undefined}\n key={zoom}\n columns={columns}\n rows={parsed.rows.length}\n getCellContent={getCellContent}\n rowMarkers=\"number\"\n rowSelectionMode=\"multi\"\n gridSelection={search ? gridSelection : undefined}\n onGridSelectionChange={\n search ? handleGridSelectionChange : undefined\n }\n scrollToActiveCell={search}\n keybindings={{ search: true }}\n smoothScrollX\n smoothScrollY\n getCellsForSelection\n width=\"100%\"\n height=\"100%\"\n theme={theme}\n rowHeight={scale(34)}\n headerHeight={scale(36)}\n />\n )}\n </div>\n </div>\n )\n}\n"
export function CsvViewerSource() {
return (
diff --git a/apps/v4/components/ui/csv-viewer.tsx b/apps/v4/components/ui/csv-viewer.tsx
index f41c783..66edead 100644
--- a/apps/v4/components/ui/csv-viewer.tsx
+++ b/apps/v4/components/ui/csv-viewer.tsx
@@ -3,18 +3,27 @@
import * as React from "react"
import type * as GlideDataGrid from "@glideapps/glide-data-grid"
import type {
+ DataEditorRef,
GridCell,
GridCellKind,
GridColumn,
+ GridSelection,
Item,
Theme,
} from "@glideapps/glide-data-grid"
+import {
+ CompactSelection,
+ emptyGridSelection,
+} from "@glideapps/glide-data-grid"
import "@glideapps/glide-data-grid/dist/index.css"
import {
+ ArrowLeft01Icon,
+ ArrowRight01Icon,
MinusSignCircleIcon,
PlusSignCircleIcon,
+ Search01Icon,
Upload01Icon,
} from "@hugeicons/core-free-icons"
import { HugeiconsIcon } from "@hugeicons/react"
@@ -22,6 +31,12 @@ import Papa from "papaparse"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
+import { Input } from "@/components/ui/input"
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover"
import {
Select,
SelectContent,
@@ -39,11 +54,21 @@ import {
} from "@/components/ui/tooltip"
const ZOOM_OPTIONS = [0.75, 1, 1.25, 1.5, 2] as const
+const CSV_SEARCH_BATCH_ROW_COUNT = 500
+const CSV_SEARCH_DEBOUNCE_MS = 300
type GlideDataGridModule = typeof GlideDataGrid
type CsvViewerProps = {
className?: string
data?: string
+ search?: boolean
+}
+
+type CsvSearchResult = {
+ col: number
+ row: number
+ displayValue: string
+ columnTitle: string
}
function toDisplayString(value: unknown): string {
@@ -55,6 +80,91 @@ function normalizeHeaderTitle(header: string, index: number): string {
return trimmed.length > 0 ? trimmed : `Column ${index + 1}`
}
+function columnIndexToA1(col: number) {
+ let columnNumber = col + 1
+ let columnName = ""
+
+ while (columnNumber > 0) {
+ const remainder = (columnNumber - 1) % 26
+ columnName = String.fromCharCode(65 + remainder) + columnName
+ columnNumber = Math.floor((columnNumber - 1) / 26)
+ }
+
+ return columnName
+}
+
+function cellAddressToA1(col: number, row: number) {
+ return `${columnIndexToA1(col)}${row + 1}`
+}
+
+function cellMatchesQuery(displayValue: string, query: string) {
+ return displayValue.toLowerCase().includes(query)
+}
+
+function createSingleCellSelection(cell: Item): GridSelection {
+ const [col, row] = cell
+
+ return {
+ columns: CompactSelection.empty(),
+ rows: CompactSelection.empty(),
+ current: {
+ cell,
+ range: { x: col, y: row, width: 1, height: 1 },
+ rangeStack: [],
+ },
+ }
+}
+
+async function findCsvSearchResults(
+ headers: string[],
+ rows: string[][],
+ rawQuery: string
+) {
+ const query = rawQuery.trim().toLowerCase()
+ if (!query) return []
+
+ const results: CsvSearchResult[] = []
+ const columnCount = Math.max(
+ headers.length,
+ rows.reduce((maxCount, row) => Math.max(maxCount, row.length), 0)
+ )
+
+ for (
+ let batchStartRow = 0;
+ batchStartRow < rows.length;
+ batchStartRow += CSV_SEARCH_BATCH_ROW_COUNT
+ ) {
+ const batchEndRow = Math.min(
+ batchStartRow + CSV_SEARCH_BATCH_ROW_COUNT,
+ rows.length
+ )
+
+ for (let row = batchStartRow; row < batchEndRow; row += 1) {
+ const rowValues = rows[row] ?? []
+
+ for (let col = 0; col < columnCount; col += 1) {
+ const displayValue = rowValues[col] ?? ""
+ if (!cellMatchesQuery(displayValue, query)) continue
+
+ results.push({
+ col,
+ row,
+ displayValue,
+ columnTitle: headers[col] ?? `Column ${col + 1}`,
+ })
+ }
+ }
+
+ if (batchEndRow < rows.length) {
+ await new Promise<void>((resolve) => {
+ window.setTimeout(resolve, 0)
+ })
+ }
+ }
+
+ return results
+}
+
function parseDelimitedText(text: string): {
headers: string[]
rows: string[][]
@@ -145,6 +255,245 @@ function ToolbarTooltip({
)
}
+function CsvSearchPopover({
+ headers,
+ rows,
+ gridRef,
+ dataIdentity,
+ controlsDisabled,
+ onGridSelectionChange,
+}: {
+ headers: string[]
+ rows: string[][]
+ gridRef: React.RefObject<DataEditorRef | null>
+ dataIdentity: string
+ controlsDisabled: boolean
+ onGridSelectionChange: (selection: GridSelection) => void
+}) {
+ const [searchDraft, setSearchDraft] = React.useState("")
+ const [searchQuery, setSearchQuery] = React.useState("")
+ const [searchResults, setSearchResults] = React.useState<CsvSearchResult[]>(
+ []
+ )
+ const [activeResultIndex, setActiveResultIndex] = React.useState(0)
+ const [isSearching, setIsSearching] = React.useState(false)
+ const searchRequestIdRef = React.useRef(0)
+ const appliedResultKeyRef = React.useRef("")
+ const activeResult = searchResults[activeResultIndex] ?? null
+ const activeResultKey = activeResult
+ ? `${activeResult.row}:${activeResult.col}`
+ : ""
+ const hasActiveQuery = Boolean(searchQuery.trim())
+ const resultLabel = isSearching
+ ? "Searching"
+ : !hasActiveQuery
+ ? "No search"
+ : searchResults.length
+ ? `${activeResultIndex + 1} / ${searchResults.length}`
+ : "No results"
+
+ const runSearch = React.useCallback(
+ (rawQuery: string) => {
+ const nextQuery = rawQuery.trim()
+ const requestId = searchRequestIdRef.current + 1
+ searchRequestIdRef.current = requestId
+ appliedResultKeyRef.current = ""
+ setSearchQuery(nextQuery)
+ setActiveResultIndex(0)
+
+ if (!nextQuery) {
+ setSearchResults([])
+ setIsSearching(false)
+ return
+ }
+
+ setIsSearching(true)
+ void findCsvSearchResults(headers, rows, nextQuery)
+ .then((nextResults) => {
+ if (searchRequestIdRef.current !== requestId) return
+ setSearchResults(nextResults)
+ })
+ .catch(() => {
+ if (searchRequestIdRef.current !== requestId) return
+ setSearchResults([])
+ })
+ .finally(() => {
+ if (searchRequestIdRef.current !== requestId) return
+ setIsSearching(false)
+ })
+ },
+ [headers, rows]
+ )
+
+ React.useEffect(() => {
+ const trimmedDraft = searchDraft.trim()
+
+ if (!trimmedDraft) {
+ runSearch("")
+ return
+ }
+
+ setIsSearching(true)
+ const timeoutId = window.setTimeout(() => {
+ runSearch(searchDraft)
+ }, CSV_SEARCH_DEBOUNCE_MS)
+
+ return () => window.clearTimeout(timeoutId)
+ }, [runSearch, searchDraft])
+
+ const clearSearch = React.useCallback(() => {
+ searchRequestIdRef.current += 1
+ setSearchDraft("")
+ setSearchQuery("")
+ setSearchResults([])
+ setActiveResultIndex(0)
+ setIsSearching(false)
+ appliedResultKeyRef.current = ""
+ onGridSelectionChange(emptyGridSelection)
+ }, [onGridSelectionChange])
+
+ const goToRelativeResult = React.useCallback(
+ (direction: 1 | -1) => {
+ if (!searchResults.length) return
+
+ setActiveResultIndex((currentIndex) => {
+ return (
+ (currentIndex + direction + searchResults.length) %
+ searchResults.length
+ )
+ })
+ },
+ [searchResults.length]
+ )
+
+ React.useEffect(() => {
+ searchRequestIdRef.current += 1
+ setSearchDraft("")
+ setSearchQuery("")
+ setSearchResults([])
+ setActiveResultIndex(0)
+ setIsSearching(false)
+ appliedResultKeyRef.current = ""
+ onGridSelectionChange(emptyGridSelection)
+ }, [dataIdentity, onGridSelectionChange])
+
+ React.useEffect(() => {
+ if (!activeResult) return
+
+ if (appliedResultKeyRef.current === activeResultKey) return
+ appliedResultKeyRef.current = activeResultKey
+
+ const cell: Item = [activeResult.col, activeResult.row]
+ onGridSelectionChange(createSingleCellSelection(cell))
+
+ const frame = window.requestAnimationFrame(() => {
+ gridRef.current?.scrollTo(
+ activeResult.col,
+ activeResult.row,
+ "both",
+ 48,
+ 48,
+ {
+ vAlign: "center",
+ hAlign: "center",
+ }
+ )
+ })
+
+ return () => window.cancelAnimationFrame(frame)
+ }, [activeResult, activeResultKey, gridRef, onGridSelectionChange])
+
+ return (
+ <Popover>
+ <ToolbarTooltip label="Search CSV">
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Search CSV"
+ disabled={controlsDisabled}
+ >
+ <HugeiconsIcon icon={Search01Icon} className="size-4" />
+ </Button>
+ </PopoverTrigger>
+ </ToolbarTooltip>
+ <PopoverContent align="end" className="w-72">
+ <div className="space-y-3">
+ <Input
+ placeholder="Search CSV"
+ value={searchDraft}
+ onChange={(event) => setSearchDraft(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key !== "Enter") return
+
+ event.preventDefault()
+ if (event.shiftKey && searchResults.length) {
+ goToRelativeResult(-1)
+ } else if (searchResults.length) {
+ goToRelativeResult(1)
+ } else if (searchDraft.trim()) {
+ runSearch(searchDraft)
+ }
+ }}
+ />
+ <div className="flex items-center justify-between gap-2">
+ <div className="min-w-0 text-xs text-muted-foreground">
+ <div className="truncate">
+ {searchResults.length ? (
+ <>
+ <span className="text-primary">{activeResultIndex + 1}</span>
+ {` / ${searchResults.length}`}
+ </>
+ ) : (
+ resultLabel
+ )}
+ </div>
+ {activeResult ? (
+ <div className="mt-0.5 truncate">
+ {activeResult.columnTitle}!{cellAddressToA1(activeResult.col, activeResult.row)}
+ </div>
+ ) : null}
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ <Button
+ type="button"
+ variant="outline"
+ size="icon-sm"
+ aria-label="Previous result"
+ disabled={isSearching || searchResults.length === 0}
+ onClick={() => goToRelativeResult(-1)}
+ >
+ <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon-sm"
+ aria-label="Next result"
+ disabled={isSearching || searchResults.length === 0}
+ onClick={() => goToRelativeResult(1)}
+ >
+ <HugeiconsIcon icon={ArrowRight01Icon} className="size-4" />
+ </Button>
+ </div>
+ </div>
+ <div className="flex justify-end">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={clearSearch}
+ >
+ Clear
+ </Button>
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ )
+}
+
function readIsDarkTheme() {
return (
typeof document !== "undefined" &&
@@ -176,22 +525,46 @@ function useIsDarkTheme() {
return isDark
}
-export function CsvViewer({ className, data }: CsvViewerProps) {
+export function CsvViewer({ className, data, search = false }: CsvViewerProps) {
const inputRef = React.useRef<HTMLInputElement | null>(null)
+ const gridRef = React.useRef<DataEditorRef | null>(null)
const isDark = useIsDarkTheme()
const [glide, setGlide] = React.useState<GlideDataGridModule | null>(null)
const [zoom, setZoom] = React.useState<(typeof ZOOM_OPTIONS)[number]>(1)
+ const [gridSelection, setGridSelection] =
+ React.useState<GridSelection>(emptyGridSelection)
const [parsed, setParsed] = React.useState(() =>
data ? parseDelimitedText(data) : { headers: [], rows: [], error: null }
)
const [isPending, setIsPending] = React.useState(false)
+ const [dataRevision, setDataRevision] = React.useState(0)
+
+ const dataIdentity = React.useMemo(
+ () =>
+ `${dataRevision}:${parsed.headers.join("\u0001")}:${parsed.rows.length}:${parsed.error ?? ""}`,
+ [dataRevision, parsed.error, parsed.headers, parsed.rows.length]
+ )
+
+ const handleGridSelectionChange = React.useCallback(
+ (selection: GridSelection) => {
+ setGridSelection(selection)
+ },
+ []
+ )
React.useEffect(() => {
if (data) {
setParsed(parseDelimitedText(data))
+ setDataRevision((revision) => revision + 1)
}
}, [data])
+ React.useEffect(() => {
+ if (!search) {
+ setGridSelection(emptyGridSelection)
+ }
+ }, [search])
+
React.useEffect(() => {
let mounted = true
@@ -211,6 +584,8 @@ export function CsvViewer({ className, data }: CsvViewerProps) {
(value: number) => Math.round(value * zoom),
[zoom]
)
+ const searchDisabled =
+ Boolean(parsed.error) || parsed.rows.length === 0 || isPending
const theme = React.useMemo<Partial<Theme>>(
() => ({
@@ -276,6 +651,7 @@ export function CsvViewer({ className, data }: CsvViewerProps) {
try {
const text = await file.text()
setParsed(parseDelimitedText(text))
+ setDataRevision((revision) => revision + 1)
} catch (error) {
setParsed({
headers: [],
@@ -283,6 +659,7 @@ export function CsvViewer({ className, data }: CsvViewerProps) {
error:
error instanceof Error ? error.message : "Could not read CSV file.",
})
+ setDataRevision((revision) => revision + 1)
} finally {
event.target.value = ""
setIsPending(false)
@@ -357,6 +734,22 @@ export function CsvViewer({ className, data }: CsvViewerProps) {
</Button>
</ToolbarTooltip>
</div>
+ {search ? (
+ <>
+ <Separator
+ orientation="vertical"
+ className="mx-1 h-4 self-center"
+ />
+ <CsvSearchPopover
+ headers={parsed.headers}
+ rows={parsed.rows}
+ gridRef={gridRef}
+ dataIdentity={dataIdentity}
+ controlsDisabled={searchDisabled}
+ onGridSelectionChange={handleGridSelectionChange}
+ />
+ </>
+ ) : null}
<Separator
orientation="vertical"
className="mx-1 h-4 self-center"
@@ -414,12 +807,18 @@ export function CsvViewer({ className, data }: CsvViewerProps) {
</div>
) : (
<glide.DataEditor
+ ref={search ? gridRef : undefined}
key={zoom}
columns={columns}
rows={parsed.rows.length}
getCellContent={getCellContent}
rowMarkers="number"
rowSelectionMode="multi"
+ gridSelection={search ? gridSelection : undefined}
+ onGridSelectionChange={
+ search ? handleGridSelectionChange : undefined
+ }
+ scrollToActiveCell={search}
keybindings={{ search: true }}
smoothScrollX
smoothScrollY
diff --git a/apps/v4/content/docs/components/csv-tsv-viewer.mdx b/apps/v4/content/docs/components/csv-tsv-viewer.mdx
index d164832..03a41eb 100644
--- a/apps/v4/content/docs/components/csv-tsv-viewer.mdx
+++ b/apps/v4/content/docs/components/csv-tsv-viewer.mdx
@@ -75,6 +75,7 @@ npm install @glideapps/[email protected] @hugeicons/core-free-icons@
- PapaParse-backed CSV and TSV parsing with empty-row handling.
- Virtualized rows and columns through Glide Data Grid.
+- Optional toolbar search via the `search` prop. When enabled, results update as you type with debounced matching, result navigation, cell selection, and scroll-into-view.
- Header controls for upload, row and column counts, and zoom.
- Grid zoom that scales row height, header height, column width, and cell text.
@@ -84,7 +85,8 @@ npm install @glideapps/[email protected] @hugeicons/core-free-icons@
The CsvViewer component renders its built-in CSV/TSV upload flow, parser state, zoom controls, and virtualized grid.
-| Prop | Type | Default | Required |
-| ----------- | -------- | ------- | -------- |
-| `className` | `string` | `-` | No |
-| `data` | `string` | `-` | No |
+| Prop | Type | Default | Required |
+| ----------- | --------- | ------- | -------- |
+| `className` | `string` | `-` | No |
+| `data` | `string` | `-` | No |
+| `search` | `boolean` | `false` | No |
diff --git a/apps/v4/registry.json b/apps/v4/registry.json
index 6cd8e83..f8456d6 100644
--- a/apps/v4/registry.json
+++ b/apps/v4/registry.json
@@ -775,7 +775,7 @@
"name": "csv-viewer",
"type": "registry:ui",
"title": "CSV Viewer",
- "description": "A CSV and TSV viewer with parsing, upload, zoom, theme-aware grid rendering, and Glide Data Grid.",
+ "description": "A CSV and TSV viewer with parsing, upload, search, zoom, theme-aware grid rendering, and Glide Data Grid.",
"dependencies": [
"@glideapps/[email protected]",
"@hugeicons/core-free-icons@^4.2.0",
@@ -785,6 +785,8 @@
"devDependencies": ["@types/papaparse@^5.5.2"],
"registryDependencies": [
"button",
+ "input",
+ "popover",
"select",
"separator",
"spinner",