Skip to content

armgit / ui

Public Imported from GitHub
0
TypeScript

Sync root title and manual source snippets

Andrew Luo285a80d85af7
diff --git a/apps/v4/app/(app)/(root)/page.tsx b/apps/v4/app/(app)/(root)/page.tsx
index 9fc7987..d9fe446 100644
--- a/apps/v4/app/(app)/(root)/page.tsx
+++ b/apps/v4/app/(app)/(root)/page.tsx
@@ -15,10 +15,11 @@ import {
} from "@/components/root-components-collage"
import { RootLiquidLogo } from "@/components/root-liquid-logo"
-const title = "UI components for document agents"
+const title = "Open source UI kit for modern document apps"
const description =
"Open source viewers for PDF, DOCX, XLSX, and CSV, with bounding box citations, file upload, e-signing, and more."
-const tagline = "Ready to drop into user-facing flows, agents, or internal tools."
+const tagline =
+ "Ready to drop into user-facing flows, agents, or internal tools."
export const dynamic = "force-static"
export const revalidate = false
diff --git a/apps/v4/components/csv-viewer-docs.tsx b/apps/v4/components/csv-viewer-docs.tsx
index d75cfb2..bbc0dda 100644
--- a/apps/v4/components/csv-viewer-docs.tsx
+++ b/apps/v4/components/csv-viewer-docs.tsx
@@ -67,7 +67,7 @@ export function CsvViewerExample() {
}`
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"\nimport "@glideapps/glide-data-grid/dist/index.css"\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 { Spinner } from "@/components/ui/spinner"\nimport { Separator } from "@/components/ui/separator"\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 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'
export function CsvViewerSource() {
return (
diff --git a/apps/v4/components/document-splitter-docs.tsx b/apps/v4/components/document-splitter-docs.tsx
index ad979b7..c39323b 100644
--- a/apps/v4/components/document-splitter-docs.tsx
+++ b/apps/v4/components/document-splitter-docs.tsx
@@ -1812,7 +1812,7 @@ export function DocumentSplitsExample() {
}`
const documentSplitterSourceCode =
- '"use client"\n\nimport * as React from "react"\nimport {\n closestCenter,\n DndContext,\n DragOverlay,\n PointerSensor,\n useDroppable,\n useSensor,\n useSensors,\n type CollisionDetection,\n type DragEndEvent,\n type DragOverEvent,\n type DragStartEvent,\n} from "@dnd-kit/core"\nimport {\n arrayMove,\n horizontalListSortingStrategy,\n SortableContext,\n useSortable,\n verticalListSortingStrategy,\n} from "@dnd-kit/sortable"\nimport { CSS } from "@dnd-kit/utilities"\nimport {\n Add01Icon,\n Delete02Icon,\n DragDropVerticalIcon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\n\nimport { cn } from "@/lib/utils"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Button } from "@/components/ui/button"\nimport { ScrollArea } from "@/components/ui/scroll-area"\n\nexport type DocumentSplitPageId = `page-${number}`\nexport type DocumentSplit = {\n id: string\n title: string\n pages: DocumentSplitPageId[]\n}\n\ntype PageId = DocumentSplitPageId\ntype SplitGroup = DocumentSplit\n\nconst THUMBNAIL_WIDTH = 72\nconst THUMBNAIL_HEIGHT = 92\nconst DRAG_OVERLAY_DROP_ANIMATION = null\n\nconst splitterCollisionDetection: CollisionDetection = (args) => {\n const dragType = args.active.data.current?.type\n\n if (dragType === "page") {\n return closestCenter({\n ...args,\n droppableContainers: args.droppableContainers.filter(\n (container) =>\n container.data.current?.type === "page" ||\n (container.data.current?.type === "page-dropzone" &&\n container.data.current?.isEmpty)\n ),\n })\n }\n\n if (dragType === "split") {\n return closestCenter({\n ...args,\n droppableContainers: args.droppableContainers.filter(\n (container) => container.data.current?.type === "split"\n ),\n })\n }\n\n return closestCenter(args)\n}\n\nexport const INITIAL_SPLITS: DocumentSplit[] = [\n {\n id: "split-1",\n title: "Abstract and intro",\n pages: ["page-1", "page-2", "page-3"],\n },\n {\n id: "split-2",\n title: "Model architecture",\n pages: ["page-4", "page-5", "page-6", "page-7"],\n },\n {\n id: "split-3",\n title: "Training and results",\n pages: ["page-8", "page-9", "page-10"],\n },\n]\n\nexport function createInitialSplits(pageCount: number) {\n if (pageCount <= 0) return INITIAL_SPLITS\n\n const pages = Array.from(\n { length: pageCount },\n (_, index) => `page-${index + 1}` as PageId\n )\n const chunkSize = Math.max(1, Math.ceil(pageCount / 3))\n\n return Array.from(\n { length: Math.ceil(pageCount / chunkSize) },\n (_, index) => {\n const startIndex = index * chunkSize\n const groupPages = pages.slice(startIndex, startIndex + chunkSize)\n const firstPage = getPageNumber(groupPages[0])\n const lastPage = getPageNumber(groupPages[groupPages.length - 1])\n\n return {\n id: `split-${index + 1}`,\n title:\n firstPage === lastPage\n ? `Page ${firstPage}`\n : `Pages ${firstPage}-${lastPage}`,\n pages: groupPages,\n }\n }\n )\n}\n\nfunction getPageNumber(pageId: PageId) {\n return Number(pageId.replace("page-", ""))\n}\n\nfunction getSplitSortableId(groupId: string) {\n return `split-sortable-${groupId}`\n}\n\nfunction findGroupId(groups: SplitGroup[], id: string) {\n if (groups.some((group) => group.id === id)) return id\n\n return groups.find((group) => group.pages.includes(id as PageId))?.id ?? null\n}\n\nfunction getGroupPages(groups: SplitGroup[], groupId: string | null) {\n return groups.find((group) => group.id === groupId)?.pages ?? []\n}\n\nfunction movePageToGroup({\n draggedPageId,\n groups,\n insertIndex,\n targetGroupId,\n}: {\n draggedPageId: PageId\n groups: SplitGroup[]\n insertIndex: number\n targetGroupId: string\n}) {\n return groups.map((group) => {\n const pagesWithoutDragged = group.pages.filter(\n (pageId) => pageId !== draggedPageId\n )\n\n if (group.id !== targetGroupId) {\n return { ...group, pages: pagesWithoutDragged }\n }\n\n const nextPages = [...pagesWithoutDragged]\n nextPages.splice(insertIndex, 0, draggedPageId)\n\n return { ...group, pages: nextPages }\n })\n}\n\nfunction areSplitGroupsEqual(left: SplitGroup[], right: SplitGroup[]) {\n if (left === right) return true\n if (left.length !== right.length) return false\n\n return left.every((leftGroup, groupIndex) => {\n const rightGroup = right[groupIndex]\n if (!rightGroup) return false\n\n return (\n leftGroup.id === rightGroup.id &&\n leftGroup.title === rightGroup.title &&\n leftGroup.pages.length === rightGroup.pages.length &&\n leftGroup.pages.every(\n (pageId, pageIndex) => pageId === rightGroup.pages[pageIndex]\n )\n )\n })\n}\n\nfunction reorderPageInGroup({\n draggedPageId,\n groups,\n overPageId,\n}: {\n draggedPageId: PageId\n groups: SplitGroup[]\n overPageId: PageId\n}) {\n const groupId = findGroupId(groups, draggedPageId)\n const pages = getGroupPages(groups, groupId)\n const draggedIndex = pages.indexOf(draggedPageId)\n const overIndex = pages.indexOf(overPageId)\n\n if (!groupId || draggedIndex === -1 || overIndex === -1) return groups\n\n return groups.map((group) =>\n group.id === groupId\n ? {\n ...group,\n pages: arrayMove(group.pages, draggedIndex, overIndex),\n }\n : group\n )\n}\n\nfunction createPageRangeLabel(pageIds: PageId[]) {\n if (pageIds.length === 0) return "No pages"\n\n return `Pages ${pageIds.map(getPageNumber).join(", ")}`\n}\n\nfunction SplitGroupDropzone({\n children,\n group,\n}: {\n children: React.ReactNode\n group: SplitGroup\n}) {\n const { isOver, setNodeRef } = useDroppable({\n id: group.id,\n data: { type: "page-dropzone", isEmpty: group.pages.length === 0 },\n })\n\n return (\n <div\n ref={setNodeRef}\n className={cn(\n "min-h-[116px] rounded-lg p-2 transition-[background-color,box-shadow]",\n isOver && "bg-accent/30 shadow-[inset_0_0_0_1px_var(--border)]"\n )}\n >\n {children}\n </div>\n )\n}\n\nfunction PageThumbnail({\n imageUrl,\n onSelect,\n pageId,\n}: {\n imageUrl?: string\n onSelect: (pageNumber: number) => void\n pageId: PageId\n}) {\n const pageNumber = getPageNumber(pageId)\n const {\n attributes,\n isDragging,\n listeners,\n setNodeRef,\n transform,\n transition,\n } = useSortable({\n id: pageId,\n data: { type: "page" },\n })\n\n return (\n <button\n ref={setNodeRef}\n type="button"\n className={cn(\n "relative shrink-0 cursor-grab overflow-hidden rounded-md border border-border bg-muted text-left shadow-xs transition-[border-color,opacity] hover:border-foreground/30 active:cursor-grabbing",\n isDragging && "opacity-0"\n )}\n style={{\n width: THUMBNAIL_WIDTH,\n height: THUMBNAIL_HEIGHT,\n transform: CSS.Transform.toString(transform),\n transition,\n }}\n onClick={() => onSelect(pageNumber)}\n {...attributes}\n {...listeners}\n >\n <FileThumbnail\n file={{\n name: `page-${pageNumber}.pdf`,\n type: "application/pdf",\n }}\n previewImageUrl={imageUrl}\n isLoading={!imageUrl}\n previewClassName="h-full aspect-auto"\n className="size-full rounded-[inherit] border-0"\n />\n <span className="absolute right-1 bottom-1 rounded bg-background/95 px-1.5 py-0.5 text-[10px] font-semibold text-foreground shadow-xs ring-1 ring-border/80">\n {pageNumber}\n </span>\n </button>\n )\n}\n\nfunction SplitGroupCard({\n canRemove,\n group,\n dragHandleProps,\n thumbnailImages,\n onRemove,\n onSelectPage,\n}: {\n canRemove: boolean\n group: SplitGroup\n dragHandleProps?: React.ComponentPropsWithoutRef<"button">\n thumbnailImages: Record<PageId, string>\n onRemove: () => void\n onSelectPage: (pageNumber: number) => void\n}) {\n return (\n <section className="w-full rounded-lg border bg-background">\n <div className="flex items-center justify-between gap-3 border-b p-3">\n <div className="flex min-w-0 items-center gap-2">\n <button\n type="button"\n aria-label={`Reorder ${group.title}`}\n className="inline-flex size-7 shrink-0 cursor-grab items-center justify-center rounded-md text-muted-foreground hover:bg-muted active:cursor-grabbing"\n {...dragHandleProps}\n >\n <HugeiconsIcon icon={DragDropVerticalIcon} className="size-4" />\n </button>\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">{group.title}</div>\n <div className="mt-1 text-xs text-muted-foreground">\n {createPageRangeLabel(group.pages)}\n </div>\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-2">\n <div className="rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">\n {group.pages.length}\n </div>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label={`Remove ${group.title}`}\n disabled={!canRemove}\n onClick={onRemove}\n >\n <HugeiconsIcon icon={Delete02Icon} className="size-4" />\n </Button>\n </div>\n </div>\n <SplitGroupDropzone group={group}>\n {group.pages.length ? (\n <SortableContext\n items={group.pages}\n strategy={horizontalListSortingStrategy}\n >\n <ScrollArea\n className="h-[110px] w-full overflow-hidden"\n orientation="horizontal"\n scrollbarGutter\n scrollbarOverflowOnly\n viewportClassName="overflow-y-hidden"\n >\n <div className="flex w-max gap-2 overflow-y-hidden py-1 pr-6">\n {group.pages.map((pageId) => (\n <PageThumbnail\n key={pageId}\n pageId={pageId}\n imageUrl={thumbnailImages[pageId]}\n onSelect={onSelectPage}\n />\n ))}\n </div>\n </ScrollArea>\n </SortableContext>\n ) : (\n <div className="grid h-[104px] place-items-center rounded-lg bg-muted/35 text-xs text-muted-foreground">\n Drop pages here\n </div>\n )}\n </SplitGroupDropzone>\n </section>\n )\n}\n\nfunction SortableSplitGroupCard({\n canRemove,\n group,\n thumbnailImages,\n onRemove,\n onSelectPage,\n}: {\n canRemove: boolean\n group: SplitGroup\n thumbnailImages: Record<PageId, string>\n onRemove: () => void\n onSelectPage: (pageNumber: number) => void\n}) {\n const {\n attributes,\n isDragging,\n listeners,\n setNodeRef,\n transform,\n transition,\n } = useSortable({\n id: getSplitSortableId(group.id),\n data: { type: "split", groupId: group.id },\n })\n\n return (\n <div\n ref={setNodeRef}\n className={cn("w-full", isDragging && "opacity-0")}\n style={{\n transform: CSS.Transform.toString(transform),\n transition,\n }}\n >\n <SplitGroupCard\n canRemove={canRemove}\n group={group}\n thumbnailImages={thumbnailImages}\n dragHandleProps={{ ...attributes, ...listeners }}\n onRemove={onRemove}\n onSelectPage={onSelectPage}\n />\n </div>\n )\n}\n\nfunction SplitGroupDragOverlay({\n group,\n thumbnailImages,\n width,\n onSelectPage,\n}: {\n group: SplitGroup\n thumbnailImages: Record<PageId, string>\n width?: number\n onSelectPage: (pageNumber: number) => void\n}) {\n return (\n <div\n className="relative z-40 max-w-[calc(100vw-2rem)]"\n style={{ width }}\n >\n <SplitGroupCard\n canRemove={false}\n group={group}\n thumbnailImages={thumbnailImages}\n onRemove={() => {}}\n onSelectPage={onSelectPage}\n />\n </div>\n )\n}\n\nexport function DocumentSplits({\n className,\n splits,\n thumbnailImages = {},\n withFrameDivider = true,\n onSelectPage,\n onSplitsChange,\n}: {\n className?: string\n splits: SplitGroup[]\n thumbnailImages?: Record<PageId, string>\n withFrameDivider?: boolean\n onSelectPage: (pageNumber: number) => void\n onSplitsChange: (splits: SplitGroup[]) => void\n}) {\n const [draggedPageId, setDraggedPageId] = React.useState<PageId | null>(null)\n const [activeSplitGroupId, setActiveSplitGroupId] = React.useState<\n string | null\n >(null)\n const [activeSplitGroupWidth, setActiveSplitGroupWidth] = React.useState<\n number | undefined\n >()\n const dragStartGroupIdRef = React.useRef<string | null>(null)\n const dragStartSplitsRef = React.useRef<SplitGroup[] | null>(null)\n const sensors = useSensors(\n useSensor(PointerSensor, { activationConstraint: { distance: 6 } })\n )\n\n const handleDragStart = React.useCallback(\n (event: DragStartEvent) => {\n const dragType = event.active.data.current?.type\n\n if (dragType === "split") {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(\n (event.active.data.current?.groupId as string | undefined) ?? null\n )\n setActiveSplitGroupWidth(event.active.rect.current.initial?.width)\n return\n }\n\n if (dragType !== "page") {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n const pageId = String(event.active.id) as PageId\n dragStartGroupIdRef.current = findGroupId(splits, pageId)\n dragStartSplitsRef.current = splits\n setDraggedPageId(pageId)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n },\n [splits]\n )\n\n const handleDragOver = React.useCallback(\n (event: DragOverEvent) => {\n if (event.active.data.current?.type !== "page" || !event.over) return\n\n const pageId = String(event.active.id) as PageId\n const overId = String(event.over.id)\n\n const sourceGroupId = findGroupId(splits, pageId)\n const targetGroupId = findGroupId(splits, overId)\n\n if (!sourceGroupId || !targetGroupId || sourceGroupId === targetGroupId) {\n return\n }\n\n const targetPages = getGroupPages(splits, targetGroupId)\n const overIndex = targetPages.indexOf(overId as PageId)\n const insertIndex = overIndex === -1 ? targetPages.length : overIndex\n\n const nextSplits = movePageToGroup({\n draggedPageId: pageId,\n groups: splits,\n insertIndex,\n targetGroupId,\n })\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n },\n [onSplitsChange, splits]\n )\n\n const handleDragEnd = React.useCallback(\n (event: DragEndEvent) => {\n if (event.active.data.current?.type === "split" && event.over) {\n const activeGroupId = event.active.data.current.groupId\n const overGroupId = event.over.data.current?.groupId\n\n const draggedIndex = splits.findIndex(\n (group) => group.id === activeGroupId\n )\n const overIndex = splits.findIndex((group) => group.id === overGroupId)\n\n if (draggedIndex !== -1 && overIndex !== -1) {\n const nextSplits = arrayMove(splits, draggedIndex, overIndex)\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n }\n\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n if (event.active.data.current?.type !== "page" || !event.over) {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n const pageId = String(event.active.id) as PageId\n const overId = String(event.over.id) as PageId\n const overGroupId = findGroupId(splits, overId)\n\n if (dragStartGroupIdRef.current === overGroupId) {\n const nextSplits = reorderPageInGroup({\n draggedPageId: pageId,\n groups: splits,\n overPageId: overId,\n })\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n }\n\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n },\n [onSplitsChange, splits]\n )\n\n const handleDragCancel = React.useCallback(() => {\n if (dragStartSplitsRef.current) {\n onSplitsChange(dragStartSplitsRef.current)\n }\n\n dragStartSplitsRef.current = null\n dragStartGroupIdRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n }, [onSplitsChange])\n\n const activeSplitGroup = activeSplitGroupId\n ? splits.find((group) => group.id === activeSplitGroupId)\n : null\n\n return (\n <aside\n className={cn(\n "flex h-full min-h-0 flex-col bg-muted/20",\n withFrameDivider && "border-t md:border-t-0 md:border-l",\n className\n )}\n >\n <div className="flex min-h-12 items-center justify-end gap-3 border-b bg-background px-3">\n <Button\n type="button"\n variant="outline"\n size="sm"\n onClick={() =>\n onSplitsChange([\n ...splits,\n {\n id: `split-${Date.now()}`,\n title: `Split ${splits.length + 1}`,\n pages: [],\n },\n ])\n }\n >\n <HugeiconsIcon icon={Add01Icon} className="size-4" />\n Add split\n </Button>\n </div>\n <DndContext\n id="document-splits-dnd"\n sensors={sensors}\n collisionDetection={splitterCollisionDetection}\n onDragStart={handleDragStart}\n onDragOver={handleDragOver}\n onDragEnd={handleDragEnd}\n onDragCancel={handleDragCancel}\n >\n <ScrollArea className="min-h-0 flex-1" scrollFade>\n <SortableContext\n items={splits.map((group) => getSplitSortableId(group.id))}\n strategy={verticalListSortingStrategy}\n >\n <div className="space-y-3 p-3">\n {splits.map((group) => (\n <SortableSplitGroupCard\n key={group.id}\n canRemove={splits.length > 1}\n group={group}\n thumbnailImages={thumbnailImages}\n onRemove={() => {\n if (splits.length <= 1) return\n onSplitsChange(\n splits.filter((split) => split.id !== group.id)\n )\n }}\n onSelectPage={onSelectPage}\n />\n ))}\n </div>\n </SortableContext>\n </ScrollArea>\n <DragOverlay dropAnimation={DRAG_OVERLAY_DROP_ANIMATION} zIndex={40}>\n {draggedPageId ? (\n <div\n className="relative overflow-hidden rounded-md border bg-background shadow-lg shadow-black/10"\n style={{ width: THUMBNAIL_WIDTH, height: THUMBNAIL_HEIGHT }}\n >\n <FileThumbnail\n file={{ name: `${draggedPageId}.pdf`, type: "application/pdf" }}\n previewImageUrl={thumbnailImages[draggedPageId]}\n isLoading={!thumbnailImages[draggedPageId]}\n previewClassName="h-full aspect-auto"\n className="size-full rounded-[inherit] border-0"\n />\n </div>\n ) : activeSplitGroup ? (\n <SplitGroupDragOverlay\n group={activeSplitGroup}\n thumbnailImages={thumbnailImages}\n width={activeSplitGroupWidth}\n onSelectPage={onSelectPage}\n />\n ) : null}\n </DragOverlay>\n </DndContext>\n </aside>\n )\n}'
+ '"use client"\n\nimport * as React from "react"\nimport {\n closestCenter,\n DndContext,\n DragOverlay,\n PointerSensor,\n useDroppable,\n useSensor,\n useSensors,\n type CollisionDetection,\n type DragEndEvent,\n type DragOverEvent,\n type DragStartEvent,\n} from "@dnd-kit/core"\nimport {\n arrayMove,\n horizontalListSortingStrategy,\n SortableContext,\n useSortable,\n verticalListSortingStrategy,\n} from "@dnd-kit/sortable"\nimport { CSS } from "@dnd-kit/utilities"\nimport {\n Add01Icon,\n Delete02Icon,\n DragDropVerticalIcon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\n\nimport { cn } from "@/lib/utils"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Button } from "@/components/ui/button"\nimport { ScrollArea } from "@/components/ui/scroll-area"\n\nexport type DocumentSplitPageId = `page-${number}`\nexport type DocumentSplit = {\n id: string\n title: string\n pages: DocumentSplitPageId[]\n}\n\ntype PageId = DocumentSplitPageId\ntype SplitGroup = DocumentSplit\n\nconst THUMBNAIL_WIDTH = 72\nconst THUMBNAIL_HEIGHT = 92\nconst DRAG_OVERLAY_DROP_ANIMATION = null\n\nconst splitterCollisionDetection: CollisionDetection = (args) => {\n const dragType = args.active.data.current?.type\n\n if (dragType === "page") {\n return closestCenter({\n ...args,\n droppableContainers: args.droppableContainers.filter(\n (container) =>\n container.data.current?.type === "page" ||\n (container.data.current?.type === "page-dropzone" &&\n container.data.current?.isEmpty)\n ),\n })\n }\n\n if (dragType === "split") {\n return closestCenter({\n ...args,\n droppableContainers: args.droppableContainers.filter(\n (container) => container.data.current?.type === "split"\n ),\n })\n }\n\n return closestCenter(args)\n}\n\nexport const INITIAL_SPLITS: DocumentSplit[] = [\n {\n id: "split-1",\n title: "Abstract and intro",\n pages: ["page-1", "page-2", "page-3"],\n },\n {\n id: "split-2",\n title: "Model architecture",\n pages: ["page-4", "page-5", "page-6", "page-7"],\n },\n {\n id: "split-3",\n title: "Training and results",\n pages: ["page-8", "page-9", "page-10"],\n },\n]\n\nexport function createInitialSplits(pageCount: number) {\n if (pageCount <= 0) return INITIAL_SPLITS\n\n const pages = Array.from(\n { length: pageCount },\n (_, index) => `page-${index + 1}` as PageId\n )\n const chunkSize = Math.max(1, Math.ceil(pageCount / 3))\n\n return Array.from(\n { length: Math.ceil(pageCount / chunkSize) },\n (_, index) => {\n const startIndex = index * chunkSize\n const groupPages = pages.slice(startIndex, startIndex + chunkSize)\n const firstPage = getPageNumber(groupPages[0])\n const lastPage = getPageNumber(groupPages[groupPages.length - 1])\n\n return {\n id: `split-${index + 1}`,\n title:\n firstPage === lastPage\n ? `Page ${firstPage}`\n : `Pages ${firstPage}-${lastPage}`,\n pages: groupPages,\n }\n }\n )\n}\n\nfunction getPageNumber(pageId: PageId) {\n return Number(pageId.replace("page-", ""))\n}\n\nfunction getSplitSortableId(groupId: string) {\n return `split-sortable-${groupId}`\n}\n\nfunction findGroupId(groups: SplitGroup[], id: string) {\n if (groups.some((group) => group.id === id)) return id\n\n return groups.find((group) => group.pages.includes(id as PageId))?.id ?? null\n}\n\nfunction getGroupPages(groups: SplitGroup[], groupId: string | null) {\n return groups.find((group) => group.id === groupId)?.pages ?? []\n}\n\nfunction movePageToGroup({\n draggedPageId,\n groups,\n insertIndex,\n targetGroupId,\n}: {\n draggedPageId: PageId\n groups: SplitGroup[]\n insertIndex: number\n targetGroupId: string\n}) {\n return groups.map((group) => {\n const pagesWithoutDragged = group.pages.filter(\n (pageId) => pageId !== draggedPageId\n )\n\n if (group.id !== targetGroupId) {\n return { ...group, pages: pagesWithoutDragged }\n }\n\n const nextPages = [...pagesWithoutDragged]\n nextPages.splice(insertIndex, 0, draggedPageId)\n\n return { ...group, pages: nextPages }\n })\n}\n\nfunction areSplitGroupsEqual(left: SplitGroup[], right: SplitGroup[]) {\n if (left === right) return true\n if (left.length !== right.length) return false\n\n return left.every((leftGroup, groupIndex) => {\n const rightGroup = right[groupIndex]\n if (!rightGroup) return false\n\n return (\n leftGroup.id === rightGroup.id &&\n leftGroup.title === rightGroup.title &&\n leftGroup.pages.length === rightGroup.pages.length &&\n leftGroup.pages.every(\n (pageId, pageIndex) => pageId === rightGroup.pages[pageIndex]\n )\n )\n })\n}\n\nfunction reorderPageInGroup({\n draggedPageId,\n groups,\n overPageId,\n}: {\n draggedPageId: PageId\n groups: SplitGroup[]\n overPageId: PageId\n}) {\n const groupId = findGroupId(groups, draggedPageId)\n const pages = getGroupPages(groups, groupId)\n const draggedIndex = pages.indexOf(draggedPageId)\n const overIndex = pages.indexOf(overPageId)\n\n if (!groupId || draggedIndex === -1 || overIndex === -1) return groups\n\n return groups.map((group) =>\n group.id === groupId\n ? {\n ...group,\n pages: arrayMove(group.pages, draggedIndex, overIndex),\n }\n : group\n )\n}\n\nfunction createPageRangeLabel(pageIds: PageId[]) {\n if (pageIds.length === 0) return "No pages"\n\n return `Pages ${pageIds.map(getPageNumber).join(", ")}`\n}\n\nfunction SplitGroupDropzone({\n children,\n group,\n}: {\n children: React.ReactNode\n group: SplitGroup\n}) {\n const { isOver, setNodeRef } = useDroppable({\n id: group.id,\n data: { type: "page-dropzone", isEmpty: group.pages.length === 0 },\n })\n\n return (\n <div\n ref={setNodeRef}\n className={cn(\n "min-h-[116px] rounded-lg p-2 transition-[background-color,box-shadow]",\n isOver && "bg-accent/30 shadow-[inset_0_0_0_1px_var(--border)]"\n )}\n >\n {children}\n </div>\n )\n}\n\nfunction PageThumbnail({\n imageUrl,\n onSelect,\n pageId,\n}: {\n imageUrl?: string\n onSelect: (pageNumber: number) => void\n pageId: PageId\n}) {\n const pageNumber = getPageNumber(pageId)\n const {\n attributes,\n isDragging,\n listeners,\n setNodeRef,\n transform,\n transition,\n } = useSortable({\n id: pageId,\n data: { type: "page" },\n })\n\n return (\n <button\n ref={setNodeRef}\n type="button"\n className={cn(\n "relative shrink-0 cursor-grab overflow-hidden rounded-md border border-border bg-muted text-left shadow-xs transition-[border-color,opacity] hover:border-foreground/30 active:cursor-grabbing",\n isDragging && "opacity-0"\n )}\n style={{\n width: THUMBNAIL_WIDTH,\n height: THUMBNAIL_HEIGHT,\n transform: CSS.Transform.toString(transform),\n transition,\n }}\n onClick={() => onSelect(pageNumber)}\n {...attributes}\n {...listeners}\n >\n <FileThumbnail\n file={{\n name: `page-${pageNumber}.pdf`,\n type: "application/pdf",\n }}\n previewImageUrl={imageUrl}\n isLoading={!imageUrl}\n previewClassName="h-full aspect-auto"\n className="size-full rounded-[inherit] border-0"\n />\n <span className="absolute right-1 bottom-1 rounded bg-background/95 px-1.5 py-0.5 text-[10px] font-semibold text-foreground shadow-xs ring-1 ring-border/80">\n {pageNumber}\n </span>\n </button>\n )\n}\n\nfunction SplitGroupCard({\n canRemove,\n group,\n dragHandleProps,\n thumbnailImages,\n onRemove,\n onSelectPage,\n}: {\n canRemove: boolean\n group: SplitGroup\n dragHandleProps?: React.ComponentPropsWithoutRef<"button">\n thumbnailImages: Record<PageId, string>\n onRemove: () => void\n onSelectPage: (pageNumber: number) => void\n}) {\n return (\n <section className="w-full rounded-lg border bg-background">\n <div className="flex items-center justify-between gap-3 border-b p-3">\n <div className="flex min-w-0 items-center gap-2">\n <button\n type="button"\n aria-label={`Reorder ${group.title}`}\n className="inline-flex size-7 shrink-0 cursor-grab items-center justify-center rounded-md text-muted-foreground hover:bg-muted active:cursor-grabbing"\n {...dragHandleProps}\n >\n <HugeiconsIcon icon={DragDropVerticalIcon} className="size-4" />\n </button>\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">{group.title}</div>\n <div className="mt-1 text-xs text-muted-foreground">\n {createPageRangeLabel(group.pages)}\n </div>\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-2">\n <div className="rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">\n {group.pages.length}\n </div>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label={`Remove ${group.title}`}\n disabled={!canRemove}\n onClick={onRemove}\n >\n <HugeiconsIcon icon={Delete02Icon} className="size-4" />\n </Button>\n </div>\n </div>\n <SplitGroupDropzone group={group}>\n {group.pages.length ? (\n <SortableContext\n items={group.pages}\n strategy={horizontalListSortingStrategy}\n >\n <ScrollArea\n className="h-[110px] w-full overflow-hidden"\n orientation="horizontal"\n scrollbarGutter\n scrollbarOverflowOnly\n viewportClassName="overflow-y-hidden"\n >\n <div className="flex w-max gap-2 overflow-y-hidden py-1 pr-6">\n {group.pages.map((pageId) => (\n <PageThumbnail\n key={pageId}\n pageId={pageId}\n imageUrl={thumbnailImages[pageId]}\n onSelect={onSelectPage}\n />\n ))}\n </div>\n </ScrollArea>\n </SortableContext>\n ) : (\n <div className="grid h-[104px] place-items-center rounded-lg bg-muted/35 text-xs text-muted-foreground">\n Drop pages here\n </div>\n )}\n </SplitGroupDropzone>\n </section>\n )\n}\n\nfunction SortableSplitGroupCard({\n canRemove,\n group,\n thumbnailImages,\n onRemove,\n onSelectPage,\n}: {\n canRemove: boolean\n group: SplitGroup\n thumbnailImages: Record<PageId, string>\n onRemove: () => void\n onSelectPage: (pageNumber: number) => void\n}) {\n const {\n attributes,\n isDragging,\n listeners,\n setNodeRef,\n transform,\n transition,\n } = useSortable({\n id: getSplitSortableId(group.id),\n data: { type: "split", groupId: group.id },\n })\n\n return (\n <div\n ref={setNodeRef}\n className={cn("w-full", isDragging && "opacity-0")}\n style={{\n transform: CSS.Transform.toString(transform),\n transition,\n }}\n >\n <SplitGroupCard\n canRemove={canRemove}\n group={group}\n thumbnailImages={thumbnailImages}\n dragHandleProps={{ ...attributes, ...listeners }}\n onRemove={onRemove}\n onSelectPage={onSelectPage}\n />\n </div>\n )\n}\n\nfunction SplitGroupDragOverlay({\n group,\n thumbnailImages,\n width,\n onSelectPage,\n}: {\n group: SplitGroup\n thumbnailImages: Record<PageId, string>\n width?: number\n onSelectPage: (pageNumber: number) => void\n}) {\n return (\n <div\n className="relative z-40 max-w-[calc(100vw-2rem)]"\n style={{ width }}\n >\n <SplitGroupCard\n canRemove={false}\n group={group}\n thumbnailImages={thumbnailImages}\n onRemove={() => {}}\n onSelectPage={onSelectPage}\n />\n </div>\n )\n}\n\nexport function DocumentSplits({\n className,\n splits,\n thumbnailImages = {},\n withFrameDivider = true,\n onSelectPage,\n onSplitsChange,\n}: {\n className?: string\n splits: SplitGroup[]\n thumbnailImages?: Record<PageId, string>\n withFrameDivider?: boolean\n onSelectPage: (pageNumber: number) => void\n onSplitsChange: (splits: SplitGroup[]) => void\n}) {\n const [draggedPageId, setDraggedPageId] = React.useState<PageId | null>(null)\n const [activeSplitGroupId, setActiveSplitGroupId] = React.useState<\n string | null\n >(null)\n const [activeSplitGroupWidth, setActiveSplitGroupWidth] = React.useState<\n number | undefined\n >()\n const dragStartGroupIdRef = React.useRef<string | null>(null)\n const dragStartSplitsRef = React.useRef<SplitGroup[] | null>(null)\n const sensors = useSensors(\n useSensor(PointerSensor, { activationConstraint: { distance: 6 } })\n )\n\n const handleDragStart = React.useCallback(\n (event: DragStartEvent) => {\n const dragType = event.active.data.current?.type\n\n if (dragType === "split") {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(\n (event.active.data.current?.groupId as string | undefined) ?? null\n )\n setActiveSplitGroupWidth(event.active.rect.current.initial?.width)\n return\n }\n\n if (dragType !== "page") {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n const pageId = String(event.active.id) as PageId\n dragStartGroupIdRef.current = findGroupId(splits, pageId)\n dragStartSplitsRef.current = splits\n setDraggedPageId(pageId)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n },\n [splits]\n )\n\n const handleDragOver = React.useCallback(\n (event: DragOverEvent) => {\n if (event.active.data.current?.type !== "page" || !event.over) return\n\n const pageId = String(event.active.id) as PageId\n const overId = String(event.over.id)\n\n const sourceGroupId = findGroupId(splits, pageId)\n const targetGroupId = findGroupId(splits, overId)\n\n if (!sourceGroupId || !targetGroupId || sourceGroupId === targetGroupId) {\n return\n }\n\n const targetPages = getGroupPages(splits, targetGroupId)\n const overIndex = targetPages.indexOf(overId as PageId)\n const insertIndex = overIndex === -1 ? targetPages.length : overIndex\n\n const nextSplits = movePageToGroup({\n draggedPageId: pageId,\n groups: splits,\n insertIndex,\n targetGroupId,\n })\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n },\n [onSplitsChange, splits]\n )\n\n const handleDragEnd = React.useCallback(\n (event: DragEndEvent) => {\n if (event.active.data.current?.type === "split" && event.over) {\n const activeGroupId = event.active.data.current.groupId\n const overGroupId = event.over.data.current?.groupId\n\n const draggedIndex = splits.findIndex(\n (group) => group.id === activeGroupId\n )\n const overIndex = splits.findIndex((group) => group.id === overGroupId)\n\n if (draggedIndex !== -1 && overIndex !== -1) {\n const nextSplits = arrayMove(splits, draggedIndex, overIndex)\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n }\n\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n if (event.active.data.current?.type !== "page" || !event.over) {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n const pageId = String(event.active.id) as PageId\n const overId = String(event.over.id) as PageId\n const overGroupId = findGroupId(splits, overId)\n\n if (dragStartGroupIdRef.current === overGroupId) {\n const nextSplits = reorderPageInGroup({\n draggedPageId: pageId,\n groups: splits,\n overPageId: overId,\n })\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n }\n\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n },\n [onSplitsChange, splits]\n )\n\n const handleDragCancel = React.useCallback(() => {\n if (dragStartSplitsRef.current) {\n onSplitsChange(dragStartSplitsRef.current)\n }\n\n dragStartSplitsRef.current = null\n dragStartGroupIdRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n }, [onSplitsChange])\n\n const activeSplitGroup = activeSplitGroupId\n ? splits.find((group) => group.id === activeSplitGroupId)\n : null\n\n return (\n <aside\n className={cn(\n "flex h-full min-h-0 flex-col bg-muted/20",\n withFrameDivider && "border-t md:border-t-0 md:border-l",\n className\n )}\n >\n <div className="flex min-h-12 items-center justify-end gap-3 border-b bg-background px-3">\n <Button\n type="button"\n variant="outline"\n size="sm"\n onClick={() =>\n onSplitsChange([\n ...splits,\n {\n id: `split-${Date.now()}`,\n title: `Split ${splits.length + 1}`,\n pages: [],\n },\n ])\n }\n >\n <HugeiconsIcon icon={Add01Icon} className="size-4" />\n Add split\n </Button>\n </div>\n <DndContext\n id="document-splits-dnd"\n sensors={sensors}\n collisionDetection={splitterCollisionDetection}\n onDragStart={handleDragStart}\n onDragOver={handleDragOver}\n onDragEnd={handleDragEnd}\n onDragCancel={handleDragCancel}\n >\n <ScrollArea className="min-h-0 flex-1" scrollFade>\n <SortableContext\n items={splits.map((group) => getSplitSortableId(group.id))}\n strategy={verticalListSortingStrategy}\n >\n <div className="space-y-3 p-3">\n {splits.map((group) => (\n <SortableSplitGroupCard\n key={group.id}\n canRemove={splits.length > 1}\n group={group}\n thumbnailImages={thumbnailImages}\n onRemove={() => {\n if (splits.length <= 1) return\n onSplitsChange(\n splits.filter((split) => split.id !== group.id)\n )\n }}\n onSelectPage={onSelectPage}\n />\n ))}\n </div>\n </SortableContext>\n </ScrollArea>\n <DragOverlay dropAnimation={DRAG_OVERLAY_DROP_ANIMATION} zIndex={40}>\n {draggedPageId ? (\n <div\n className="relative overflow-hidden rounded-md border bg-background shadow-lg shadow-black/10"\n style={{ width: THUMBNAIL_WIDTH, height: THUMBNAIL_HEIGHT }}\n >\n <FileThumbnail\n file={{ name: `${draggedPageId}.pdf`, type: "application/pdf" }}\n previewImageUrl={thumbnailImages[draggedPageId]}\n isLoading={!thumbnailImages[draggedPageId]}\n previewClassName="h-full aspect-auto"\n className="size-full rounded-[inherit] border-0"\n />\n </div>\n ) : activeSplitGroup ? (\n <SplitGroupDragOverlay\n group={activeSplitGroup}\n thumbnailImages={thumbnailImages}\n width={activeSplitGroupWidth}\n onSelectPage={onSelectPage}\n />\n ) : null}\n </DragOverlay>\n </DndContext>\n </aside>\n )\n}\n'
export function DocumentSplitsSource() {
return (
diff --git a/apps/v4/components/document-viewer-sidebar-docs.tsx b/apps/v4/components/document-viewer-sidebar-docs.tsx
index f6ee684..349c854 100644
--- a/apps/v4/components/document-viewer-sidebar-docs.tsx
+++ b/apps/v4/components/document-viewer-sidebar-docs.tsx
@@ -223,105 +223,8 @@ export function DocumentViewerShell() {
)
}`
-const documentViewerSidebarSourceCode = `"use client"
-
-import * as React from "react"
-
-import { cn } from "@/lib/utils"
-
-const INLINE_THUMBNAIL_SIDEBAR_MIN_WIDTH = 768
-
-export function useElementWidth<TElement extends HTMLElement>() {
- const ref = React.useRef<TElement | null>(null)
- const [width, setWidth] = React.useState(0)
-
- React.useLayoutEffect(() => {
- const element = ref.current
- if (!element) return
-
- const updateWidth = () => {
- setWidth(element.getBoundingClientRect().width)
- }
-
- updateWidth()
-
- const observer = new ResizeObserver(updateWidth)
- observer.observe(element)
-
- return () => observer.disconnect()
- }, [])
-
- return [ref, width] as const
-}
-
-export function useInlineThumbnailSidebar(width: number) {
- return width >= INLINE_THUMBNAIL_SIDEBAR_MIN_WIDTH
-}
-
-export function DocumentViewerThumbnailSidebar({
- children,
- className,
- inline,
- open,
-}: {
- children: React.ReactNode
- className?: string
- inline: boolean
- open: boolean
-}) {
- const [transitionsReady, setTransitionsReady] = React.useState(false)
- const shouldAnimateSidebar = transitionsReady && open
-
- React.useEffect(() => {
- let secondFrameId = 0
- const firstFrameId = window.requestAnimationFrame(() => {
- secondFrameId = window.requestAnimationFrame(() => {
- setTransitionsReady(true)
- })
- })
-
- return () => {
- window.cancelAnimationFrame(firstFrameId)
- window.cancelAnimationFrame(secondFrameId)
- }
- }, [])
-
- return (
- <aside
- data-document-thumbnail-sidebar=""
- data-sidebar-mode={inline ? "inline" : "overlay"}
- data-sidebar-open={open ? "true" : "false"}
- className={cn(
- "absolute inset-y-0 left-0 z-30 w-40 shrink-0 overflow-hidden border-r bg-sidebar shadow-lg",
- shouldAnimateSidebar
- ? "transition-[translate,margin-left,border-color] duration-200 ease-out"
- : "transition-none",
- inline && "relative z-auto translate-x-0 shadow-none",
- open
- ? "ml-0 translate-x-0"
- : inline
- ? "pointer-events-auto -ml-40 border-r-0"
- : "pointer-events-none -translate-x-full border-r-0",
- className
- )}
- >
- {children}
- </aside>
- )
-}
-
-export function DocumentViewerSidebarSkeleton({ inline }: { inline: boolean }) {
- if (!inline) return null
-
- return (
- <div className="w-40 shrink-0 border-r bg-sidebar p-4">
- <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">
- <div className="h-full animate-pulse bg-muted" />
- </div>
- <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />
- </div>
- )
-}`
+const documentViewerSidebarSourceCode =
+ '"use client"\n\nimport * as React from "react"\n\nimport { cn } from "@/lib/utils"\n\nconst INLINE_THUMBNAIL_SIDEBAR_MIN_WIDTH = 768\n\nexport function useElementWidth<TElement extends HTMLElement>() {\n const ref = React.useRef<TElement | null>(null)\n const [width, setWidth] = React.useState(0)\n\n React.useLayoutEffect(() => {\n const element = ref.current\n if (!element) return\n\n const updateWidth = () => {\n setWidth(element.getBoundingClientRect().width)\n }\n\n updateWidth()\n\n const observer = new ResizeObserver(updateWidth)\n observer.observe(element)\n\n return () => observer.disconnect()\n }, [])\n\n return [ref, width] as const\n}\n\nexport function useInlineThumbnailSidebar(width: number) {\n return width >= INLINE_THUMBNAIL_SIDEBAR_MIN_WIDTH\n}\n\nexport function DocumentViewerThumbnailSidebar({\n children,\n className,\n inline,\n open,\n}: {\n children: React.ReactNode\n className?: string\n inline: boolean\n open: boolean\n}) {\n const [transitionsReady, setTransitionsReady] = React.useState(false)\n const shouldAnimateSidebar = transitionsReady && open\n\n React.useEffect(() => {\n let secondFrameId = 0\n const firstFrameId = window.requestAnimationFrame(() => {\n secondFrameId = window.requestAnimationFrame(() => {\n setTransitionsReady(true)\n })\n })\n\n return () => {\n window.cancelAnimationFrame(firstFrameId)\n window.cancelAnimationFrame(secondFrameId)\n }\n }, [])\n\n return (\n <aside\n data-document-thumbnail-sidebar=""\n data-sidebar-mode={inline ? "inline" : "overlay"}\n data-sidebar-open={open ? "true" : "false"}\n className={cn(\n "absolute inset-y-0 left-0 z-30 w-40 shrink-0 overflow-hidden border-r bg-sidebar shadow-lg",\n shouldAnimateSidebar\n ? "transition-[translate,margin-left,border-color] duration-200 ease-out"\n : "transition-none",\n inline && "relative z-auto translate-x-0 shadow-none",\n open\n ? "ml-0 translate-x-0"\n : inline\n ? "pointer-events-auto -ml-40 border-r-0"\n : "pointer-events-none -translate-x-full border-r-0",\n className\n )}\n >\n {children}\n </aside>\n )\n}\n\nexport function DocumentViewerSidebarSkeleton({ inline }: { inline: boolean }) {\n if (!inline) return null\n\n return (\n <div className="w-40 shrink-0 border-r bg-sidebar p-4">\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </div>\n )\n}\n'
export function DocumentViewerSidebarSource() {
return (
diff --git a/apps/v4/components/file-system-source-code.tsx b/apps/v4/components/file-system-source-code.tsx
index a774972..259d6ce 100644
--- a/apps/v4/components/file-system-source-code.tsx
+++ b/apps/v4/components/file-system-source-code.tsx
@@ -5,7 +5,7 @@ import { DocsSourceCodeBlock } from "@/components/docs-code-block"
// Generated from components/ui/file-system.tsx — keep in sync when the
// component changes.
export const fileSystemSourceCode =
- '"use client"\n\nimport * as React from "react"\nimport {\n ArrowLeft01Icon,\n ArrowRight01Icon,\n Cancel01Icon,\n File01Icon,\n GalleryThumbnailsIcon,\n GridViewIcon,\n LayoutThreeColumnIcon,\n LeftToRightListBulletIcon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { prepareFileTreeInput } from "@pierre/trees"\nimport { FileTree as PierreFileTree, useFileTree } from "@pierre/trees/react"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogTitle,\n} from "@/components/ui/dialog"\nimport { DocxViewerPreview } from "@/components/ui/docx-viewer"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { PDFViewer } from "@/components/ui/pdf-viewer"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"\nimport { XlsxViewerPreview } from "@/components/ui/xlsx-viewer"\n\nexport type FileSystemView = "icons" | "list" | "columns" | "gallery"\n\nexport type FileSystemFolderItem = {\n kind: "folder"\n /** Folder prefix, e.g. `"invoices/2026/"`. A trailing slash is added when missing. */\n path: string\n name?: string\n parentPath?: string\n /** Set when children exist but are not in `items` yet; enables `loadChildren`. */\n hasChildren?: boolean\n createdAt?: string\n updatedAt?: string\n}\n\nexport type FileSystemFileItem = {\n kind: "file"\n /** Display/canonical path, e.g. `"invoices/2026/jan.pdf"`. */\n path: string\n /** Original object key (S3/R2). Defaults to `path`. */\n key?: string\n name?: string\n parentPath?: string\n contentType?: string\n size?: number\n createdAt?: string\n updatedAt?: string\n etag?: string\n /** Optional if already public/presigned. Otherwise resolved via `getFileUrl`. */\n url?: string\n /** Externally generated thumbnail. The component never renders documents itself. */\n previewImageUrl?: string | null\n /**\n * Externally generated page thumbnails (first entry is the cover). When a\n * file has more than one page, large thumbnails show a hover pager.\n */\n previewImageUrls?: string[] | null\n /**\n * Total page count when it exceeds `previewImageUrls.length`; the pager\n * loads the remaining pages on demand via `loadPreviewImageUrl`.\n */\n previewPageCount?: number\n /** Thumbnail aspect ratio (width / height). Defaults to a portrait page. */\n previewAspectRatio?: number\n metadata?: Record<string, string>\n}\n\nexport type FileSystemItem = FileSystemFolderItem | FileSystemFileItem\n\nexport type FileSystemLoadChildrenArgs = {\n path: string\n cursor: string | null\n}\n\nexport type FileSystemLoadChildrenResult = {\n items: FileSystemItem[]\n nextCursor?: string | null\n}\n\nexport type FileSystemProps = {\n /** Flat manifest. Folders are optional; missing prefixes are inferred from file paths. */\n items: FileSystemItem[]\n className?: string\n /** Label for the root folder. */\n title?: string\n defaultView?: FileSystemView\n view?: FileSystemView\n onViewChange?: (view: FileSystemView) => void\n /** Folder prefix to open initially, e.g. `"invoices/"`. */\n defaultPath?: string\n onSelectionChange?: (item: FileSystemItem | null) => void\n /**\n * Called on file open (double-click), replacing the built-in behavior. By\n * default PDF, DOCX, XLSX, and image files open in a viewer dialog and\n * other files open their resolved URL in a new tab.\n */\n onFileOpen?: (file: FileSystemFileItem, url: string | null) => void\n /** Resolve a URL (e.g. presigned) for a file without one. */\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n /** Lazily fetch children for folders with `hasChildren` and no loaded entries. */\n loadChildren?: (\n args: FileSystemLoadChildrenArgs\n ) => Promise<FileSystemLoadChildrenResult>\n /** Custom preview node for files without `previewImageUrl`. */\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n /**\n * Lazily render a page thumbnail beyond the eagerly provided\n * `previewImageUrls` (the pager calls this as pages come into view).\n */\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n}\n\ntype FolderEntry = FileSystemFolderItem & {\n name: string\n parentPath: string\n}\n\ntype FileEntry = FileSystemFileItem & {\n key: string\n name: string\n parentPath: string\n}\n\ntype FileSystemEntry = FolderEntry | FileEntry\n\ntype FileSystemIndex = {\n children: Map<string, FileSystemEntry[]>\n files: Map<string, FileEntry>\n folders: Map<string, FolderEntry>\n}\n\nfunction normalizeFolderPath(path: string) {\n if (!path || path === "/") return ""\n return path.endsWith("/") ? path : `${path}/`\n}\n\nfunction pathName(path: string) {\n const trimmed = path.endsWith("/") ? path.slice(0, -1) : path\n const separatorIndex = trimmed.lastIndexOf("/")\n return separatorIndex === -1 ? trimmed : trimmed.slice(separatorIndex + 1)\n}\n\nfunction pathParent(path: string) {\n const trimmed = path.endsWith("/") ? path.slice(0, -1) : path\n const separatorIndex = trimmed.lastIndexOf("/")\n return separatorIndex === -1 ? "" : trimmed.slice(0, separatorIndex + 1)\n}\n\nfunction fileExtension(name: string) {\n const dotIndex = name.lastIndexOf(".")\n return dotIndex === -1 ? "" : name.slice(dotIndex + 1).toLowerCase()\n}\n\nconst FILE_KIND_LABELS: Record<string, string> = {\n csv: "CSV Document",\n doc: "Word Document",\n docx: "Word Document",\n gif: "GIF Image",\n jpeg: "JPEG Image",\n jpg: "JPEG Image",\n md: "Markdown Document",\n pdf: "PDF Document",\n png: "PNG Image",\n ppt: "PowerPoint Presentation",\n pptx: "PowerPoint Presentation",\n svg: "SVG Image",\n tsv: "TSV Document",\n txt: "Plain Text",\n webp: "WebP Image",\n xls: "Excel Workbook",\n xlsx: "Excel Workbook",\n zip: "ZIP Archive",\n}\n\nfunction fileKindLabel(file: FileEntry) {\n const byExtension = FILE_KIND_LABELS[fileExtension(file.name)]\n\n if (byExtension) return byExtension\n if (file.contentType?.startsWith("image/")) return "Image"\n\n return file.contentType ?? "Document"\n}\n\nexport type FileSystemViewerKind = "docx" | "image" | "pdf" | "xlsx"\n\nfunction viewerKindForFile(\n file: FileSystemFileItem\n): FileSystemViewerKind | null {\n if (file.contentType?.startsWith("image/")) return "image"\n if (file.contentType === "application/pdf") return "pdf"\n\n const name = (file.name ?? file.path).toLowerCase()\n\n if (name.endsWith(".pdf")) return "pdf"\n if (name.endsWith(".docx")) return "docx"\n if (name.endsWith(".xlsx")) return "xlsx"\n if (/\\.(avif|gif|jpe?g|png|svg|webp)$/.test(name)) return "image"\n\n return null\n}\n\n// PDF and DOCX pages want height; spreadsheets want width; images get a\n// roomy but contained frame.\nconst VIEWER_DIALOG_CLASSNAMES: Record<FileSystemViewerKind, string> = {\n docx: "h-[88vh] w-[min(96vw,68rem)] max-w-none",\n image: "max-h-[88vh] w-fit max-w-[min(96vw,64rem)]",\n pdf: "h-[88vh] w-[min(96vw,68rem)] max-w-none",\n xlsx: "h-[85vh] w-[min(96vw,100rem)] max-w-none",\n}\n\nfunction formatByteSize(size: number | undefined) {\n if (size === undefined) return null\n if (size < 1000) return `${size} bytes`\n\n const units = ["KB", "MB", "GB", "TB"]\n let value = size\n\n for (const unit of units) {\n value /= 1000\n if (value < 1000 || unit === "TB") {\n return `${value >= 100 ? Math.round(value) : value.toFixed(value >= 10 ? 1 : 2).replace(/\\.?0+$/, "")} ${unit}`\n }\n }\n\n return null\n}\n\nfunction formatTimestamp(value: string | undefined) {\n if (!value) return null\n\n const date = new Date(value)\n\n if (Number.isNaN(date.getTime())) return null\n\n const day = date.toLocaleDateString("en-US", {\n day: "numeric",\n month: "short",\n year: "numeric",\n })\n const time = date.toLocaleTimeString("en-US", {\n hour: "numeric",\n minute: "2-digit",\n })\n\n return `${day} at ${time}`\n}\n\nfunction buildFileSystemIndex(items: FileSystemItem[]): FileSystemIndex {\n const folders = new Map<string, FolderEntry>()\n const files = new Map<string, FileEntry>()\n\n const ensureFolderChain = (folderPath: string) => {\n let path = normalizeFolderPath(folderPath)\n\n while (path && !folders.has(path)) {\n folders.set(path, {\n kind: "folder",\n name: pathName(path),\n parentPath: pathParent(path),\n path,\n })\n path = pathParent(path)\n }\n }\n\n for (const item of items) {\n if (item.kind === "folder") {\n const path = normalizeFolderPath(item.path)\n\n if (!path) continue\n\n folders.set(path, {\n ...item,\n name: item.name ?? pathName(path),\n parentPath: normalizeFolderPath(item.parentPath ?? pathParent(path)),\n path,\n })\n ensureFolderChain(pathParent(path))\n } else {\n if (!item.path) continue\n\n files.set(item.path, {\n ...item,\n key: item.key ?? item.path,\n name: item.name ?? pathName(item.path),\n parentPath: normalizeFolderPath(\n item.parentPath ?? pathParent(item.path)\n ),\n })\n ensureFolderChain(pathParent(item.path))\n }\n }\n\n const children = new Map<string, FileSystemEntry[]>()\n const pushChild = (entry: FileSystemEntry) => {\n const siblings = children.get(entry.parentPath)\n\n if (siblings) {\n siblings.push(entry)\n } else {\n children.set(entry.parentPath, [entry])\n }\n }\n\n for (const folder of folders.values()) pushChild(folder)\n for (const file of files.values()) pushChild(file)\n for (const siblings of children.values()) {\n siblings.sort((left, right) =>\n left.name.localeCompare(right.name, undefined, {\n numeric: true,\n sensitivity: "base",\n })\n )\n }\n\n return { children, files, folders }\n}\n\nfunction folderHasChildren(index: FileSystemIndex, folder: FolderEntry) {\n return (\n (index.children.get(folder.path)?.length ?? 0) > 0 ||\n folder.hasChildren === true\n )\n}\n\n// A single SVG source so the same glyph renders as a React element, inside the\n// @pierre/trees shadow DOM (via CSS url()), and stays pixel-identical in both.\nconst FOLDER_GLYPH_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 50" width="64" height="50"><defs><linearGradient id="fs-folder-back" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#3dabf5"/><stop offset="1" stop-color="#1d84dd"/></linearGradient><linearGradient id="fs-folder-front" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#7accfb"/><stop offset="1" stop-color="#37a0ef"/></linearGradient></defs><path d="M5 10c0-3.31 2.69-6 6-6h10.9c1.6 0 3.13.7 4.18 1.9l1.5 1.73a3.5 3.5 0 0 0 2.64 1.22H54c2.76 0 5 2.24 5 5V40c0 3.87-3.13 7-7 7H12c-3.87 0-7-3.13-7-7V10Z" fill="url(#fs-folder-back)"/><path d="M5 15.5h54V40c0 3.87-3.13 7-7 7H12c-3.87 0-7-3.13-7-7V15.5Z" fill="url(#fs-folder-front)"/></svg>`\n\nconst FOLDER_GLYPH_DATA_URL = `data:image/svg+xml,${encodeURIComponent(FOLDER_GLYPH_SVG)}`\n\nfunction FileSystemFolderGlyph({ className }: { className?: string }) {\n return (\n <img\n src={FOLDER_GLYPH_DATA_URL}\n alt=""\n aria-hidden="true"\n draggable={false}\n className={className}\n />\n )\n}\n\nfunction escapeXmlAttribute(value: string) {\n return value\n .replaceAll("&", "&amp;")\n .replaceAll("<", "&lt;")\n .replaceAll(">", "&gt;")\n .replaceAll(\'"\', "&quot;")\n}\n\nfunction FileGenericPreview({ file }: { file: FileEntry }) {\n const extension = fileExtension(file.name)\n\n return (\n <div className="flex size-full flex-col items-center justify-center gap-1.5 bg-white text-neutral-400 dark:bg-neutral-100">\n <HugeiconsIcon icon={File01Icon} className="size-1/3 min-h-4 min-w-4" />\n {extension ? (\n <span className="text-[min(0.625rem,18cqw)] font-semibold tracking-wide uppercase">\n {extension}\n </span>\n ) : null}\n </div>\n )\n}\n\nfunction filePreviewUrls(file: FileSystemFileItem) {\n if (file.previewImageUrls?.length) return file.previewImageUrls\n return file.previewImageUrl ? [file.previewImageUrl] : []\n}\n\n// djb2 — cheap stable hash for remount keys derived from path lists.\nfunction hashString(value: string) {\n let hash = 5381\n\n for (let index = 0; index < value.length; index += 1) {\n hash = ((hash << 5) + hash + value.charCodeAt(index)) | 0\n }\n return hash\n}\n\nfunction FileVisual({\n file,\n className,\n loadPreviewImageUrl,\n pageable = false,\n previewAspectRatio,\n previewClassName,\n renderFilePreview,\n}: {\n file: FileEntry\n className?: string\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n /** Show a hover pager over multi-page thumbnails. */\n pageable?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n}) {\n const previewUrls = filePreviewUrls(file)\n const canLoadLazily = pageable && Boolean(loadPreviewImageUrl)\n const totalPages = Math.max(\n previewUrls.length,\n canLoadLazily ? (file.previewPageCount ?? 0) : 0\n )\n const [pageIndex, setPageIndex] = React.useState(0)\n const [lazyPageUrls, setLazyPageUrls] = React.useState<\n Record<number, string>\n >({})\n const clampedPageIndex = Math.min(pageIndex, Math.max(totalPages - 1, 0))\n const previewUrl =\n previewUrls[clampedPageIndex] ?? lazyPageUrls[clampedPageIndex] ?? null\n const resolvedAspectRatio = file.previewAspectRatio ?? previewAspectRatio\n const isLazyPagePending =\n canLoadLazily && !previewUrl && clampedPageIndex < totalPages\n\n const fileRef = React.useRef(file)\n\n React.useEffect(() => {\n fileRef.current = file\n })\n\n React.useEffect(() => {\n setPageIndex(0)\n setLazyPageUrls({})\n }, [file.path])\n\n // Keyed by path (not object identity) so manifest churn doesn\'t re-request\n // the page already being loaded.\n React.useEffect(() => {\n if (!isLazyPagePending || !loadPreviewImageUrl) return\n\n let isCurrent = true\n\n void loadPreviewImageUrl(fileRef.current, clampedPageIndex)\n .then((url) => {\n if (isCurrent && url) {\n setLazyPageUrls((previous) => ({\n ...previous,\n [clampedPageIndex]: url,\n }))\n }\n })\n .catch(() => {})\n\n return () => {\n isCurrent = false\n }\n }, [clampedPageIndex, file.path, isLazyPagePending, loadPreviewImageUrl])\n\n const customPreview =\n !previewUrl && !isLazyPagePending ? renderFilePreview?.(file) : null\n const showPager = pageable && totalPages > 1\n const thumbnail = (\n <FileThumbnail\n file={{ name: file.name, type: file.contentType ?? "" }}\n className={cn("@container", !showPager && className)}\n previewAspectRatio={resolvedAspectRatio}\n previewClassName={cn("bg-white dark:bg-neutral-100", previewClassName)}\n previewImageUrl={previewUrl ?? undefined}\n isLoading={isLazyPagePending}\n previewContent={\n previewUrl || isLazyPagePending\n ? undefined\n : (customPreview ?? <FileGenericPreview file={file} />)\n }\n />\n )\n\n if (!showPager) return thumbnail\n\n return (\n <div className={cn("group/pager relative", className)}>\n {thumbnail}\n <div className="absolute inset-x-0 bottom-1.5 flex items-center justify-center gap-1 opacity-0 transition-opacity group-focus-within/pager:opacity-100 group-hover/pager:opacity-100">\n <button\n type="button"\n aria-label="Previous page"\n disabled={clampedPageIndex === 0}\n onClick={(event) => {\n event.stopPropagation()\n setPageIndex((previous) => Math.max(0, previous - 1))\n }}\n onDoubleClick={(event) => event.stopPropagation()}\n className="flex size-6 items-center justify-center rounded-md bg-background/80 text-foreground shadow-xs backdrop-blur-sm transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />\n </button>\n <span className="rounded-md bg-background/80 px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground tabular-nums shadow-xs backdrop-blur-sm">\n {clampedPageIndex + 1}/{totalPages}\n </span>\n <button\n type="button"\n aria-label="Next page"\n disabled={clampedPageIndex >= totalPages - 1}\n onClick={(event) => {\n event.stopPropagation()\n setPageIndex((previous) => Math.min(totalPages - 1, previous + 1))\n }}\n onDoubleClick={(event) => event.stopPropagation()}\n className="flex size-6 items-center justify-center rounded-md bg-background/80 text-foreground shadow-xs backdrop-blur-sm transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-3.5" />\n </button>\n </div>\n </div>\n )\n}\n\nconst VIEW_OPTIONS: Array<{\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n label: string\n value: FileSystemView\n}> = [\n { icon: GridViewIcon, label: "Grid", value: "icons" },\n { icon: LeftToRightListBulletIcon, label: "List", value: "list" },\n { icon: LayoutThreeColumnIcon, label: "Columns", value: "columns" },\n { icon: GalleryThumbnailsIcon, label: "Gallery", value: "gallery" },\n]\n\nexport function FileSystem({\n items,\n className,\n title = "Files",\n defaultView = "icons",\n view: viewProp,\n onViewChange,\n defaultPath = "",\n onSelectionChange,\n onFileOpen,\n getFileUrl,\n loadChildren,\n loadPreviewImageUrl,\n renderFilePreview,\n}: FileSystemProps) {\n const [internalView, setInternalView] = React.useState(defaultView)\n const view = viewProp ?? internalView\n const setView = React.useCallback(\n (nextView: FileSystemView) => {\n setInternalView(nextView)\n onViewChange?.(nextView)\n },\n [onViewChange]\n )\n\n const [loadedItems, setLoadedItems] = React.useState<FileSystemItem[]>([])\n const allItems = React.useMemo(\n () => (loadedItems.length ? [...items, ...loadedItems] : items),\n [items, loadedItems]\n )\n const index = React.useMemo(() => buildFileSystemIndex(allItems), [allItems])\n\n const [history, setHistory] = React.useState(() => ({\n index: 0,\n stack: [normalizeFolderPath(defaultPath)],\n }))\n const currentPath = history.stack[history.index] ?? ""\n const canGoBack = history.index > 0\n const canGoForward = history.index < history.stack.length - 1\n\n const [selectedPath, setSelectedPath] = React.useState<string | null>(null)\n const selectedEntry = React.useMemo(() => {\n if (selectedPath === null) return null\n\n return (\n index.files.get(selectedPath) ?? index.folders.get(selectedPath) ?? null\n )\n }, [index, selectedPath])\n\n const selectEntry = React.useCallback(\n (entry: FileSystemEntry | null) => {\n setSelectedPath(entry?.path ?? null)\n onSelectionChange?.(entry)\n },\n [onSelectionChange]\n )\n\n // Below this width the tabs view switcher no longer fits in the toolbar.\n const rootRef = React.useRef<HTMLDivElement | null>(null)\n const [isCompact, setIsCompact] = React.useState(false)\n\n React.useEffect(() => {\n const root = rootRef.current\n\n if (!root || typeof ResizeObserver === "undefined") return\n\n const observer = new ResizeObserver((observerEntries) => {\n const width = observerEntries[0]?.contentRect.width\n\n if (width !== undefined) setIsCompact(width < 480)\n })\n\n observer.observe(root)\n return () => observer.disconnect()\n }, [])\n\n const requestedFoldersRef = React.useRef(new Set<string>())\n const [loadingFolders, setLoadingFolders] = React.useState<Set<string>>(\n () => new Set()\n )\n const ensureChildren = React.useCallback(\n (folderPath: string) => {\n if (!loadChildren) return\n\n const folder = index.folders.get(folderPath)\n\n if (!folder?.hasChildren) return\n if (index.children.get(folderPath)?.length) return\n if (requestedFoldersRef.current.has(folderPath)) return\n\n requestedFoldersRef.current.add(folderPath)\n setLoadingFolders((previous) => new Set(previous).add(folderPath))\n\n void (async () => {\n try {\n let cursor: string | null = null\n\n do {\n const result = await loadChildren({ cursor, path: folderPath })\n\n if (result.items.length) {\n setLoadedItems((previous) => [...previous, ...result.items])\n }\n cursor = result.nextCursor ?? null\n } while (cursor)\n } catch {\n requestedFoldersRef.current.delete(folderPath)\n } finally {\n setLoadingFolders((previous) => {\n const next = new Set(previous)\n\n next.delete(folderPath)\n return next\n })\n }\n })()\n },\n [index, loadChildren]\n )\n\n const navigateTo = React.useCallback(\n (folderPath: string) => {\n const path = normalizeFolderPath(folderPath)\n\n setHistory((previous) => {\n if (previous.stack[previous.index] === path) return previous\n\n const stack = [...previous.stack.slice(0, previous.index + 1), path]\n\n return { index: stack.length - 1, stack }\n })\n selectEntry(null)\n ensureChildren(path)\n },\n [ensureChildren, selectEntry]\n )\n\n React.useEffect(() => {\n ensureChildren(currentPath)\n }, [currentPath, ensureChildren])\n\n // Navigation unmounts the focused row, dropping focus to <body> and killing\n // the ⌘ shortcuts; reclaim focus onto the component root when that happens.\n const hasNavigatedRef = React.useRef(false)\n\n React.useEffect(() => {\n if (!hasNavigatedRef.current) {\n hasNavigatedRef.current = true\n return\n }\n\n const root = rootRef.current\n\n if (root && document.activeElement === document.body) {\n root.focus()\n }\n }, [currentPath])\n\n const [openedFile, setOpenedFile] = React.useState<{\n file: FileEntry\n kind: FileSystemViewerKind\n url: string\n } | null>(null)\n\n const openFile = React.useCallback(\n (file: FileEntry) => {\n void (async () => {\n let url = file.url ?? null\n\n if (!url && getFileUrl) {\n try {\n url = await getFileUrl(file)\n } catch {\n url = null\n }\n }\n if (onFileOpen) {\n onFileOpen(file, url)\n return\n }\n\n const kind = viewerKindForFile(file)\n\n if (kind && url) {\n setOpenedFile({ file, kind, url })\n } else if (url && typeof window !== "undefined") {\n window.open(url, "_blank", "noopener,noreferrer")\n }\n })()\n },\n [getFileUrl, onFileOpen]\n )\n\n const openEntry = React.useCallback(\n (entry: FileSystemEntry) => {\n if (entry.kind === "folder") {\n navigateTo(entry.path)\n } else {\n openFile(entry)\n }\n },\n [navigateTo, openFile]\n )\n\n // Selecting a lazy folder (columns view, keyboard nav) prefetches children.\n const selectAndPrefetchEntry = React.useCallback(\n (entry: FileSystemEntry | null) => {\n selectEntry(entry)\n if (entry?.kind === "folder") ensureChildren(entry.path)\n },\n [ensureChildren, selectEntry]\n )\n\n const goBack = React.useCallback(() => {\n setHistory((previous) => ({\n ...previous,\n index: Math.max(0, previous.index - 1),\n }))\n selectEntry(null)\n }, [selectEntry])\n\n const goForward = React.useCallback(() => {\n setHistory((previous) => ({\n ...previous,\n index: Math.min(previous.stack.length - 1, previous.index + 1),\n }))\n selectEntry(null)\n }, [selectEntry])\n\n // Finder shortcuts: ⌘↑ encloses, ⌘↓ opens the selection, ⌘[ / ⌘] navigate\n // history. Fires for keydown anywhere inside the component — including the\n // portaled viewer dialog (React events propagate through portals), so bail\n // while a file is open.\n const handleRootKeyDown = (event: React.KeyboardEvent) => {\n if (openedFile) return\n if (!(event.metaKey || event.ctrlKey)) return\n\n if (event.key === "ArrowUp") {\n if (currentPath === "") return\n navigateTo(pathParent(currentPath))\n } else if (event.key === "ArrowDown") {\n if (!selectedEntry) return\n openEntry(selectedEntry)\n } else if (event.key === "[") {\n if (!canGoBack) return\n goBack()\n } else if (event.key === "]") {\n if (!canGoForward) return\n goForward()\n } else {\n return\n }\n event.preventDefault()\n }\n\n const currentEntries = index.children.get(currentPath) ?? []\n const currentFolderName =\n currentPath === "" ? title : pathName(currentPath) || title\n const isLoadingCurrentFolder = loadingFolders.has(currentPath)\n\n const viewProps: FileSystemViewProps = {\n currentPath,\n entries: currentEntries,\n getFileUrl,\n index,\n loadPreviewImageUrl,\n loadingFolders,\n onOpen: openEntry,\n onSelect: selectAndPrefetchEntry,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n }\n\n const openedFileName = openedFile\n ? (openedFile.file.name ?? openedFile.file.path)\n : ""\n const activeViewOption = VIEW_OPTIONS.find((option) => option.value === view)\n const viewerCloseToolbarAction = (\n <DialogClose\n aria-label="Close preview"\n render={<Button type="button" variant="ghost" size="icon-sm" />}\n >\n <HugeiconsIcon icon={Cancel01Icon} className="size-4" />\n </DialogClose>\n )\n\n return (\n <div\n ref={rootRef}\n tabIndex={-1}\n onKeyDown={handleRootKeyDown}\n className={cn(\n "flex h-[480px] min-h-0 flex-col overflow-hidden rounded-xl border bg-background text-foreground outline-none",\n className\n )}\n >\n <div className="grid h-12 shrink-0 grid-cols-[1fr_auto_1fr] items-center gap-2 border-b bg-muted/40 px-2">\n <div className="flex min-w-0 items-center gap-0.5">\n <button\n type="button"\n aria-label="Back"\n title="Back (⌘[)"\n disabled={!canGoBack}\n onClick={goBack}\n className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4.5" />\n </button>\n <button\n type="button"\n aria-label="Forward"\n title="Forward (⌘])"\n disabled={!canGoForward}\n onClick={goForward}\n className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-4.5" />\n </button>\n <span className="ml-1.5 truncate text-sm font-semibold">\n {currentFolderName}\n </span>\n </div>\n {isCompact ? (\n <Select\n value={view}\n onValueChange={(value) => setView(value as FileSystemView)}\n >\n <SelectTrigger size="sm" aria-label="View" className="min-w-32">\n <SelectValue>\n {activeViewOption ? (\n <span className="flex items-center gap-2">\n <HugeiconsIcon\n icon={activeViewOption.icon}\n className="size-4"\n />\n {activeViewOption.label}\n </span>\n ) : null}\n </SelectValue>\n </SelectTrigger>\n <SelectContent>\n {VIEW_OPTIONS.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n <span className="flex items-center gap-2">\n <HugeiconsIcon icon={option.icon} className="size-4" />\n {option.label}\n </span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : (\n <Tabs\n value={view}\n onValueChange={(value) => setView(value as FileSystemView)}\n className="gap-0"\n >\n <TabsList className="h-8 p-0.5">\n {VIEW_OPTIONS.map((option) => (\n <TabsTrigger\n key={option.value}\n value={option.value}\n aria-label={`${option.label} view`}\n title={option.label}\n className="h-7 grow-0 px-2.5 sm:h-7"\n >\n <HugeiconsIcon icon={option.icon} className="size-4" />\n </TabsTrigger>\n ))}\n </TabsList>\n </Tabs>\n )}\n <div />\n </div>\n <div className="relative min-h-0 flex-1">\n {isLoadingCurrentFolder && currentEntries.length === 0 ? (\n <FileSystemEmptyState label="Loading…" isLoading />\n ) : currentEntries.length === 0 && view !== "columns" ? (\n <FileSystemEmptyState label="This folder is empty" />\n ) : view === "icons" ? (\n <FileSystemIconsView {...viewProps} />\n ) : view === "list" ? (\n <FileSystemListView {...viewProps} />\n ) : view === "columns" ? (\n <FileSystemColumnsView {...viewProps} />\n ) : (\n <FileSystemGalleryView {...viewProps} />\n )}\n </div>\n <div\n aria-live="polite"\n className="flex h-7 shrink-0 items-center justify-center gap-1 border-t bg-muted/40 px-3 text-xs text-muted-foreground"\n >\n <span>\n {currentEntries.length}{" "}\n {currentEntries.length === 1 ? "item" : "items"}\n </span>\n {selectedEntry ? <span>· “{selectedEntry.name}” selected</span> : null}\n </div>\n <Dialog\n open={openedFile !== null}\n onOpenChange={(open) => {\n if (!open) setOpenedFile(null)\n }}\n >\n {openedFile ? (\n <DialogContent\n className={cn(\n "overflow-hidden p-0",\n VIEWER_DIALOG_CLASSNAMES[openedFile.kind]\n )}\n showCloseButton={openedFile.kind === "image"}\n >\n <DialogTitle className="sr-only">{openedFileName}</DialogTitle>\n {openedFile.kind === "pdf" ? (\n <PDFViewer\n file={openedFile.url}\n className="h-full min-h-0 flex-1 overflow-hidden rounded-2xl"\n downloadFileName={openedFileName}\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n ) : openedFile.kind === "docx" ? (\n <DocxViewerPreview\n src={openedFile.url}\n fileName={openedFileName}\n className="h-full min-h-0 flex-1"\n rounded\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n ) : openedFile.kind === "xlsx" ? (\n <XlsxViewerPreview\n src={openedFile.url}\n fileName={openedFileName}\n className="h-full min-h-0 flex-1"\n rounded\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n ) : (\n <img\n src={openedFile.url}\n alt={openedFileName}\n className="max-h-[88vh] w-auto max-w-full rounded-2xl object-contain"\n />\n )}\n </DialogContent>\n ) : null}\n </Dialog>\n </div>\n )\n}\n\ntype FileSystemViewProps = {\n currentPath: string\n entries: FileSystemEntry[]\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n index: FileSystemIndex\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n loadingFolders: Set<string>\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n selectedEntry: FileSystemEntry | null\n selectedPath: string | null\n}\n\n// Resolves a display URL for a file: its own `url`, else via `getFileUrl`.\n// Keyed by path/url (not object identity) so manifest churn — e.g. thumbnails\n// streaming in — doesn\'t re-trigger presign calls for the same file.\nfunction useResolvedFileUrl(\n file: FileEntry | null,\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n) {\n const [resolvedUrl, setResolvedUrl] = React.useState<string | null>(\n file?.url ?? null\n )\n const fileRef = React.useRef(file)\n\n React.useEffect(() => {\n fileRef.current = file\n })\n\n const filePath = file?.path ?? null\n const fileUrl = file?.url ?? null\n\n React.useEffect(() => {\n const currentFile = fileRef.current\n\n if (!currentFile || fileUrl) {\n setResolvedUrl(fileUrl)\n return\n }\n if (!getFileUrl) {\n setResolvedUrl(null)\n return\n }\n\n let isCurrent = true\n\n setResolvedUrl(null)\n void Promise.resolve(getFileUrl(currentFile))\n .then((url) => {\n if (isCurrent) setResolvedUrl(url)\n })\n .catch(() => {})\n\n return () => {\n isCurrent = false\n }\n }, [filePath, fileUrl, getFileUrl])\n\n return resolvedUrl\n}\n\nfunction FileSystemEmptyState({\n label,\n isLoading = false,\n}: {\n label: string\n isLoading?: boolean\n}) {\n return (\n <div\n className={cn(\n "flex size-full items-center justify-center text-sm text-muted-foreground",\n isLoading && "animate-pulse motion-reduce:animate-none"\n )}\n >\n {label}\n </div>\n )\n}\n\nconst ARROW_KEYS = new Set(["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"])\n\n// Selects (and focuses) the entry reached by an arrow key. Up/down use row\n// geometry so navigation follows the rendered auto-fill grid.\nfunction moveGridSelection({\n entries,\n itemRefs,\n key,\n onSelect,\n selectedPath,\n}: {\n entries: FileSystemEntry[]\n itemRefs: Map<string, HTMLButtonElement>\n key: string\n onSelect: (entry: FileSystemEntry | null) => void\n selectedPath: string | null\n}) {\n if (entries.length === 0) return false\n\n const currentIndex = entries.findIndex((entry) => entry.path === selectedPath)\n let nextEntry: FileSystemEntry | undefined\n\n if (currentIndex === -1) {\n nextEntry = entries[0]\n } else if (key === "ArrowLeft" || key === "ArrowRight") {\n nextEntry = entries[currentIndex + (key === "ArrowLeft" ? -1 : 1)]\n } else {\n const currentElement = itemRefs.get(entries[currentIndex].path)\n\n if (!currentElement) return false\n\n const currentRect = currentElement.getBoundingClientRect()\n let bestScore = Infinity\n\n for (const entry of entries) {\n if (entry.path === selectedPath) continue\n\n const rect = itemRefs.get(entry.path)?.getBoundingClientRect()\n\n if (!rect) continue\n\n const rowDelta =\n key === "ArrowDown"\n ? rect.top - currentRect.top\n : currentRect.top - rect.top\n\n if (rowDelta <= 1) continue\n\n const score = rowDelta * 1000 + Math.abs(rect.left - currentRect.left)\n\n if (score < bestScore) {\n bestScore = score\n nextEntry = entry\n }\n }\n }\n\n if (!nextEntry) return false\n\n onSelect(nextEntry)\n itemRefs.get(nextEntry.path)?.focus()\n return true\n}\n\nfunction FileSystemIconsView({\n entries,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedPath,\n}: FileSystemViewProps) {\n const itemRefs = React.useRef(new Map<string, HTMLButtonElement>())\n\n return (\n <ScrollArea\n orientation="vertical"\n viewportClassName="p-3"\n viewportProps={{\n onClick: (event) => {\n if (event.target === event.currentTarget) onSelect(null)\n },\n }}\n >\n <div\n role="listbox"\n aria-label="Files"\n className="grid grid-cols-[repeat(auto-fill,minmax(6.5rem,1fr))] gap-x-1 gap-y-3"\n onKeyDown={(event) => {\n if (!ARROW_KEYS.has(event.key)) return\n if (\n moveGridSelection({\n entries,\n itemRefs: itemRefs.current,\n key: event.key,\n onSelect,\n selectedPath,\n })\n ) {\n event.preventDefault()\n }\n }}\n >\n {entries.map((entry) => {\n const isSelected = entry.path === selectedPath\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isSelected}\n ref={(element) => {\n if (element) {\n itemRefs.current.set(entry.path, element)\n } else {\n itemRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n className="group flex flex-col items-center gap-1.5 outline-none"\n >\n <span\n className={cn(\n "flex h-16 w-20 items-center justify-center rounded-lg p-1 transition-colors group-focus-visible:ring-2 group-focus-visible:ring-ring",\n isSelected && "bg-accent"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-13 w-auto drop-shadow-sm" />\n ) : (\n <FileVisual\n file={entry}\n className={cn(\n "rounded-sm shadow-xs",\n // Landscape thumbnails get extra width so they fill\n // the tile instead of rendering as a short sliver.\n (entry.previewAspectRatio ?? 0.78) > 1.2\n ? "w-[4.75rem]"\n : "w-12"\n )}\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )}\n </span>\n <span\n className={cn(\n "max-w-full rounded-sm px-1.5 py-px text-center text-xs leading-tight break-words",\n isSelected\n ? "bg-primary text-primary-foreground"\n : "text-foreground"\n )}\n >\n <span className="line-clamp-2">{entry.name}</span>\n </span>\n </button>\n )\n })}\n </div>\n </ScrollArea>\n )\n}\n\nfunction FileSystemListView({\n currentPath,\n index,\n onOpen,\n onSelect,\n selectedPath,\n}: FileSystemViewProps) {\n const relativePaths = React.useMemo(() => {\n const paths: string[] = []\n\n for (const path of index.files.keys()) {\n if (currentPath === "" || path.startsWith(currentPath)) {\n const relativePath = path.slice(currentPath.length)\n\n if (relativePath) paths.push(relativePath)\n }\n }\n return paths.sort()\n }, [currentPath, index])\n // Content-derived key: the tree only remounts when the path set actually\n // changes (a bare length check misses same-count replacements).\n const treeKey = React.useMemo(\n () => hashString(relativePaths.join("\\n")),\n [relativePaths]\n )\n\n if (relativePaths.length === 0) {\n return <FileSystemEmptyState label="This folder is empty" />\n }\n\n return (\n <div className="flex size-full flex-col">\n {/* Paddings match the tree\'s row geometry: name text starts 46px in\n (16px tree padding + 30px icon lane), metadata ends 24px from the\n right (16px tree padding + 8px decoration inset). */}\n <div className="flex shrink-0 items-center border-b py-1.5 pr-6 pl-[46px] text-xs font-medium text-muted-foreground">\n <span className="flex-1">Name</span>\n <span className="w-44 text-right">Date Modified</span>\n <span className="w-20 text-right">Size</span>\n </div>\n <FileSystemPierreTree\n key={`${currentPath}::${treeKey}`}\n currentPath={currentPath}\n index={index}\n initialSelectedPath={\n selectedPath?.startsWith(currentPath)\n ? selectedPath.slice(currentPath.length).replace(/\\/$/, "")\n : null\n }\n onOpen={onOpen}\n onSelect={onSelect}\n relativePaths={relativePaths}\n />\n </div>\n )\n}\n\nfunction FileSystemPierreTree({\n currentPath,\n index,\n initialSelectedPath,\n onOpen,\n onSelect,\n relativePaths,\n}: {\n currentPath: string\n index: FileSystemIndex\n initialSelectedPath: string | null\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n relativePaths: string[]\n}) {\n const preparedInput = React.useMemo(\n () => prepareFileTreeInput(relativePaths, { sort: "default" }),\n [relativePaths]\n )\n // Inject per-file thumbnails into the tree\'s shadow DOM as sprite symbols\n // wrapping an <image>, remapped onto rows by file basename. The chevron is\n // remapped to the Hugeicons arrow so it matches the rest of the component;\n // the tree\'s rotation CSS keys off data-icon-name, which remapping keeps.\n const icons = React.useMemo(() => {\n const byFileName: Record<string, { name: string; viewBox: string }> = {}\n const symbols: string[] = [\n `<symbol id="file-system-chevron" viewBox="0 0 24 24"><path d="M18 9.00005C18 9.00005 13.5811 15 12 15C10.4188 15 6 9 6 9" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/></symbol>`,\n ]\n\n for (const relativePath of relativePaths) {\n const file = index.files.get(`${currentPath}${relativePath}`)\n const coverUrl = file ? filePreviewUrls(file)[0] : undefined\n\n if (!file || !coverUrl) continue\n\n const baseName = file.name.toLowerCase()\n\n if (byFileName[baseName]) continue\n\n const symbolId = `file-system-thumbnail-${symbols.length}`\n\n symbols.push(\n `<symbol id="${symbolId}" viewBox="0 0 16 16"><clipPath id="${symbolId}-clip"><rect width="16" height="16" rx="2.5"/></clipPath><image href="${escapeXmlAttribute(coverUrl)}" width="16" height="16" preserveAspectRatio="xMidYMid slice" clip-path="url(#${symbolId}-clip)"/></symbol>`\n )\n byFileName[baseName] = { name: symbolId, viewBox: "0 0 16 16" }\n }\n\n return {\n byFileName,\n remap: {\n "file-tree-icon-chevron": {\n name: "file-system-chevron",\n viewBox: "0 0 24 24",\n },\n },\n spriteSheet: `<svg data-icon-sprite aria-hidden="true" width="0" height="0">${symbols.join("")}</svg>`,\n }\n }, [currentPath, index, relativePaths])\n const { model } = useFileTree({\n flattenEmptyDirectories: false,\n icons,\n initialExpansion: "closed",\n initialSelectedPaths: initialSelectedPath ? [initialSelectedPath] : [],\n itemHeight: 28,\n overscan: 12,\n preparedInput,\n renderRowDecoration: ({ row }) => {\n const entry =\n row.kind === "file"\n ? index.files.get(`${currentPath}${row.path}`)\n : index.folders.get(normalizeFolderPath(`${currentPath}${row.path}`))\n\n if (!entry) return null\n\n // The decoration lane renders one <span title>; CSS splits it into\n // aligned Date Modified (::before from title) and Size columns.\n const dateColumn =\n formatTimestamp(entry.updatedAt ?? entry.createdAt) ?? "—"\n\n if (entry.kind === "folder") {\n const childCount = index.children.get(entry.path)?.length\n\n return {\n text:\n childCount === undefined\n ? "—"\n : `${childCount} ${childCount === 1 ? "item" : "items"}`,\n title: dateColumn,\n }\n }\n\n return { text: formatByteSize(entry.size) ?? "—", title: dateColumn }\n },\n unsafeCSS: `\n button[data-type=\'item\']:not([data-item-selected]):hover {\n background: color-mix(in oklab, var(--color-accent) 50%, transparent);\n }\n button[data-type=\'item\'][data-item-selected] {\n background: var(--color-primary);\n color: var(--color-primary-foreground);\n }\n button[data-type=\'item\'][data-item-selected] *,\n button[data-type=\'item\'][data-item-selected] [data-item-section]::before,\n button[data-type=\'item\'][data-item-selected] svg {\n color: var(--color-primary-foreground) !important;\n }\n [data-item-section=\'decoration\'] > span {\n display: grid;\n grid-template-columns: 11rem 5rem;\n justify-items: end;\n white-space: nowrap;\n }\n [data-item-section=\'decoration\'] > span::before {\n content: attr(title);\n }\n button[data-type=\'item\'][data-item-type=\'folder\'] [data-item-section=\'content\'] {\n display: flex;\n align-items: center;\n min-width: 0;\n }\n button[data-type=\'item\'][data-item-type=\'folder\'] [data-item-section=\'content\']::before {\n content: "";\n flex: none;\n width: 18px;\n height: 14px;\n margin-right: 4px;\n background: url("${FOLDER_GLYPH_DATA_URL}") center / contain no-repeat;\n }\n `,\n onSelectionChange: (selectedPaths) => {\n const relativePath = selectedPaths[0]\n\n if (!relativePath) {\n onSelect(null)\n return\n }\n\n const absolutePath = `${currentPath}${relativePath}`\n const entry =\n index.files.get(absolutePath) ??\n index.folders.get(normalizeFolderPath(absolutePath)) ??\n null\n\n onSelect(entry)\n },\n })\n\n // Thumbnails can resolve after mount (e.g. generated client-side); push\n // sprite updates into the existing model instead of remounting the tree.\n React.useEffect(() => {\n model.setIcons(icons)\n }, [icons, model])\n\n return (\n <PierreFileTree\n model={model}\n className="block min-h-0 flex-1"\n onDoubleClick={(event) => {\n // Rows live in the tree\'s shadow DOM; composedPath surfaces the row\n // element so double-clicked files open like in the other views.\n for (const target of event.nativeEvent.composedPath()) {\n if (!(target instanceof HTMLElement)) continue\n const relativePath = target.dataset?.itemPath\n if (!relativePath) continue\n\n const file = index.files.get(`${currentPath}${relativePath}`)\n\n if (file) onOpen(file)\n return\n }\n }}\n style={\n {\n "--trees-bg-override": "transparent",\n "--trees-border-color-override": "var(--color-border)",\n "--trees-fg-override": "var(--color-foreground)",\n "--trees-selected-bg-override": "var(--color-primary)",\n } as React.CSSProperties\n }\n />\n )\n}\n\nfunction FileSystemColumnsView(props: FileSystemViewProps) {\n const {\n currentPath,\n index,\n loadPreviewImageUrl,\n loadingFolders,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n } = props\n const scrollContainerRef = React.useRef<HTMLDivElement | null>(null)\n const rowRefs = React.useRef(new Map<string, HTMLButtonElement>())\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (!ARROW_KEYS.has(event.key)) return\n\n let nextEntry: FileSystemEntry | null | undefined\n\n if (!selectedEntry || !selectedPath?.startsWith(currentPath)) {\n nextEntry = index.children.get(currentPath)?.[0]\n } else if (event.key === "ArrowUp" || event.key === "ArrowDown") {\n const siblings = index.children.get(selectedEntry.parentPath) ?? []\n const currentIndex = siblings.findIndex(\n (sibling) => sibling.path === selectedEntry.path\n )\n\n nextEntry = siblings[currentIndex + (event.key === "ArrowUp" ? -1 : 1)]\n } else if (event.key === "ArrowLeft") {\n if (selectedEntry.parentPath !== currentPath) {\n nextEntry = index.folders.get(selectedEntry.parentPath)\n }\n } else if (selectedEntry.kind === "folder") {\n nextEntry = index.children.get(selectedEntry.path)?.[0]\n }\n\n if (!nextEntry) return\n\n onSelect(nextEntry)\n rowRefs.current.get(nextEntry.path)?.focus()\n event.preventDefault()\n }\n\n const columnPaths = React.useMemo(() => {\n const paths = [currentPath]\n\n if (!selectedPath?.startsWith(currentPath)) return paths\n\n const targetFolder =\n selectedEntry?.kind === "folder"\n ? selectedEntry.path\n : (selectedEntry?.parentPath ?? currentPath)\n const relativePath = targetFolder.slice(currentPath.length)\n let walkedPath = currentPath\n\n for (const segment of relativePath.split("/")) {\n if (!segment) continue\n walkedPath = `${walkedPath}${segment}/`\n paths.push(walkedPath)\n }\n return paths\n }, [currentPath, selectedEntry, selectedPath])\n const columnPathSet = React.useMemo(() => new Set(columnPaths), [columnPaths])\n const selectedFile =\n selectedEntry?.kind === "file" ? (selectedEntry as FileEntry) : null\n const selectedFileSize = selectedFile\n ? formatByteSize(selectedFile.size)\n : null\n\n React.useEffect(() => {\n const container = scrollContainerRef.current\n\n if (container) container.scrollLeft = container.scrollWidth\n }, [columnPaths.length, selectedPath])\n\n return (\n <ScrollArea\n orientation="horizontal"\n viewportRef={scrollContainerRef}\n viewportClassName="overscroll-x-contain"\n >\n <div className="flex h-full w-max min-w-full" onKeyDown={handleKeyDown}>\n {columnPaths.map((columnPath) => (\n <ScrollArea\n key={columnPath || "(root)"}\n orientation="vertical"\n className="w-60 shrink-0 border-r"\n viewportClassName="flex flex-col gap-px p-1.5"\n viewportProps={{ "aria-label": "Files", role: "listbox" }}\n >\n {loadingFolders.has(columnPath) &&\n !index.children.get(columnPath)?.length ? (\n <div className="animate-pulse px-2 py-1.5 text-xs text-muted-foreground motion-reduce:animate-none">\n Loading…\n </div>\n ) : (\n (index.children.get(columnPath) ?? []).map((entry) => {\n const isSelected = entry.path === selectedPath\n const isOnTrail =\n entry.kind === "folder" && columnPathSet.has(entry.path)\n\n const coverUrl =\n entry.kind === "file" ? filePreviewUrls(entry)[0] : undefined\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isSelected}\n ref={(element) => {\n if (element) {\n rowRefs.current.set(entry.path, element)\n } else {\n rowRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n className={cn(\n "flex shrink-0 items-center gap-2 rounded-md px-2 py-1 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",\n isSelected\n ? "bg-primary text-primary-foreground"\n : isOnTrail\n ? "bg-accent"\n : "hover:bg-accent/50"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-3.5 w-auto shrink-0" />\n ) : coverUrl ? (\n <img\n src={coverUrl}\n alt=""\n draggable={false}\n className="size-4 shrink-0 rounded-[3px] bg-white object-cover"\n />\n ) : (\n <HugeiconsIcon\n icon={File01Icon}\n className={cn(\n "size-4 shrink-0",\n !isSelected && "text-muted-foreground"\n )}\n />\n )}\n <span className="min-w-0 flex-1 truncate">\n {entry.name}\n </span>\n {entry.kind === "folder" &&\n folderHasChildren(index, entry) ? (\n <HugeiconsIcon\n icon={ArrowRight01Icon}\n className={cn(\n "size-3.5 shrink-0",\n !isSelected && "text-muted-foreground/60"\n )}\n />\n ) : null}\n </button>\n )\n })\n )}\n </ScrollArea>\n ))}\n {selectedFile ? (\n <ScrollArea\n orientation="vertical"\n className="min-w-72 flex-1"\n viewportClassName="flex justify-center p-4"\n >\n <div className="flex w-full max-w-lg flex-col items-stretch gap-3">\n {/* Width derives from the aspect ratio so the thumbnail grows\n with the pane up to a 20rem height cap. */}\n <div\n className="mx-auto w-full shrink-0"\n style={{\n maxWidth: `min(100%, ${(selectedFile.previewAspectRatio ?? 0.78) * 20}rem)`,\n }}\n >\n <FileVisual\n file={selectedFile}\n className="w-full"\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageable\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n </div>\n <div className="text-center">\n <div className="text-sm font-semibold break-words">\n {selectedFile.name}\n </div>\n <div className="text-xs text-muted-foreground">\n {fileKindLabel(selectedFile)}\n {selectedFileSize ? ` - ${selectedFileSize}` : null}\n </div>\n </div>\n <FileSystemInformation entry={selectedFile} index={index} />\n </div>\n </ScrollArea>\n ) : null}\n </div>\n </ScrollArea>\n )\n}\n\nfunction FileSystemInformation({\n entry,\n index,\n}: {\n entry: FileSystemEntry\n index: FileSystemIndex\n}) {\n const rows: Array<[string, string]> = []\n const created = formatTimestamp(entry.createdAt)\n const updated = formatTimestamp(entry.updatedAt)\n\n if (created) rows.push(["Created", created])\n if (updated) rows.push(["Modified", updated])\n if (entry.kind === "file") {\n const size = formatByteSize(entry.size)\n\n if (size) rows.push(["Size", size])\n } else {\n const childCount = index.children.get(entry.path)?.length\n\n if (childCount !== undefined) {\n rows.push(["Items", `${childCount}`])\n }\n }\n\n if (rows.length === 0) return null\n\n return (\n <div className="border-t pt-3">\n <div className="mb-1.5 text-xs font-semibold">Information</div>\n <dl className="space-y-1">\n {rows.map(([label, value]) => (\n <div\n key={label}\n className="flex items-baseline justify-between gap-3 text-xs"\n >\n <dt className="shrink-0 text-muted-foreground">{label}</dt>\n <dd className="text-right" suppressHydrationWarning>\n {value}\n </dd>\n </div>\n ))}\n </dl>\n </div>\n )\n}\n\nfunction FileSystemGalleryView(props: FileSystemViewProps) {\n const {\n entries,\n getFileUrl,\n index,\n loadPreviewImageUrl,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n } = props\n const stripRefs = React.useRef(new Map<string, HTMLButtonElement>())\n const activeEntry =\n selectedEntry && entries.some((entry) => entry.path === selectedEntry.path)\n ? selectedEntry\n : (entries[0] ?? null)\n const activeFile = activeEntry?.kind === "file" ? activeEntry : null\n const activeViewerKind = activeFile ? viewerKindForFile(activeFile) : null\n const activeFileUrl = useResolvedFileUrl(activeFile, getFileUrl)\n const activeFileSize = activeFile ? formatByteSize(activeFile.size) : null\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return\n if (entries.length === 0) return\n\n const currentIndex = activeEntry\n ? entries.findIndex((entry) => entry.path === activeEntry.path)\n : -1\n const nextEntry =\n entries[\n currentIndex === -1\n ? 0\n : currentIndex + (event.key === "ArrowLeft" ? -1 : 1)\n ]\n\n if (!nextEntry) return\n\n onSelect(nextEntry)\n stripRefs.current.get(nextEntry.path)?.focus()\n event.preventDefault()\n }\n\n return (\n <div className="flex size-full flex-col" onKeyDown={handleKeyDown}>\n <div className="flex min-h-0 flex-1">\n <div className="flex min-h-0 min-w-0 flex-1 items-center justify-center p-3">\n {activeEntry ? (\n activeEntry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-40 max-h-full w-auto drop-shadow-md" />\n ) : activeViewerKind === "image" && activeFileUrl ? (\n <img\n src={activeFileUrl}\n alt={activeEntry.name}\n className="max-h-full max-w-full rounded-lg object-contain"\n />\n ) : activeViewerKind === "pdf" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <PDFViewer\n key={activeEntry.path}\n file={activeFileUrl}\n className="h-full"\n showToolbar={false}\n />\n </div>\n ) : activeViewerKind === "docx" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <DocxViewerPreview\n key={activeEntry.path}\n src={activeFileUrl}\n fileName={activeEntry.name}\n className="h-full"\n showToolbar={false}\n />\n </div>\n ) : activeViewerKind === "xlsx" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <XlsxViewerPreview\n key={activeEntry.path}\n src={activeFileUrl}\n fileName={activeEntry.name}\n className="h-full"\n showToolbar={false}\n />\n </div>\n ) : (\n <FileVisual\n file={activeEntry}\n className="w-56 max-w-full"\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageable\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )\n ) : null}\n </div>\n {activeEntry ? (\n <ScrollArea\n orientation="vertical"\n className="hidden w-64 shrink-0 border-l sm:block"\n viewportClassName="flex flex-col gap-3 p-4"\n >\n <div className="flex items-center gap-3">\n {activeFile ? (\n <FileVisual\n file={activeFile}\n className={cn(\n "shrink-0 rounded-sm",\n (activeFile.previewAspectRatio ?? 0.78) > 1.2\n ? "w-16"\n : "w-9"\n )}\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n ) : (\n <FileSystemFolderGlyph className="h-8 w-auto shrink-0" />\n )}\n <div className="min-w-0 flex-1">\n <div className="text-sm font-semibold break-words">\n {activeEntry.name}\n </div>\n <div className="text-xs text-muted-foreground">\n {activeFile ? fileKindLabel(activeFile) : "Folder"}\n {activeFileSize ? ` - ${activeFileSize}` : null}\n </div>\n </div>\n </div>\n <FileSystemInformation entry={activeEntry} index={index} />\n </ScrollArea>\n ) : null}\n </div>\n <ScrollArea\n orientation="horizontal"\n className="h-auto w-full shrink-0 border-t"\n >\n <div\n role="listbox"\n aria-label="Files"\n className="flex w-max min-w-full items-center gap-1.5 p-2"\n >\n {entries.map((entry) => {\n const isActive = entry.path === (activeEntry?.path ?? selectedPath)\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isActive}\n ref={(element) => {\n if (element) {\n stripRefs.current.set(entry.path, element)\n } else {\n stripRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n title={entry.name}\n className={cn(\n "flex size-14 shrink-0 items-center justify-center rounded-md border border-transparent p-1 outline-none focus-visible:ring-2 focus-visible:ring-ring",\n isActive && "border-ring/40 bg-accent"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-9 w-auto" />\n ) : (\n <FileVisual\n file={entry}\n className="w-9 rounded-sm"\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )}\n </button>\n )\n })}\n </div>\n </ScrollArea>\n </div>\n )\n}\n'
+ '"use client"\n\nimport * as React from "react"\nimport {\n ArrowLeft01Icon,\n ArrowRight01Icon,\n Cancel01Icon,\n File01Icon,\n GalleryThumbnailsIcon,\n GridViewIcon,\n LayoutThreeColumnIcon,\n LeftToRightListBulletIcon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { prepareFileTreeInput } from "@pierre/trees"\nimport { FileTree as PierreFileTree, useFileTree } from "@pierre/trees/react"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogTitle,\n} from "@/components/ui/dialog"\nimport { DocxViewerPreview } from "@/components/ui/docx-viewer"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { PDFViewer } from "@/components/ui/pdf-viewer"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"\nimport { XlsxViewerPreview } from "@/components/ui/xlsx-viewer"\n\nexport type FileSystemView = "icons" | "list" | "columns" | "gallery"\n\nexport type FileSystemFolderItem = {\n kind: "folder"\n /** Folder prefix, e.g. `"invoices/2026/"`. A trailing slash is added when missing. */\n path: string\n name?: string\n parentPath?: string\n /** Set when children exist but are not in `items` yet; enables `loadChildren`. */\n hasChildren?: boolean\n createdAt?: string\n updatedAt?: string\n}\n\nexport type FileSystemFileItem = {\n kind: "file"\n /** Display/canonical path, e.g. `"invoices/2026/jan.pdf"`. */\n path: string\n /** Original object key (S3/R2). Defaults to `path`. */\n key?: string\n name?: string\n parentPath?: string\n contentType?: string\n size?: number\n createdAt?: string\n updatedAt?: string\n etag?: string\n /** Optional if already public/presigned. Otherwise resolved via `getFileUrl`. */\n url?: string\n /** Externally generated thumbnail. The component never renders documents itself. */\n previewImageUrl?: string | null\n /**\n * Externally generated page thumbnails (first entry is the cover). When a\n * file has more than one page, large thumbnails show a hover pager.\n */\n previewImageUrls?: string[] | null\n /**\n * Total page count when it exceeds `previewImageUrls.length`; the pager\n * loads the remaining pages on demand via `loadPreviewImageUrl`.\n */\n previewPageCount?: number\n /** Thumbnail aspect ratio (width / height). Defaults to a portrait page. */\n previewAspectRatio?: number\n metadata?: Record<string, string>\n}\n\nexport type FileSystemItem = FileSystemFolderItem | FileSystemFileItem\n\nexport type FileSystemLoadChildrenArgs = {\n path: string\n cursor: string | null\n}\n\nexport type FileSystemLoadChildrenResult = {\n items: FileSystemItem[]\n nextCursor?: string | null\n}\n\nexport type FileSystemProps = {\n /** Flat manifest. Folders are optional; missing prefixes are inferred from file paths. */\n items: FileSystemItem[]\n className?: string\n /** Label for the root folder. */\n title?: string\n defaultView?: FileSystemView\n view?: FileSystemView\n onViewChange?: (view: FileSystemView) => void\n /** Folder prefix to open initially, e.g. `"invoices/"`. */\n defaultPath?: string\n onSelectionChange?: (item: FileSystemItem | null) => void\n /**\n * Called on file open (double-click), replacing the built-in behavior. By\n * default PDF, DOCX, XLSX, and image files open in a viewer dialog and\n * other files open their resolved URL in a new tab.\n */\n onFileOpen?: (file: FileSystemFileItem, url: string | null) => void\n /** Resolve a URL (e.g. presigned) for a file without one. */\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n /** Lazily fetch children for folders with `hasChildren` and no loaded entries. */\n loadChildren?: (\n args: FileSystemLoadChildrenArgs\n ) => Promise<FileSystemLoadChildrenResult>\n /** Custom preview node for files without `previewImageUrl`. */\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n /**\n * Lazily render a page thumbnail beyond the eagerly provided\n * `previewImageUrls` (the pager calls this as pages come into view).\n */\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n}\n\ntype FolderEntry = FileSystemFolderItem & {\n name: string\n parentPath: string\n}\n\ntype FileEntry = FileSystemFileItem & {\n key: string\n name: string\n parentPath: string\n}\n\ntype FileSystemEntry = FolderEntry | FileEntry\n\ntype FileSystemIndex = {\n children: Map<string, FileSystemEntry[]>\n files: Map<string, FileEntry>\n folders: Map<string, FolderEntry>\n}\n\nfunction normalizeFolderPath(path: string) {\n if (!path || path === "/") return ""\n return path.endsWith("/") ? path : `${path}/`\n}\n\nfunction pathName(path: string) {\n const trimmed = path.endsWith("/") ? path.slice(0, -1) : path\n const separatorIndex = trimmed.lastIndexOf("/")\n return separatorIndex === -1 ? trimmed : trimmed.slice(separatorIndex + 1)\n}\n\nfunction pathParent(path: string) {\n const trimmed = path.endsWith("/") ? path.slice(0, -1) : path\n const separatorIndex = trimmed.lastIndexOf("/")\n return separatorIndex === -1 ? "" : trimmed.slice(0, separatorIndex + 1)\n}\n\nfunction fileExtension(name: string) {\n const dotIndex = name.lastIndexOf(".")\n return dotIndex === -1 ? "" : name.slice(dotIndex + 1).toLowerCase()\n}\n\nconst FILE_KIND_LABELS: Record<string, string> = {\n csv: "CSV Document",\n doc: "Word Document",\n docx: "Word Document",\n gif: "GIF Image",\n jpeg: "JPEG Image",\n jpg: "JPEG Image",\n md: "Markdown Document",\n pdf: "PDF Document",\n png: "PNG Image",\n ppt: "PowerPoint Presentation",\n pptx: "PowerPoint Presentation",\n svg: "SVG Image",\n tsv: "TSV Document",\n txt: "Plain Text",\n webp: "WebP Image",\n xls: "Excel Workbook",\n xlsx: "Excel Workbook",\n zip: "ZIP Archive",\n}\n\nfunction fileKindLabel(file: FileEntry) {\n const byExtension = FILE_KIND_LABELS[fileExtension(file.name)]\n\n if (byExtension) return byExtension\n if (file.contentType?.startsWith("image/")) return "Image"\n\n return file.contentType ?? "Document"\n}\n\nexport type FileSystemViewerKind = "docx" | "image" | "pdf" | "xlsx"\n\nfunction viewerKindForFile(\n file: FileSystemFileItem\n): FileSystemViewerKind | null {\n if (file.contentType?.startsWith("image/")) return "image"\n if (file.contentType === "application/pdf") return "pdf"\n\n const name = (file.name ?? file.path).toLowerCase()\n\n if (name.endsWith(".pdf")) return "pdf"\n if (name.endsWith(".docx")) return "docx"\n if (name.endsWith(".xlsx")) return "xlsx"\n if (/\\.(avif|gif|jpe?g|png|svg|webp)$/.test(name)) return "image"\n\n return null\n}\n\n// PDF and DOCX pages want height; spreadsheets want width; images get a\n// roomy but contained frame.\nconst VIEWER_DIALOG_CLASSNAMES: Record<FileSystemViewerKind, string> = {\n docx: "h-[88vh] w-[min(96vw,68rem)] max-w-none",\n image: "max-h-[88vh] w-fit max-w-[min(96vw,64rem)]",\n pdf: "h-[88vh] w-[min(96vw,68rem)] max-w-none",\n xlsx: "h-[85vh] w-[min(96vw,100rem)] max-w-none",\n}\n\nfunction formatByteSize(size: number | undefined) {\n if (size === undefined) return null\n if (size < 1000) return `${size} bytes`\n\n const units = ["KB", "MB", "GB", "TB"]\n let value = size\n\n for (const unit of units) {\n value /= 1000\n if (value < 1000 || unit === "TB") {\n return `${value >= 100 ? Math.round(value) : value.toFixed(value >= 10 ? 1 : 2).replace(/\\.?0+$/, "")} ${unit}`\n }\n }\n\n return null\n}\n\nfunction formatTimestamp(value: string | undefined) {\n if (!value) return null\n\n const date = new Date(value)\n\n if (Number.isNaN(date.getTime())) return null\n\n const day = date.toLocaleDateString("en-US", {\n day: "numeric",\n month: "short",\n year: "numeric",\n })\n const time = date.toLocaleTimeString("en-US", {\n hour: "numeric",\n minute: "2-digit",\n })\n\n return `${day} at ${time}`\n}\n\nfunction buildFileSystemIndex(items: FileSystemItem[]): FileSystemIndex {\n const folders = new Map<string, FolderEntry>()\n const files = new Map<string, FileEntry>()\n\n const ensureFolderChain = (folderPath: string) => {\n let path = normalizeFolderPath(folderPath)\n\n while (path && !folders.has(path)) {\n folders.set(path, {\n kind: "folder",\n name: pathName(path),\n parentPath: pathParent(path),\n path,\n })\n path = pathParent(path)\n }\n }\n\n for (const item of items) {\n if (item.kind === "folder") {\n const path = normalizeFolderPath(item.path)\n\n if (!path) continue\n\n folders.set(path, {\n ...item,\n name: item.name ?? pathName(path),\n parentPath: normalizeFolderPath(item.parentPath ?? pathParent(path)),\n path,\n })\n ensureFolderChain(pathParent(path))\n } else {\n if (!item.path) continue\n\n files.set(item.path, {\n ...item,\n key: item.key ?? item.path,\n name: item.name ?? pathName(item.path),\n parentPath: normalizeFolderPath(\n item.parentPath ?? pathParent(item.path)\n ),\n })\n ensureFolderChain(pathParent(item.path))\n }\n }\n\n const children = new Map<string, FileSystemEntry[]>()\n const pushChild = (entry: FileSystemEntry) => {\n const siblings = children.get(entry.parentPath)\n\n if (siblings) {\n siblings.push(entry)\n } else {\n children.set(entry.parentPath, [entry])\n }\n }\n\n for (const folder of folders.values()) pushChild(folder)\n for (const file of files.values()) pushChild(file)\n for (const siblings of children.values()) {\n siblings.sort((left, right) =>\n left.name.localeCompare(right.name, undefined, {\n numeric: true,\n sensitivity: "base",\n })\n )\n }\n\n return { children, files, folders }\n}\n\nfunction folderHasChildren(index: FileSystemIndex, folder: FolderEntry) {\n return (\n (index.children.get(folder.path)?.length ?? 0) > 0 ||\n folder.hasChildren === true\n )\n}\n\n// A single SVG source so the same glyph renders as a React element, inside the\n// @pierre/trees shadow DOM (via CSS url()), and stays pixel-identical in both.\nconst FOLDER_GLYPH_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 50" width="64" height="50"><defs><linearGradient id="fs-folder-back" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#3dabf5"/><stop offset="1" stop-color="#1d84dd"/></linearGradient><linearGradient id="fs-folder-front" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#7accfb"/><stop offset="1" stop-color="#37a0ef"/></linearGradient></defs><path d="M5 10c0-3.31 2.69-6 6-6h10.9c1.6 0 3.13.7 4.18 1.9l1.5 1.73a3.5 3.5 0 0 0 2.64 1.22H54c2.76 0 5 2.24 5 5V40c0 3.87-3.13 7-7 7H12c-3.87 0-7-3.13-7-7V10Z" fill="url(#fs-folder-back)"/><path d="M5 15.5h54V40c0 3.87-3.13 7-7 7H12c-3.87 0-7-3.13-7-7V15.5Z" fill="url(#fs-folder-front)"/></svg>`\n\nconst FOLDER_GLYPH_DATA_URL = `data:image/svg+xml,${encodeURIComponent(FOLDER_GLYPH_SVG)}`\n\nfunction FileSystemFolderGlyph({ className }: { className?: string }) {\n return (\n <img\n src={FOLDER_GLYPH_DATA_URL}\n alt=""\n aria-hidden="true"\n draggable={false}\n className={className}\n />\n )\n}\n\nfunction escapeXmlAttribute(value: string) {\n return value\n .replaceAll("&", "&amp;")\n .replaceAll("<", "&lt;")\n .replaceAll(">", "&gt;")\n .replaceAll(\'"\', "&quot;")\n}\n\nfunction FileGenericPreview({ file }: { file: FileEntry }) {\n const extension = fileExtension(file.name)\n\n return (\n <div className="flex size-full flex-col items-center justify-center gap-1.5 bg-white text-neutral-400 dark:bg-neutral-100">\n <HugeiconsIcon icon={File01Icon} className="size-1/3 min-h-4 min-w-4" />\n {extension ? (\n <span className="text-[min(0.625rem,18cqw)] font-semibold tracking-wide uppercase">\n {extension}\n </span>\n ) : null}\n </div>\n )\n}\n\nfunction filePreviewUrls(file: FileSystemFileItem) {\n if (file.previewImageUrls?.length) return file.previewImageUrls\n return file.previewImageUrl ? [file.previewImageUrl] : []\n}\n\n// djb2 — cheap stable hash for remount keys derived from path lists.\nfunction hashString(value: string) {\n let hash = 5381\n\n for (let index = 0; index < value.length; index += 1) {\n hash = ((hash << 5) + hash + value.charCodeAt(index)) | 0\n }\n return hash\n}\n\nfunction FileVisual({\n file,\n className,\n loadPreviewImageUrl,\n pageable = false,\n previewAspectRatio,\n previewClassName,\n renderFilePreview,\n}: {\n file: FileEntry\n className?: string\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n /** Show a hover pager over multi-page thumbnails. */\n pageable?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n}) {\n const previewUrls = filePreviewUrls(file)\n const canLoadLazily = pageable && Boolean(loadPreviewImageUrl)\n const totalPages = Math.max(\n previewUrls.length,\n canLoadLazily ? (file.previewPageCount ?? 0) : 0\n )\n const [pageIndex, setPageIndex] = React.useState(0)\n const [lazyPageUrls, setLazyPageUrls] = React.useState<\n Record<number, string>\n >({})\n const clampedPageIndex = Math.min(pageIndex, Math.max(totalPages - 1, 0))\n const previewUrl =\n previewUrls[clampedPageIndex] ?? lazyPageUrls[clampedPageIndex] ?? null\n const resolvedAspectRatio = file.previewAspectRatio ?? previewAspectRatio\n const isLazyPagePending =\n canLoadLazily && !previewUrl && clampedPageIndex < totalPages\n\n const fileRef = React.useRef(file)\n\n React.useEffect(() => {\n fileRef.current = file\n })\n\n React.useEffect(() => {\n setPageIndex(0)\n setLazyPageUrls({})\n }, [file.path])\n\n // Keyed by path (not object identity) so manifest churn doesn\'t re-request\n // the page already being loaded.\n React.useEffect(() => {\n if (!isLazyPagePending || !loadPreviewImageUrl) return\n\n let isCurrent = true\n\n void loadPreviewImageUrl(fileRef.current, clampedPageIndex)\n .then((url) => {\n if (isCurrent && url) {\n setLazyPageUrls((previous) => ({\n ...previous,\n [clampedPageIndex]: url,\n }))\n }\n })\n .catch(() => {})\n\n return () => {\n isCurrent = false\n }\n }, [clampedPageIndex, file.path, isLazyPagePending, loadPreviewImageUrl])\n\n const customPreview =\n !previewUrl && !isLazyPagePending ? renderFilePreview?.(file) : null\n const showPager = pageable && totalPages > 1\n const thumbnail = (\n <FileThumbnail\n file={{ name: file.name, type: file.contentType ?? "" }}\n className={cn("@container", !showPager && className)}\n previewAspectRatio={resolvedAspectRatio}\n previewClassName={cn("bg-white dark:bg-neutral-100", previewClassName)}\n previewImageUrl={previewUrl ?? undefined}\n isLoading={isLazyPagePending}\n previewContent={\n previewUrl || isLazyPagePending\n ? undefined\n : (customPreview ?? <FileGenericPreview file={file} />)\n }\n />\n )\n\n if (!showPager) return thumbnail\n\n return (\n <div className={cn("group/pager relative", className)}>\n {thumbnail}\n <div className="absolute inset-x-0 bottom-1.5 flex items-center justify-center gap-1 opacity-0 transition-opacity group-focus-within/pager:opacity-100 group-hover/pager:opacity-100">\n <button\n type="button"\n aria-label="Previous page"\n disabled={clampedPageIndex === 0}\n onClick={(event) => {\n event.stopPropagation()\n setPageIndex((previous) => Math.max(0, previous - 1))\n }}\n onDoubleClick={(event) => event.stopPropagation()}\n className="flex size-6 items-center justify-center rounded-md bg-background/80 text-foreground shadow-xs backdrop-blur-sm transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />\n </button>\n <span className="rounded-md bg-background/80 px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground tabular-nums shadow-xs backdrop-blur-sm">\n {clampedPageIndex + 1}/{totalPages}\n </span>\n <button\n type="button"\n aria-label="Next page"\n disabled={clampedPageIndex >= totalPages - 1}\n onClick={(event) => {\n event.stopPropagation()\n setPageIndex((previous) => Math.min(totalPages - 1, previous + 1))\n }}\n onDoubleClick={(event) => event.stopPropagation()}\n className="flex size-6 items-center justify-center rounded-md bg-background/80 text-foreground shadow-xs backdrop-blur-sm transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-3.5" />\n </button>\n </div>\n </div>\n )\n}\n\nconst VIEW_OPTIONS: Array<{\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n label: string\n value: FileSystemView\n}> = [\n { icon: GridViewIcon, label: "Grid", value: "icons" },\n { icon: LeftToRightListBulletIcon, label: "List", value: "list" },\n { icon: LayoutThreeColumnIcon, label: "Columns", value: "columns" },\n { icon: GalleryThumbnailsIcon, label: "Gallery", value: "gallery" },\n]\n\nexport function FileSystem({\n items,\n className,\n title = "Files",\n defaultView = "icons",\n view: viewProp,\n onViewChange,\n defaultPath = "",\n onSelectionChange,\n onFileOpen,\n getFileUrl,\n loadChildren,\n loadPreviewImageUrl,\n renderFilePreview,\n}: FileSystemProps) {\n const [internalView, setInternalView] = React.useState(defaultView)\n const view = viewProp ?? internalView\n const setView = React.useCallback(\n (nextView: FileSystemView) => {\n setInternalView(nextView)\n onViewChange?.(nextView)\n },\n [onViewChange]\n )\n\n const [loadedItems, setLoadedItems] = React.useState<FileSystemItem[]>([])\n const allItems = React.useMemo(\n () => (loadedItems.length ? [...items, ...loadedItems] : items),\n [items, loadedItems]\n )\n const index = React.useMemo(() => buildFileSystemIndex(allItems), [allItems])\n\n const [history, setHistory] = React.useState(() => ({\n index: 0,\n stack: [normalizeFolderPath(defaultPath)],\n }))\n const currentPath = history.stack[history.index] ?? ""\n const canGoBack = history.index > 0\n const canGoForward = history.index < history.stack.length - 1\n\n const [selectedPath, setSelectedPath] = React.useState<string | null>(null)\n const selectedEntry = React.useMemo(() => {\n if (selectedPath === null) return null\n\n return (\n index.files.get(selectedPath) ?? index.folders.get(selectedPath) ?? null\n )\n }, [index, selectedPath])\n\n const selectEntry = React.useCallback(\n (entry: FileSystemEntry | null) => {\n setSelectedPath(entry?.path ?? null)\n onSelectionChange?.(entry)\n },\n [onSelectionChange]\n )\n\n // Below this width the tabs view switcher no longer fits in the toolbar.\n const rootRef = React.useRef<HTMLDivElement | null>(null)\n const [isCompact, setIsCompact] = React.useState(false)\n\n React.useEffect(() => {\n const root = rootRef.current\n\n if (!root || typeof ResizeObserver === "undefined") return\n\n const observer = new ResizeObserver((observerEntries) => {\n const width = observerEntries[0]?.contentRect.width\n\n if (width !== undefined) setIsCompact(width < 480)\n })\n\n observer.observe(root)\n return () => observer.disconnect()\n }, [])\n\n const requestedFoldersRef = React.useRef(new Set<string>())\n const [loadingFolders, setLoadingFolders] = React.useState<Set<string>>(\n () => new Set()\n )\n const ensureChildren = React.useCallback(\n (folderPath: string) => {\n if (!loadChildren) return\n\n const folder = index.folders.get(folderPath)\n\n if (!folder?.hasChildren) return\n if (index.children.get(folderPath)?.length) return\n if (requestedFoldersRef.current.has(folderPath)) return\n\n requestedFoldersRef.current.add(folderPath)\n setLoadingFolders((previous) => new Set(previous).add(folderPath))\n\n void (async () => {\n try {\n let cursor: string | null = null\n\n do {\n const result = await loadChildren({ cursor, path: folderPath })\n\n if (result.items.length) {\n setLoadedItems((previous) => [...previous, ...result.items])\n }\n cursor = result.nextCursor ?? null\n } while (cursor)\n } catch {\n requestedFoldersRef.current.delete(folderPath)\n } finally {\n setLoadingFolders((previous) => {\n const next = new Set(previous)\n\n next.delete(folderPath)\n return next\n })\n }\n })()\n },\n [index, loadChildren]\n )\n\n const navigateTo = React.useCallback(\n (folderPath: string) => {\n const path = normalizeFolderPath(folderPath)\n\n setHistory((previous) => {\n if (previous.stack[previous.index] === path) return previous\n\n const stack = [...previous.stack.slice(0, previous.index + 1), path]\n\n return { index: stack.length - 1, stack }\n })\n selectEntry(null)\n ensureChildren(path)\n },\n [ensureChildren, selectEntry]\n )\n\n React.useEffect(() => {\n ensureChildren(currentPath)\n }, [currentPath, ensureChildren])\n\n // Navigation unmounts the focused row, dropping focus to <body> and killing\n // the ⌘ shortcuts; reclaim focus onto the component root when that happens.\n const hasNavigatedRef = React.useRef(false)\n\n React.useEffect(() => {\n if (!hasNavigatedRef.current) {\n hasNavigatedRef.current = true\n return\n }\n\n const root = rootRef.current\n\n if (root && document.activeElement === document.body) {\n root.focus()\n }\n }, [currentPath])\n\n const [openedFile, setOpenedFile] = React.useState<{\n file: FileEntry\n kind: FileSystemViewerKind\n url: string\n } | null>(null)\n\n const openFile = React.useCallback(\n (file: FileEntry) => {\n void (async () => {\n let url = file.url ?? null\n\n if (!url && getFileUrl) {\n try {\n url = await getFileUrl(file)\n } catch {\n url = null\n }\n }\n if (onFileOpen) {\n onFileOpen(file, url)\n return\n }\n\n const kind = viewerKindForFile(file)\n\n if (kind && url) {\n setOpenedFile({ file, kind, url })\n } else if (url && typeof window !== "undefined") {\n window.open(url, "_blank", "noopener,noreferrer")\n }\n })()\n },\n [getFileUrl, onFileOpen]\n )\n\n const openEntry = React.useCallback(\n (entry: FileSystemEntry) => {\n if (entry.kind === "folder") {\n navigateTo(entry.path)\n } else {\n openFile(entry)\n }\n },\n [navigateTo, openFile]\n )\n\n // Selecting a lazy folder (columns view, keyboard nav) prefetches children.\n const selectAndPrefetchEntry = React.useCallback(\n (entry: FileSystemEntry | null) => {\n selectEntry(entry)\n if (entry?.kind === "folder") ensureChildren(entry.path)\n },\n [ensureChildren, selectEntry]\n )\n\n const goBack = React.useCallback(() => {\n setHistory((previous) => ({\n ...previous,\n index: Math.max(0, previous.index - 1),\n }))\n selectEntry(null)\n }, [selectEntry])\n\n const goForward = React.useCallback(() => {\n setHistory((previous) => ({\n ...previous,\n index: Math.min(previous.stack.length - 1, previous.index + 1),\n }))\n selectEntry(null)\n }, [selectEntry])\n\n const currentEntries = index.children.get(currentPath) ?? []\n const currentFolderName =\n currentPath === "" ? title : pathName(currentPath) || title\n const isLoadingCurrentFolder = loadingFolders.has(currentPath)\n\n const viewProps: FileSystemViewProps = {\n currentPath,\n entries: currentEntries,\n getFileUrl,\n index,\n loadPreviewImageUrl,\n loadingFolders,\n onOpen: openEntry,\n onSelect: selectAndPrefetchEntry,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n }\n\n const openedFileName = openedFile\n ? (openedFile.file.name ?? openedFile.file.path)\n : ""\n const activeViewOption = VIEW_OPTIONS.find((option) => option.value === view)\n const viewerCloseToolbarAction = (\n <DialogClose\n aria-label="Close preview"\n render={<Button type="button" variant="ghost" size="icon-sm" />}\n >\n <HugeiconsIcon icon={Cancel01Icon} className="size-4" />\n </DialogClose>\n )\n\n return (\n <div\n ref={rootRef}\n tabIndex={-1}\n className={cn(\n "flex h-[480px] min-h-0 flex-col overflow-hidden rounded-xl border bg-background text-foreground outline-none",\n className\n )}\n >\n <div className="grid h-12 shrink-0 grid-cols-[1fr_auto_1fr] items-center gap-2 border-b bg-muted/40 px-2">\n <div className="flex min-w-0 items-center gap-0.5">\n <button\n type="button"\n aria-label="Back"\n title="Back"\n disabled={!canGoBack}\n onClick={goBack}\n className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4.5" />\n </button>\n <button\n type="button"\n aria-label="Forward"\n title="Forward"\n disabled={!canGoForward}\n onClick={goForward}\n className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-4.5" />\n </button>\n <span className="ml-1.5 truncate text-sm font-semibold">\n {currentFolderName}\n </span>\n </div>\n {isCompact ? (\n <Select\n value={view}\n onValueChange={(value) => setView(value as FileSystemView)}\n >\n <SelectTrigger size="sm" aria-label="View" className="min-w-32">\n <SelectValue>\n {activeViewOption ? (\n <span className="flex items-center gap-2">\n <HugeiconsIcon\n icon={activeViewOption.icon}\n className="size-4"\n />\n {activeViewOption.label}\n </span>\n ) : null}\n </SelectValue>\n </SelectTrigger>\n <SelectContent>\n {VIEW_OPTIONS.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n <span className="flex items-center gap-2">\n <HugeiconsIcon icon={option.icon} className="size-4" />\n {option.label}\n </span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : (\n <Tabs\n value={view}\n onValueChange={(value) => setView(value as FileSystemView)}\n className="gap-0"\n >\n <TabsList className="h-8 p-0.5">\n {VIEW_OPTIONS.map((option) => (\n <TabsTrigger\n key={option.value}\n value={option.value}\n aria-label={`${option.label} view`}\n title={option.label}\n className="h-7 grow-0 px-2.5 sm:h-7"\n >\n <HugeiconsIcon icon={option.icon} className="size-4" />\n </TabsTrigger>\n ))}\n </TabsList>\n </Tabs>\n )}\n <div />\n </div>\n <div className="relative min-h-0 flex-1">\n {isLoadingCurrentFolder && currentEntries.length === 0 ? (\n <FileSystemEmptyState label="Loading…" isLoading />\n ) : currentEntries.length === 0 && view !== "columns" ? (\n <FileSystemEmptyState label="This folder is empty" />\n ) : view === "icons" ? (\n <FileSystemIconsView {...viewProps} />\n ) : view === "list" ? (\n <FileSystemListView {...viewProps} />\n ) : view === "columns" ? (\n <FileSystemColumnsView {...viewProps} />\n ) : (\n <FileSystemGalleryView {...viewProps} />\n )}\n </div>\n <div\n aria-live="polite"\n className="flex h-7 shrink-0 items-center justify-center gap-1 border-t bg-muted/40 px-3 text-xs text-muted-foreground"\n >\n <span>\n {currentEntries.length}{" "}\n {currentEntries.length === 1 ? "item" : "items"}\n </span>\n {selectedEntry ? <span>· “{selectedEntry.name}” selected</span> : null}\n </div>\n <Dialog\n open={openedFile !== null}\n onOpenChange={(open) => {\n if (!open) setOpenedFile(null)\n }}\n >\n {openedFile ? (\n <DialogContent\n className={cn(\n "overflow-hidden p-0",\n VIEWER_DIALOG_CLASSNAMES[openedFile.kind]\n )}\n showCloseButton={openedFile.kind === "image"}\n >\n <DialogTitle className="sr-only">{openedFileName}</DialogTitle>\n {openedFile.kind === "pdf" ? (\n <PDFViewer\n file={openedFile.url}\n className="h-full min-h-0 flex-1 overflow-hidden rounded-2xl"\n downloadFileName={openedFileName}\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n ) : openedFile.kind === "docx" ? (\n <DocxViewerPreview\n src={openedFile.url}\n fileName={openedFileName}\n className="h-full min-h-0 flex-1"\n rounded\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n ) : openedFile.kind === "xlsx" ? (\n <XlsxViewerPreview\n src={openedFile.url}\n fileName={openedFileName}\n className="h-full min-h-0 flex-1"\n rounded\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n ) : (\n <img\n src={openedFile.url}\n alt={openedFileName}\n className="max-h-[88vh] w-auto max-w-full rounded-2xl object-contain"\n />\n )}\n </DialogContent>\n ) : null}\n </Dialog>\n </div>\n )\n}\n\ntype FileSystemViewProps = {\n currentPath: string\n entries: FileSystemEntry[]\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n index: FileSystemIndex\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n loadingFolders: Set<string>\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n selectedEntry: FileSystemEntry | null\n selectedPath: string | null\n}\n\n// Resolves a display URL for a file: its own `url`, else via `getFileUrl`.\n// Keyed by path/url (not object identity) so manifest churn — e.g. thumbnails\n// streaming in — doesn\'t re-trigger presign calls for the same file.\nfunction useResolvedFileUrl(\n file: FileEntry | null,\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n) {\n const [resolvedUrl, setResolvedUrl] = React.useState<string | null>(\n file?.url ?? null\n )\n const fileRef = React.useRef(file)\n\n React.useEffect(() => {\n fileRef.current = file\n })\n\n const filePath = file?.path ?? null\n const fileUrl = file?.url ?? null\n\n React.useEffect(() => {\n const currentFile = fileRef.current\n\n if (!currentFile || fileUrl) {\n setResolvedUrl(fileUrl)\n return\n }\n if (!getFileUrl) {\n setResolvedUrl(null)\n return\n }\n\n let isCurrent = true\n\n setResolvedUrl(null)\n void Promise.resolve(getFileUrl(currentFile))\n .then((url) => {\n if (isCurrent) setResolvedUrl(url)\n })\n .catch(() => {})\n\n return () => {\n isCurrent = false\n }\n }, [filePath, fileUrl, getFileUrl])\n\n return resolvedUrl\n}\n\nfunction FileSystemEmptyState({\n label,\n isLoading = false,\n}: {\n label: string\n isLoading?: boolean\n}) {\n return (\n <div\n className={cn(\n "flex size-full items-center justify-center text-sm text-muted-foreground",\n isLoading && "animate-pulse motion-reduce:animate-none"\n )}\n >\n {label}\n </div>\n )\n}\n\nconst ARROW_KEYS = new Set(["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"])\n\n// Selects (and focuses) the entry reached by an arrow key. Up/down use row\n// geometry so navigation follows the rendered auto-fill grid.\nfunction moveGridSelection({\n entries,\n itemRefs,\n key,\n onSelect,\n selectedPath,\n}: {\n entries: FileSystemEntry[]\n itemRefs: Map<string, HTMLButtonElement>\n key: string\n onSelect: (entry: FileSystemEntry | null) => void\n selectedPath: string | null\n}) {\n if (entries.length === 0) return false\n\n const currentIndex = entries.findIndex((entry) => entry.path === selectedPath)\n let nextEntry: FileSystemEntry | undefined\n\n if (currentIndex === -1) {\n nextEntry = entries[0]\n } else if (key === "ArrowLeft" || key === "ArrowRight") {\n nextEntry = entries[currentIndex + (key === "ArrowLeft" ? -1 : 1)]\n } else {\n const currentElement = itemRefs.get(entries[currentIndex].path)\n\n if (!currentElement) return false\n\n const currentRect = currentElement.getBoundingClientRect()\n let bestScore = Infinity\n\n for (const entry of entries) {\n if (entry.path === selectedPath) continue\n\n const rect = itemRefs.get(entry.path)?.getBoundingClientRect()\n\n if (!rect) continue\n\n const rowDelta =\n key === "ArrowDown"\n ? rect.top - currentRect.top\n : currentRect.top - rect.top\n\n if (rowDelta <= 1) continue\n\n const score = rowDelta * 1000 + Math.abs(rect.left - currentRect.left)\n\n if (score < bestScore) {\n bestScore = score\n nextEntry = entry\n }\n }\n }\n\n if (!nextEntry) return false\n\n onSelect(nextEntry)\n itemRefs.get(nextEntry.path)?.focus()\n return true\n}\n\nfunction FileSystemIconsView({\n entries,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedPath,\n}: FileSystemViewProps) {\n const itemRefs = React.useRef(new Map<string, HTMLButtonElement>())\n\n return (\n <ScrollArea\n orientation="vertical"\n viewportClassName="p-3"\n viewportProps={{\n onClick: (event) => {\n if (event.target === event.currentTarget) onSelect(null)\n },\n }}\n >\n <div\n role="listbox"\n aria-label="Files"\n className="grid grid-cols-[repeat(auto-fill,minmax(6.5rem,1fr))] gap-x-1 gap-y-3"\n onKeyDown={(event) => {\n if (!ARROW_KEYS.has(event.key)) return\n if (\n moveGridSelection({\n entries,\n itemRefs: itemRefs.current,\n key: event.key,\n onSelect,\n selectedPath,\n })\n ) {\n event.preventDefault()\n }\n }}\n >\n {entries.map((entry) => {\n const isSelected = entry.path === selectedPath\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isSelected}\n ref={(element) => {\n if (element) {\n itemRefs.current.set(entry.path, element)\n } else {\n itemRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n className="group flex flex-col items-center gap-1.5 outline-none"\n >\n <span\n className={cn(\n "flex h-16 w-20 items-center justify-center rounded-lg p-1 transition-colors group-focus-visible:ring-2 group-focus-visible:ring-ring",\n isSelected && "bg-accent"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-13 w-auto drop-shadow-sm" />\n ) : (\n <FileVisual\n file={entry}\n className={cn(\n "rounded-sm shadow-xs",\n // Landscape thumbnails get extra width so they fill\n // the tile instead of rendering as a short sliver.\n (entry.previewAspectRatio ?? 0.78) > 1.2\n ? "w-[4.75rem]"\n : "w-12"\n )}\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )}\n </span>\n <span\n className={cn(\n "max-w-full rounded-sm px-1.5 py-px text-center text-xs leading-tight break-words",\n isSelected\n ? "bg-primary text-primary-foreground"\n : "text-foreground"\n )}\n >\n <span className="line-clamp-2">{entry.name}</span>\n </span>\n </button>\n )\n })}\n </div>\n </ScrollArea>\n )\n}\n\nfunction FileSystemListView({\n currentPath,\n index,\n onOpen,\n onSelect,\n selectedPath,\n}: FileSystemViewProps) {\n const relativePaths = React.useMemo(() => {\n const paths: string[] = []\n\n for (const path of index.files.keys()) {\n if (currentPath === "" || path.startsWith(currentPath)) {\n const relativePath = path.slice(currentPath.length)\n\n if (relativePath) paths.push(relativePath)\n }\n }\n return paths.sort()\n }, [currentPath, index])\n // Content-derived key: the tree only remounts when the path set actually\n // changes (a bare length check misses same-count replacements).\n const treeKey = React.useMemo(\n () => hashString(relativePaths.join("\\n")),\n [relativePaths]\n )\n\n if (relativePaths.length === 0) {\n return <FileSystemEmptyState label="This folder is empty" />\n }\n\n return (\n <div className="flex size-full flex-col">\n {/* Paddings match the tree\'s row geometry: name text starts 46px in\n (16px tree padding + 30px icon lane), metadata ends 24px from the\n right (16px tree padding + 8px decoration inset). */}\n <div className="flex shrink-0 items-center border-b py-1.5 pr-6 pl-[46px] text-xs font-medium text-muted-foreground">\n <span className="flex-1">Name</span>\n <span className="w-44 text-right">Date Modified</span>\n <span className="w-20 text-right">Size</span>\n </div>\n <FileSystemPierreTree\n key={`${currentPath}::${treeKey}`}\n currentPath={currentPath}\n index={index}\n initialSelectedPath={\n selectedPath?.startsWith(currentPath)\n ? selectedPath.slice(currentPath.length).replace(/\\/$/, "")\n : null\n }\n onOpen={onOpen}\n onSelect={onSelect}\n relativePaths={relativePaths}\n />\n </div>\n )\n}\n\nfunction FileSystemPierreTree({\n currentPath,\n index,\n initialSelectedPath,\n onOpen,\n onSelect,\n relativePaths,\n}: {\n currentPath: string\n index: FileSystemIndex\n initialSelectedPath: string | null\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n relativePaths: string[]\n}) {\n const preparedInput = React.useMemo(\n () => prepareFileTreeInput(relativePaths, { sort: "default" }),\n [relativePaths]\n )\n // Inject per-file thumbnails into the tree\'s shadow DOM as sprite symbols\n // wrapping an <image>, remapped onto rows by file basename. The chevron is\n // remapped to the Hugeicons arrow so it matches the rest of the component;\n // the tree\'s rotation CSS keys off data-icon-name, which remapping keeps.\n const icons = React.useMemo(() => {\n const byFileName: Record<string, { name: string; viewBox: string }> = {}\n const symbols: string[] = [\n `<symbol id="file-system-chevron" viewBox="0 0 24 24"><path d="M18 9.00005C18 9.00005 13.5811 15 12 15C10.4188 15 6 9 6 9" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/></symbol>`,\n ]\n\n for (const relativePath of relativePaths) {\n const file = index.files.get(`${currentPath}${relativePath}`)\n const coverUrl = file ? filePreviewUrls(file)[0] : undefined\n\n if (!file || !coverUrl) continue\n\n const baseName = file.name.toLowerCase()\n\n if (byFileName[baseName]) continue\n\n const symbolId = `file-system-thumbnail-${symbols.length}`\n\n symbols.push(\n `<symbol id="${symbolId}" viewBox="0 0 16 16"><clipPath id="${symbolId}-clip"><rect width="16" height="16" rx="2.5"/></clipPath><image href="${escapeXmlAttribute(coverUrl)}" width="16" height="16" preserveAspectRatio="xMidYMid slice" clip-path="url(#${symbolId}-clip)"/></symbol>`\n )\n byFileName[baseName] = { name: symbolId, viewBox: "0 0 16 16" }\n }\n\n return {\n byFileName,\n remap: {\n "file-tree-icon-chevron": {\n name: "file-system-chevron",\n viewBox: "0 0 24 24",\n },\n },\n spriteSheet: `<svg data-icon-sprite aria-hidden="true" width="0" height="0">${symbols.join("")}</svg>`,\n }\n }, [currentPath, index, relativePaths])\n const { model } = useFileTree({\n flattenEmptyDirectories: false,\n icons,\n initialExpansion: "closed",\n initialSelectedPaths: initialSelectedPath ? [initialSelectedPath] : [],\n itemHeight: 28,\n overscan: 12,\n preparedInput,\n renderRowDecoration: ({ row }) => {\n const entry =\n row.kind === "file"\n ? index.files.get(`${currentPath}${row.path}`)\n : index.folders.get(normalizeFolderPath(`${currentPath}${row.path}`))\n\n if (!entry) return null\n\n // The decoration lane renders one <span title>; CSS splits it into\n // aligned Date Modified (::before from title) and Size columns.\n const dateColumn =\n formatTimestamp(entry.updatedAt ?? entry.createdAt) ?? "—"\n\n if (entry.kind === "folder") {\n const childCount = index.children.get(entry.path)?.length\n\n return {\n text:\n childCount === undefined\n ? "—"\n : `${childCount} ${childCount === 1 ? "item" : "items"}`,\n title: dateColumn,\n }\n }\n\n return { text: formatByteSize(entry.size) ?? "—", title: dateColumn }\n },\n unsafeCSS: `\n button[data-type=\'item\']:not([data-item-selected]):hover {\n background: color-mix(in oklab, var(--color-accent) 50%, transparent);\n }\n button[data-type=\'item\'][data-item-selected] {\n background: var(--color-primary);\n color: var(--color-primary-foreground);\n }\n button[data-type=\'item\'][data-item-selected] *,\n button[data-type=\'item\'][data-item-selected] [data-item-section]::before,\n button[data-type=\'item\'][data-item-selected] svg {\n color: var(--color-primary-foreground) !important;\n }\n [data-item-section=\'decoration\'] > span {\n display: grid;\n grid-template-columns: 11rem 5rem;\n justify-items: end;\n white-space: nowrap;\n }\n [data-item-section=\'decoration\'] > span::before {\n content: attr(title);\n }\n button[data-type=\'item\'][data-item-type=\'folder\'] [data-item-section=\'content\'] {\n display: flex;\n align-items: center;\n min-width: 0;\n }\n button[data-type=\'item\'][data-item-type=\'folder\'] [data-item-section=\'content\']::before {\n content: "";\n flex: none;\n width: 18px;\n height: 14px;\n margin-right: 4px;\n background: url("${FOLDER_GLYPH_DATA_URL}") center / contain no-repeat;\n }\n `,\n onSelectionChange: (selectedPaths) => {\n const relativePath = selectedPaths[0]\n\n if (!relativePath) {\n onSelect(null)\n return\n }\n\n const absolutePath = `${currentPath}${relativePath}`\n const entry =\n index.files.get(absolutePath) ??\n index.folders.get(normalizeFolderPath(absolutePath)) ??\n null\n\n onSelect(entry)\n },\n })\n\n // Thumbnails can resolve after mount (e.g. generated client-side); push\n // sprite updates into the existing model instead of remounting the tree.\n React.useEffect(() => {\n model.setIcons(icons)\n }, [icons, model])\n\n return (\n <PierreFileTree\n model={model}\n className="block min-h-0 flex-1"\n onDoubleClick={(event) => {\n // Rows live in the tree\'s shadow DOM; composedPath surfaces the row\n // element so double-clicked files open like in the other views.\n for (const target of event.nativeEvent.composedPath()) {\n if (!(target instanceof HTMLElement)) continue\n const relativePath = target.dataset?.itemPath\n if (!relativePath) continue\n\n const file = index.files.get(`${currentPath}${relativePath}`)\n\n if (file) onOpen(file)\n return\n }\n }}\n style={\n {\n "--trees-bg-override": "transparent",\n "--trees-border-color-override": "var(--color-border)",\n "--trees-fg-override": "var(--color-foreground)",\n "--trees-selected-bg-override": "var(--color-primary)",\n } as React.CSSProperties\n }\n />\n )\n}\n\nfunction FileSystemColumnsView(props: FileSystemViewProps) {\n const {\n currentPath,\n index,\n loadPreviewImageUrl,\n loadingFolders,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n } = props\n const scrollContainerRef = React.useRef<HTMLDivElement | null>(null)\n const rowRefs = React.useRef(new Map<string, HTMLButtonElement>())\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (!ARROW_KEYS.has(event.key)) return\n\n let nextEntry: FileSystemEntry | null | undefined\n\n if (!selectedEntry || !selectedPath?.startsWith(currentPath)) {\n nextEntry = index.children.get(currentPath)?.[0]\n } else if (event.key === "ArrowUp" || event.key === "ArrowDown") {\n const siblings = index.children.get(selectedEntry.parentPath) ?? []\n const currentIndex = siblings.findIndex(\n (sibling) => sibling.path === selectedEntry.path\n )\n\n nextEntry = siblings[currentIndex + (event.key === "ArrowUp" ? -1 : 1)]\n } else if (event.key === "ArrowLeft") {\n if (selectedEntry.parentPath !== currentPath) {\n nextEntry = index.folders.get(selectedEntry.parentPath)\n }\n } else if (selectedEntry.kind === "folder") {\n nextEntry = index.children.get(selectedEntry.path)?.[0]\n }\n\n if (!nextEntry) return\n\n onSelect(nextEntry)\n rowRefs.current.get(nextEntry.path)?.focus()\n event.preventDefault()\n }\n\n const columnPaths = React.useMemo(() => {\n const paths = [currentPath]\n\n if (!selectedPath?.startsWith(currentPath)) return paths\n\n const targetFolder =\n selectedEntry?.kind === "folder"\n ? selectedEntry.path\n : (selectedEntry?.parentPath ?? currentPath)\n const relativePath = targetFolder.slice(currentPath.length)\n let walkedPath = currentPath\n\n for (const segment of relativePath.split("/")) {\n if (!segment) continue\n walkedPath = `${walkedPath}${segment}/`\n paths.push(walkedPath)\n }\n return paths\n }, [currentPath, selectedEntry, selectedPath])\n const columnPathSet = React.useMemo(() => new Set(columnPaths), [columnPaths])\n const selectedFile =\n selectedEntry?.kind === "file" ? (selectedEntry as FileEntry) : null\n const selectedFileSize = selectedFile\n ? formatByteSize(selectedFile.size)\n : null\n\n React.useEffect(() => {\n const container = scrollContainerRef.current\n\n if (container) container.scrollLeft = container.scrollWidth\n }, [columnPaths.length, selectedPath])\n\n return (\n <ScrollArea\n orientation="horizontal"\n viewportRef={scrollContainerRef}\n viewportClassName="overscroll-x-contain"\n >\n <div className="flex h-full w-max min-w-full" onKeyDown={handleKeyDown}>\n {columnPaths.map((columnPath) => (\n <ScrollArea\n key={columnPath || "(root)"}\n orientation="vertical"\n className="w-60 shrink-0 border-r"\n viewportClassName="flex flex-col gap-px p-1.5"\n viewportProps={{ "aria-label": "Files", role: "listbox" }}\n >\n {loadingFolders.has(columnPath) &&\n !index.children.get(columnPath)?.length ? (\n <div className="animate-pulse px-2 py-1.5 text-xs text-muted-foreground motion-reduce:animate-none">\n Loading…\n </div>\n ) : (\n (index.children.get(columnPath) ?? []).map((entry) => {\n const isSelected = entry.path === selectedPath\n const isOnTrail =\n entry.kind === "folder" && columnPathSet.has(entry.path)\n\n const coverUrl =\n entry.kind === "file" ? filePreviewUrls(entry)[0] : undefined\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isSelected}\n ref={(element) => {\n if (element) {\n rowRefs.current.set(entry.path, element)\n } else {\n rowRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n className={cn(\n "flex shrink-0 items-center gap-2 rounded-md px-2 py-1 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",\n isSelected\n ? "bg-primary text-primary-foreground"\n : isOnTrail\n ? "bg-accent"\n : "hover:bg-accent/50"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-3.5 w-auto shrink-0" />\n ) : coverUrl ? (\n <img\n src={coverUrl}\n alt=""\n draggable={false}\n className="size-4 shrink-0 rounded-[3px] bg-white object-cover"\n />\n ) : (\n <HugeiconsIcon\n icon={File01Icon}\n className={cn(\n "size-4 shrink-0",\n !isSelected && "text-muted-foreground"\n )}\n />\n )}\n <span className="min-w-0 flex-1 truncate">\n {entry.name}\n </span>\n {entry.kind === "folder" &&\n folderHasChildren(index, entry) ? (\n <HugeiconsIcon\n icon={ArrowRight01Icon}\n className={cn(\n "size-3.5 shrink-0",\n !isSelected && "text-muted-foreground/60"\n )}\n />\n ) : null}\n </button>\n )\n })\n )}\n </ScrollArea>\n ))}\n {selectedFile ? (\n <ScrollArea\n orientation="vertical"\n className="min-w-72 flex-1"\n viewportClassName="flex justify-center p-4"\n >\n <div className="flex w-full max-w-lg flex-col items-stretch gap-3">\n {/* Width derives from the aspect ratio so the thumbnail grows\n with the pane up to a 20rem height cap. */}\n <div\n className="mx-auto w-full shrink-0"\n style={{\n maxWidth: `min(100%, ${(selectedFile.previewAspectRatio ?? 0.78) * 20}rem)`,\n }}\n >\n <FileVisual\n file={selectedFile}\n className="w-full"\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageable\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n </div>\n <div className="text-center">\n <div className="text-sm font-semibold break-words">\n {selectedFile.name}\n </div>\n <div className="text-xs text-muted-foreground">\n {fileKindLabel(selectedFile)}\n {selectedFileSize ? ` - ${selectedFileSize}` : null}\n </div>\n </div>\n <FileSystemInformation entry={selectedFile} index={index} />\n </div>\n </ScrollArea>\n ) : null}\n </div>\n </ScrollArea>\n )\n}\n\nfunction FileSystemInformation({\n entry,\n index,\n}: {\n entry: FileSystemEntry\n index: FileSystemIndex\n}) {\n const rows: Array<[string, string]> = []\n const created = formatTimestamp(entry.createdAt)\n const updated = formatTimestamp(entry.updatedAt)\n\n if (created) rows.push(["Created", created])\n if (updated) rows.push(["Modified", updated])\n if (entry.kind === "file") {\n const size = formatByteSize(entry.size)\n\n if (size) rows.push(["Size", size])\n } else {\n const childCount = index.children.get(entry.path)?.length\n\n if (childCount !== undefined) {\n rows.push(["Items", `${childCount}`])\n }\n }\n\n if (rows.length === 0) return null\n\n return (\n <div className="border-t pt-3">\n <div className="mb-1.5 text-xs font-semibold">Information</div>\n <dl className="space-y-1">\n {rows.map(([label, value]) => (\n <div\n key={label}\n className="flex items-baseline justify-between gap-3 text-xs"\n >\n <dt className="shrink-0 text-muted-foreground">{label}</dt>\n <dd className="text-right" suppressHydrationWarning>\n {value}\n </dd>\n </div>\n ))}\n </dl>\n </div>\n )\n}\n\nfunction FileSystemGalleryView(props: FileSystemViewProps) {\n const {\n entries,\n getFileUrl,\n index,\n loadPreviewImageUrl,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n } = props\n const stripRefs = React.useRef(new Map<string, HTMLButtonElement>())\n const activeEntry =\n selectedEntry && entries.some((entry) => entry.path === selectedEntry.path)\n ? selectedEntry\n : (entries[0] ?? null)\n const activeFile = activeEntry?.kind === "file" ? activeEntry : null\n const activeViewerKind = activeFile ? viewerKindForFile(activeFile) : null\n const activeFileUrl = useResolvedFileUrl(activeFile, getFileUrl)\n const activeFileSize = activeFile ? formatByteSize(activeFile.size) : null\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return\n if (entries.length === 0) return\n\n const currentIndex = activeEntry\n ? entries.findIndex((entry) => entry.path === activeEntry.path)\n : -1\n const nextEntry =\n entries[\n currentIndex === -1\n ? 0\n : currentIndex + (event.key === "ArrowLeft" ? -1 : 1)\n ]\n\n if (!nextEntry) return\n\n onSelect(nextEntry)\n stripRefs.current.get(nextEntry.path)?.focus()\n event.preventDefault()\n }\n\n return (\n <div className="flex size-full flex-col" onKeyDown={handleKeyDown}>\n <div className="flex min-h-0 flex-1">\n <div className="flex min-h-0 min-w-0 flex-1 items-center justify-center p-3">\n {activeEntry ? (\n activeEntry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-40 max-h-full w-auto drop-shadow-md" />\n ) : activeViewerKind === "image" && activeFileUrl ? (\n <img\n src={activeFileUrl}\n alt={activeEntry.name}\n className="max-h-full max-w-full rounded-lg object-contain"\n />\n ) : activeViewerKind === "pdf" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <PDFViewer\n key={activeEntry.path}\n file={activeFileUrl}\n className="h-full"\n showToolbar={false}\n />\n </div>\n ) : activeViewerKind === "docx" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <DocxViewerPreview\n key={activeEntry.path}\n src={activeFileUrl}\n fileName={activeEntry.name}\n className="h-full"\n showToolbar={false}\n />\n </div>\n ) : activeViewerKind === "xlsx" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <XlsxViewerPreview\n key={activeEntry.path}\n src={activeFileUrl}\n fileName={activeEntry.name}\n className="h-full"\n showToolbar={false}\n />\n </div>\n ) : (\n <FileVisual\n file={activeEntry}\n className="w-56 max-w-full"\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageable\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )\n ) : null}\n </div>\n {activeEntry ? (\n <ScrollArea\n orientation="vertical"\n className="hidden w-64 shrink-0 border-l sm:block"\n viewportClassName="flex flex-col gap-3 p-4"\n >\n <div className="flex items-center gap-3">\n {activeFile ? (\n <FileVisual\n file={activeFile}\n className={cn(\n "shrink-0 rounded-sm",\n (activeFile.previewAspectRatio ?? 0.78) > 1.2\n ? "w-16"\n : "w-9"\n )}\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n ) : (\n <FileSystemFolderGlyph className="h-8 w-auto shrink-0" />\n )}\n <div className="min-w-0 flex-1">\n <div className="text-sm font-semibold break-words">\n {activeEntry.name}\n </div>\n <div className="text-xs text-muted-foreground">\n {activeFile ? fileKindLabel(activeFile) : "Folder"}\n {activeFileSize ? ` - ${activeFileSize}` : null}\n </div>\n </div>\n </div>\n <FileSystemInformation entry={activeEntry} index={index} />\n </ScrollArea>\n ) : null}\n </div>\n <ScrollArea\n orientation="horizontal"\n className="h-auto w-full shrink-0 border-t"\n >\n <div\n role="listbox"\n aria-label="Files"\n className="flex w-max min-w-full items-center gap-1.5 p-2"\n >\n {entries.map((entry) => {\n const isActive = entry.path === (activeEntry?.path ?? selectedPath)\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isActive}\n ref={(element) => {\n if (element) {\n stripRefs.current.set(entry.path, element)\n } else {\n stripRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n title={entry.name}\n className={cn(\n "flex size-14 shrink-0 items-center justify-center rounded-md border border-transparent p-1 outline-none focus-visible:ring-2 focus-visible:ring-ring",\n isActive && "border-ring/40 bg-accent"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-9 w-auto" />\n ) : (\n <FileVisual\n file={entry}\n className="w-9 rounded-sm"\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )}\n </button>\n )\n })}\n </div>\n </ScrollArea>\n </div>\n )\n}\n'
export function FileSystemSourceCode() {
return (
diff --git a/apps/v4/components/file-thumbnail-docs.tsx b/apps/v4/components/file-thumbnail-docs.tsx
index dced93f..6342590 100644
--- a/apps/v4/components/file-thumbnail-docs.tsx
+++ b/apps/v4/components/file-thumbnail-docs.tsx
@@ -654,180 +654,8 @@ function XlsxThumbnailCapture({ onImageUrl }) {
return null
}`
-const fileThumbnailSourceCode = `"use client"
-
-import * as React from "react"
-
-export type ThumbnailFile = {
- name: string
- type: string
-}
-
-export type FileThumbnailProps = {
- file: ThumbnailFile | File
- className?: string
- previewAspectRatio?: number
- previewClassName?: string
- previewContent?: React.ReactNode
- previewImageUrl?: string | null
- isLoading?: boolean
- hasError?: boolean
-}
-
-function cx(...classes: Array<string | false | null | undefined>) {
- return classes.filter(Boolean).join(" ")
-}
-
-export function FileThumbnailLoadingOverlay() {
- return (
- <div
- aria-hidden="true"
- className="absolute inset-0 z-10 overflow-hidden bg-muted"
- >
- <div className="absolute inset-0 bg-muted" />
- <div className="absolute inset-0 animate-pulse bg-background/55 motion-reduce:animate-none" />
- </div>
- )
-}
-
-export function FileThumbnail({
- file: _file,
- className,
- previewAspectRatio,
- previewClassName,
- previewContent,
- previewImageUrl,
- isLoading = false,
- hasError = false,
-}: FileThumbnailProps) {
- const imageRef = React.useRef<HTMLImageElement | null>(null)
- const revealFrameRef = React.useRef<number | null>(null)
- const [loadedPreviewImageUrl, setLoadedPreviewImageUrl] = React.useState<
- string | null
- >(null)
- const [failedPreviewImageUrl, setFailedPreviewImageUrl] = React.useState<
- string | null
- >(null)
- const imageFailed = Boolean(
- previewImageUrl && failedPreviewImageUrl === previewImageUrl
- )
- const isImageLoading = Boolean(
- previewImageUrl && loadedPreviewImageUrl !== previewImageUrl && !imageFailed
- )
- const showLoading = isLoading || isImageLoading
- const hasPreviewContent = Boolean(previewContent)
- const showFallback =
- !showLoading &&
- (hasError || imageFailed || (!previewImageUrl && !hasPreviewContent))
- const cancelImageReveal = React.useCallback(() => {
- if (revealFrameRef.current === null) return
-
- window.cancelAnimationFrame(revealFrameRef.current)
- revealFrameRef.current = null
- }, [])
- const markImageLoaded = React.useCallback(
- (image: HTMLImageElement, imageUrl: string | null | undefined) => {
- if (!imageUrl) return
-
- const didLoad = image.naturalWidth > 0 && image.naturalHeight > 0
-
- setFailedPreviewImageUrl(didLoad ? null : imageUrl)
- if (didLoad) {
- cancelImageReveal()
- revealFrameRef.current = window.requestAnimationFrame(() => {
- revealFrameRef.current = window.requestAnimationFrame(() => {
- setLoadedPreviewImageUrl(imageUrl)
- revealFrameRef.current = null
- })
- })
- }
- },
- [cancelImageReveal]
- )
-
- React.useEffect(() => {
- cancelImageReveal()
-
- if (previewImageUrl) return
-
- setLoadedPreviewImageUrl(null)
- setFailedPreviewImageUrl(null)
- }, [cancelImageReveal, previewImageUrl])
-
- React.useEffect(() => cancelImageReveal, [cancelImageReveal])
-
- React.useEffect(() => {
- const image = imageRef.current
-
- if (!image || !previewImageUrl) return
-
- if (image.complete) {
- markImageLoaded(image, previewImageUrl)
- }
- }, [markImageLoaded, previewImageUrl])
-
- return (
- <div
- className={cx(
- "group overflow-hidden rounded-lg border bg-background text-foreground",
- className
- )}
- >
- <div
- className={cx(
- "relative aspect-square overflow-hidden bg-muted [contain:layout_paint]",
- previewClassName
- )}
- style={
- previewAspectRatio
- ? { aspectRatio: String(previewAspectRatio) }
- : undefined
- }
- >
- {previewImageUrl ? (
- <img
- ref={imageRef}
- src={previewImageUrl}
- alt=""
- draggable={false}
- loading="lazy"
- decoding="async"
- className={cx(
- "absolute inset-0 block size-full object-cover transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
- showLoading ? "opacity-0 blur-sm" : "blur-0 opacity-100"
- )}
- onLoad={(event) => {
- markImageLoaded(event.currentTarget, previewImageUrl)
- }}
- onError={() => {
- if (previewImageUrl) {
- cancelImageReveal()
- setFailedPreviewImageUrl(previewImageUrl)
- setLoadedPreviewImageUrl((currentUrl) =>
- currentUrl === previewImageUrl ? null : currentUrl
- )
- }
- }}
- />
- ) : null}
- {previewContent ? (
- <div
- className={cx(
- "absolute inset-0 size-full transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
- showLoading ? "opacity-0 blur-sm" : "blur-0 opacity-100"
- )}
- >
- {previewContent}
- </div>
- ) : null}
- {showLoading ? <FileThumbnailLoadingOverlay /> : null}
- {showFallback ? (
- <div className="absolute inset-0 bg-muted" aria-hidden="true" />
- ) : null}
- </div>
- </div>
- )
-}`
+const fileThumbnailSourceCode =
+ '"use client"\n\nimport * as React from "react"\n\nexport type ThumbnailFile = {\n name: string\n type: string\n}\n\nexport type FileThumbnailProps = {\n file: ThumbnailFile | File\n className?: string\n previewAspectRatio?: number\n previewClassName?: string\n previewContent?: React.ReactNode\n previewImageUrl?: string | null\n isLoading?: boolean\n hasError?: boolean\n}\n\nfunction cx(...classes: Array<string | false | null | undefined>) {\n return classes.filter(Boolean).join(" ")\n}\n\n// Preview URLs that have completed a reveal this session. View/tab switches\n// remount thumbnails; URLs in this set render instantly instead of replaying\n// the blur-in, so only an image\'s first load animates.\nconst revealedPreviewImageUrls = new Set<string>()\n\nexport function FileThumbnailLoadingOverlay() {\n return (\n <div\n aria-hidden="true"\n className="absolute inset-0 z-10 overflow-hidden bg-muted"\n >\n <div className="absolute inset-0 bg-muted" />\n <div className="absolute inset-0 animate-pulse bg-background/55 motion-reduce:animate-none" />\n </div>\n )\n}\n\nexport function FileThumbnail({\n file: _file,\n className,\n previewAspectRatio,\n previewClassName,\n previewContent,\n previewImageUrl,\n isLoading = false,\n hasError = false,\n}: FileThumbnailProps) {\n const imageRef = React.useRef<HTMLImageElement | null>(null)\n const revealFrameRef = React.useRef<number | null>(null)\n const [loadedPreviewImageUrl, setLoadedPreviewImageUrl] = React.useState<\n string | null\n >(() =>\n previewImageUrl && revealedPreviewImageUrls.has(previewImageUrl)\n ? previewImageUrl\n : null\n )\n const [failedPreviewImageUrl, setFailedPreviewImageUrl] = React.useState<\n string | null\n >(null)\n const imageFailed = Boolean(\n previewImageUrl && failedPreviewImageUrl === previewImageUrl\n )\n const isImageLoading = Boolean(\n previewImageUrl &&\n loadedPreviewImageUrl !== previewImageUrl &&\n !imageFailed &&\n !revealedPreviewImageUrls.has(previewImageUrl)\n )\n const showLoading = isLoading || isImageLoading\n const hasPreviewContent = Boolean(previewContent)\n const showFallback =\n !showLoading &&\n (hasError || imageFailed || (!previewImageUrl && !hasPreviewContent))\n const cancelImageReveal = React.useCallback(() => {\n if (revealFrameRef.current === null) return\n\n window.cancelAnimationFrame(revealFrameRef.current)\n revealFrameRef.current = null\n }, [])\n const markImageLoaded = React.useCallback(\n (image: HTMLImageElement, imageUrl: string | null | undefined) => {\n if (!imageUrl) return\n\n const didLoad = image.naturalWidth > 0 && image.naturalHeight > 0\n\n setFailedPreviewImageUrl(didLoad ? null : imageUrl)\n if (didLoad) {\n revealedPreviewImageUrls.add(imageUrl)\n cancelImageReveal()\n revealFrameRef.current = window.requestAnimationFrame(() => {\n revealFrameRef.current = window.requestAnimationFrame(() => {\n setLoadedPreviewImageUrl(imageUrl)\n revealFrameRef.current = null\n })\n })\n }\n },\n [cancelImageReveal]\n )\n\n React.useEffect(() => {\n cancelImageReveal()\n\n if (previewImageUrl) return\n\n setLoadedPreviewImageUrl(null)\n setFailedPreviewImageUrl(null)\n }, [cancelImageReveal, previewImageUrl])\n\n React.useEffect(() => cancelImageReveal, [cancelImageReveal])\n\n React.useEffect(() => {\n const image = imageRef.current\n\n if (!image || !previewImageUrl) return\n\n if (image.complete) {\n markImageLoaded(image, previewImageUrl)\n }\n }, [markImageLoaded, previewImageUrl])\n\n return (\n <div\n className={cx(\n "group overflow-hidden rounded-lg border bg-background text-foreground",\n className\n )}\n >\n <div\n className={cx(\n "relative aspect-square overflow-hidden bg-muted [contain:layout_paint]",\n previewClassName\n )}\n style={\n previewAspectRatio\n ? { aspectRatio: String(previewAspectRatio) }\n : undefined\n }\n >\n {previewImageUrl ? (\n <img\n ref={imageRef}\n src={previewImageUrl}\n alt=""\n draggable={false}\n loading="lazy"\n decoding="async"\n className={cx(\n "absolute inset-0 block size-full object-cover transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",\n showLoading ? "opacity-0 blur-sm" : "blur-0 opacity-100"\n )}\n onLoad={(event) => {\n markImageLoaded(event.currentTarget, previewImageUrl)\n }}\n onError={() => {\n if (previewImageUrl) {\n revealedPreviewImageUrls.delete(previewImageUrl)\n cancelImageReveal()\n setFailedPreviewImageUrl(previewImageUrl)\n setLoadedPreviewImageUrl((currentUrl) =>\n currentUrl === previewImageUrl ? null : currentUrl\n )\n }\n }}\n />\n ) : null}\n {previewContent ? (\n <div\n className={cx(\n "absolute inset-0 size-full transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",\n showLoading ? "opacity-0 blur-sm" : "blur-0 opacity-100"\n )}\n >\n {previewContent}\n </div>\n ) : null}\n {showLoading ? <FileThumbnailLoadingOverlay /> : null}\n {showFallback ? (\n <div className="absolute inset-0 bg-muted" aria-hidden="true" />\n ) : null}\n </div>\n </div>\n )\n}\n'
export function FileThumbnailSource() {
return (
diff --git a/apps/v4/components/file-upload-docs.tsx b/apps/v4/components/file-upload-docs.tsx
index 1558ac1..67ac7a3 100644
--- a/apps/v4/components/file-upload-docs.tsx
+++ b/apps/v4/components/file-upload-docs.tsx
@@ -12,12 +12,12 @@ import { BorderBeam } from "border-beam"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
+import { Card } from "@/components/ui/card"
import { FileThumbnail } from "@/components/ui/file-thumbnail"
import {
DocsSourceCodeBlock,
DocsViewCodeBlock,
} from "@/components/docs-code-block"
-import { Card } from "@/components/ui/card"
type FileUploadItem = {
id: string
@@ -355,7 +355,7 @@ export function FileUploadExample() {
}`
const fileUploadUsageCode =
- '"use client"\n\nimport * as React from "react"\nimport {\n FileImageIcon,\n FileSpreadsheetIcon,\n FileUploadIcon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { BorderBeam } from "border-beam"\n\nimport { cn } from "@/lib/utils"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Card } from "@/components/ui/card"\n\ntype FileUploadItem = {\n id: string\n name: string\n type: string\n size: number\n url: string\n}\n\ntype AcceptedFileType = {\n label: string\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n}\n\ntype FileUploadProps = {\n accept?: string\n acceptedFileTypes?: AcceptedFileType[]\n borderBeamTheme?: React.ComponentProps<typeof BorderBeam>["theme"]\n browseLabel?: string\n className?: string\n description?: string\n draggingLabel?: string\n multiple?: boolean\n showBorderBeam?: boolean\n showFileList?: boolean\n title?: string\n onFilesAccepted?: (files: File[]) => void\n onFilesChange?: (files: FileUploadItem[]) => void\n}\n\nconst ACCEPTED_FILE_TYPES: AcceptedFileType[] = [\n { label: "Image", icon: FileImageIcon },\n { label: "PDF", icon: FileUploadIcon },\n { label: "Sheet", icon: FileSpreadsheetIcon },\n]\nconst ICON_TRANSFORMS = [\n {\n idle: "translate(-78%, -50%) rotate(-8deg)",\n active: "translate(-114%, -50%) rotate(-12deg) scale(1.08)",\n },\n {\n idle: "translate(-50%, -50%) rotate(0deg)",\n active: "translate(-50%, -50%) rotate(0deg) scale(1.18)",\n },\n {\n idle: "translate(-22%, -50%) rotate(8deg)",\n active: "translate(14%, -50%) rotate(12deg) scale(1.08)",\n },\n]\n\nfunction formatBytes(bytes: number) {\n if (bytes === 0) return "0 B"\n\n const units = ["B", "KB", "MB", "GB"]\n const index = Math.min(\n Math.floor(Math.log(bytes) / Math.log(1024)),\n units.length - 1\n )\n\n return `${(bytes / 1024 ** index).toFixed(index === 0 ? 0 : 1)} ${\n units[index]\n }`\n}\n\nfunction matchesAccept(file: File, accept?: string) {\n if (!accept) return true\n\n return accept.split(",").some((rawToken) => {\n const token = rawToken.trim().toLowerCase()\n\n if (!token) return false\n if (token.startsWith(".")) return file.name.toLowerCase().endsWith(token)\n if (token.endsWith("/*")) {\n return file.type.toLowerCase().startsWith(token.slice(0, -1))\n }\n\n return file.type.toLowerCase() === token\n })\n}\n\nfunction toUploadItems(files: FileList | File[]): FileUploadItem[] {\n return Array.from(files).map((file) => ({\n id: `${file.name}-${file.size}-${file.lastModified}`,\n name: file.name,\n type: file.type || "Unknown type",\n size: file.size,\n url: URL.createObjectURL(file),\n }))\n}\n\nfunction UploadIconCluster({\n acceptedFileTypes,\n isDragging,\n}: {\n acceptedFileTypes: AcceptedFileType[]\n isDragging: boolean\n}) {\n const singleIcon = acceptedFileTypes.length === 1\n\n return (\n <div className="relative h-14 w-36">\n {acceptedFileTypes.map((item, index) => (\n <Card\n key={item.label}\n className={cn(\n "absolute top-1/2 left-1/2 grid size-12 place-items-center rounded-xl bg-background text-muted-foreground transition-[transform,color,background-color] duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] before:rounded-[calc(var(--radius-xl)-1px)]",\n "motion-reduce:transition-none",\n index === 1 && "z-10",\n isDragging &&\n "bg-popover text-foreground shadow-md shadow-black/10 not-dark:bg-clip-border dark:shadow-black/25"\n )}\n style={{\n transform: singleIcon\n ? `translate(-50%, -50%) scale(${isDragging ? 1.14 : 1})`\n : isDragging\n ? ICON_TRANSFORMS[index]?.active\n : ICON_TRANSFORMS[index]?.idle,\n }}\n >\n <HugeiconsIcon icon={item.icon} className="size-5" />\n </Card>\n ))}\n </div>\n )\n}\n\nexport function FileUpload({\n accept,\n acceptedFileTypes = ACCEPTED_FILE_TYPES,\n borderBeamTheme = "light",\n browseLabel = "Browse files",\n className,\n description = "PDF, DOCX, XLSX, CSV, PNG, or JPG",\n draggingLabel = "Drop to add",\n multiple = true,\n showBorderBeam = true,\n showFileList = true,\n title = "Click to upload or drop files",\n onFilesAccepted,\n onFilesChange,\n}: FileUploadProps) {\n const dragDepthRef = React.useRef(0)\n const inputRef = React.useRef<HTMLInputElement>(null)\n const [isDragging, setIsDragging] = React.useState(false)\n const [files, setFiles] = React.useState<FileUploadItem[]>([])\n const [rejectionMessage, setRejectionMessage] = React.useState<string | null>(\n null\n )\n\n const commitFiles = React.useCallback(\n (nextFiles: FileList | File[]) => {\n const acceptedFiles = Array.from(nextFiles)\n .filter((file) => matchesAccept(file, accept))\n .slice(0, multiple ? undefined : 1)\n\n if (acceptedFiles.length === 0) {\n setRejectionMessage("This file type is not supported here.")\n return\n }\n\n setRejectionMessage(null)\n onFilesAccepted?.(acceptedFiles)\n\n const items = toUploadItems(acceptedFiles)\n setFiles((previousFiles) => {\n previousFiles.forEach((file) => URL.revokeObjectURL(file.url))\n return items\n })\n onFilesChange?.(items)\n },\n [accept, multiple, onFilesAccepted, onFilesChange]\n )\n\n React.useEffect(() => {\n return () => {\n files.forEach((file) => URL.revokeObjectURL(file.url))\n }\n }, [files])\n\n const openFileDialog = React.useCallback(() => {\n inputRef.current?.click()\n }, [])\n\n const dropzone = (\n <div\n role="button"\n tabIndex={0}\n className={cn(\n "relative flex min-h-64 cursor-pointer flex-col items-center justify-center gap-5 overflow-hidden rounded-[1.125rem] border border-dashed bg-background px-6 py-10 text-center transition-[border-color,background-color] duration-200 ease-out",\n "motion-reduce:transition-none",\n isDragging\n ? "border-foreground/40 bg-accent/35"\n : "border-foreground/20 hover:border-foreground/35 hover:bg-muted/35 dark:border-foreground/25 dark:hover:border-foreground/40"\n )}\n onClick={openFileDialog}\n onDragEnter={(event) => {\n event.preventDefault()\n dragDepthRef.current += 1\n setIsDragging(true)\n }}\n onDragLeave={(event) => {\n event.preventDefault()\n dragDepthRef.current = Math.max(0, dragDepthRef.current - 1)\n if (dragDepthRef.current === 0) setIsDragging(false)\n }}\n onDragOver={(event) => event.preventDefault()}\n onDrop={(event) => {\n event.preventDefault()\n dragDepthRef.current = 0\n setIsDragging(false)\n if (event.dataTransfer.files.length > 0) {\n commitFiles(event.dataTransfer.files)\n }\n }}\n onKeyDown={(event) => {\n if (event.key === "Enter" || event.key === " ") {\n event.preventDefault()\n openFileDialog()\n }\n }}\n >\n <UploadIconCluster\n acceptedFileTypes={acceptedFileTypes}\n isDragging={isDragging}\n />\n <div className="space-y-1">\n <div className="text-sm font-medium">{title}</div>\n <div className="text-xs text-muted-foreground">{description}</div>\n {rejectionMessage ? (\n <div className="text-xs text-destructive">{rejectionMessage}</div>\n ) : null}\n </div>\n <div className="inline-flex items-center gap-2 rounded-full border bg-background px-3 py-1 text-xs text-muted-foreground">\n <HugeiconsIcon icon={Upload01Icon} className="size-3.5" />\n <span>{isDragging ? draggingLabel : browseLabel}</span>\n </div>\n <input\n ref={inputRef}\n type="file"\n accept={accept}\n multiple={multiple}\n className="hidden"\n onChange={(event) => {\n if (event.target.files) {\n commitFiles(event.target.files)\n event.currentTarget.value = ""\n }\n }}\n />\n </div>\n )\n\n return (\n <div className={cn("space-y-3", className)}>\n {showBorderBeam ? (\n <BorderBeam\n active={isDragging}\n borderRadius={18}\n brightness={2.4}\n className="rounded-[1.125rem]"\n colorVariant="ocean"\n duration={2.4}\n size="md"\n strength={1}\n theme={borderBeamTheme}\n >\n {dropzone}\n </BorderBeam>\n ) : (\n dropzone\n )}\n {showFileList && files.length > 0 ? (\n <div className="rounded-xl border bg-background">\n {files.map((file) => (\n <div\n key={file.id}\n className="flex items-center gap-3 border-b px-3 py-2.5 last:border-b-0"\n >\n <FileThumbnail\n file={{\n name: file.name,\n type: file.type,\n }}\n previewImageUrl={\n file.type.startsWith("image/") ? file.url : null\n }\n className="size-10 shrink-0 rounded-lg"\n />\n <div className="min-w-0 flex-1">\n <div className="truncate text-sm font-medium">{file.name}</div>\n <div className="truncate text-xs text-muted-foreground">\n {file.type} - {formatBytes(file.size)}\n </div>\n </div>\n <div className="rounded-full bg-muted px-2 py-1 text-xs text-muted-foreground">\n Ready\n </div>\n </div>\n ))}\n </div>\n ) : null}\n </div>\n )\n}'
+ '"use client"\n\nimport * as React from "react"\nimport {\n FileImageIcon,\n FileSpreadsheetIcon,\n FileUploadIcon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { BorderBeam } from "border-beam"\n\nimport { cn } from "@/lib/utils"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Card } from "@/components/ui/card"\n\ntype FileUploadItem = {\n id: string\n name: string\n type: string\n size: number\n url: string\n}\n\ntype AcceptedFileType = {\n label: string\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n}\n\ntype FileUploadProps = {\n accept?: string\n acceptedFileTypes?: AcceptedFileType[]\n borderBeamTheme?: React.ComponentProps<typeof BorderBeam>["theme"]\n browseLabel?: string\n className?: string\n description?: string\n draggingLabel?: string\n multiple?: boolean\n showBorderBeam?: boolean\n showFileList?: boolean\n title?: string\n onFilesAccepted?: (files: File[]) => void\n onFilesChange?: (files: FileUploadItem[]) => void\n}\n\nconst ACCEPTED_FILE_TYPES: AcceptedFileType[] = [\n { label: "Image", icon: FileImageIcon },\n { label: "PDF", icon: FileUploadIcon },\n { label: "Sheet", icon: FileSpreadsheetIcon },\n]\nconst ICON_TRANSFORMS = [\n {\n idle: "translate(-78%, -50%) rotate(-8deg)",\n active: "translate(-114%, -50%) rotate(-12deg) scale(1.08)",\n },\n {\n idle: "translate(-50%, -50%) rotate(0deg)",\n active: "translate(-50%, -50%) rotate(0deg) scale(1.18)",\n },\n {\n idle: "translate(-22%, -50%) rotate(8deg)",\n active: "translate(14%, -50%) rotate(12deg) scale(1.08)",\n },\n]\n\nfunction formatBytes(bytes: number) {\n if (bytes === 0) return "0 B"\n\n const units = ["B", "KB", "MB", "GB"]\n const index = Math.min(\n Math.floor(Math.log(bytes) / Math.log(1024)),\n units.length - 1\n )\n\n return `${(bytes / 1024 ** index).toFixed(index === 0 ? 0 : 1)} ${\n units[index]\n }`\n}\n\nfunction matchesAccept(file: File, accept?: string) {\n if (!accept) return true\n\n return accept.split(",").some((rawToken) => {\n const token = rawToken.trim().toLowerCase()\n\n if (!token) return false\n if (token.startsWith(".")) return file.name.toLowerCase().endsWith(token)\n if (token.endsWith("/*")) {\n return file.type.toLowerCase().startsWith(token.slice(0, -1))\n }\n\n return file.type.toLowerCase() === token\n })\n}\n\nfunction toUploadItems(files: FileList | File[]): FileUploadItem[] {\n return Array.from(files).map((file) => ({\n id: `${file.name}-${file.size}-${file.lastModified}`,\n name: file.name,\n type: file.type || "Unknown type",\n size: file.size,\n url: URL.createObjectURL(file),\n }))\n}\n\nfunction UploadIconCluster({\n acceptedFileTypes,\n isDragging,\n}: {\n acceptedFileTypes: AcceptedFileType[]\n isDragging: boolean\n}) {\n const singleIcon = acceptedFileTypes.length === 1\n\n return (\n <div className="relative h-14 w-36">\n {acceptedFileTypes.map((item, index) => (\n <Card\n key={item.label}\n className={cn(\n "absolute top-1/2 left-1/2 grid size-12 place-items-center rounded-xl bg-background text-muted-foreground transition-[transform,color,background-color] duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] before:rounded-[calc(var(--radius-xl)-1px)]",\n "motion-reduce:transition-none",\n index === 1 && "z-10",\n isDragging &&\n "bg-popover text-foreground shadow-md shadow-black/10 not-dark:bg-clip-border dark:shadow-black/25"\n )}\n style={{\n transform: singleIcon\n ? `translate(-50%, -50%) scale(${isDragging ? 1.14 : 1})`\n : isDragging\n ? ICON_TRANSFORMS[index]?.active\n : ICON_TRANSFORMS[index]?.idle,\n }}\n >\n <HugeiconsIcon icon={item.icon} className="size-5" />\n </Card>\n ))}\n </div>\n )\n}\n\nexport function FileUpload({\n accept,\n acceptedFileTypes = ACCEPTED_FILE_TYPES,\n borderBeamTheme = "light",\n browseLabel = "Browse files",\n className,\n description = "PDF, DOCX, XLSX, CSV, PNG, or JPG",\n draggingLabel = "Drop to add",\n multiple = true,\n showBorderBeam = true,\n showFileList = true,\n title = "Click to upload or drop files",\n onFilesAccepted,\n onFilesChange,\n}: FileUploadProps) {\n const dragDepthRef = React.useRef(0)\n const inputRef = React.useRef<HTMLInputElement>(null)\n const [isDragging, setIsDragging] = React.useState(false)\n const [files, setFiles] = React.useState<FileUploadItem[]>([])\n const [rejectionMessage, setRejectionMessage] = React.useState<string | null>(\n null\n )\n\n const commitFiles = React.useCallback(\n (nextFiles: FileList | File[]) => {\n const acceptedFiles = Array.from(nextFiles)\n .filter((file) => matchesAccept(file, accept))\n .slice(0, multiple ? undefined : 1)\n\n if (acceptedFiles.length === 0) {\n setRejectionMessage("This file type is not supported here.")\n return\n }\n\n setRejectionMessage(null)\n onFilesAccepted?.(acceptedFiles)\n\n const items = toUploadItems(acceptedFiles)\n setFiles((previousFiles) => {\n previousFiles.forEach((file) => URL.revokeObjectURL(file.url))\n return items\n })\n onFilesChange?.(items)\n },\n [accept, multiple, onFilesAccepted, onFilesChange]\n )\n\n React.useEffect(() => {\n return () => {\n files.forEach((file) => URL.revokeObjectURL(file.url))\n }\n }, [files])\n\n const openFileDialog = React.useCallback(() => {\n inputRef.current?.click()\n }, [])\n\n const dropzone = (\n <div\n role="button"\n tabIndex={0}\n className={cn(\n "relative flex min-h-64 cursor-pointer flex-col items-center justify-center gap-5 overflow-hidden rounded-[1.125rem] border border-dashed bg-background px-6 py-10 text-center transition-[border-color,background-color] duration-200 ease-out",\n "motion-reduce:transition-none",\n isDragging\n ? "border-foreground/40 bg-accent/35"\n : "border-foreground/20 hover:border-foreground/35 hover:bg-muted/35 dark:border-foreground/25 dark:hover:border-foreground/40"\n )}\n onClick={openFileDialog}\n onDragEnter={(event) => {\n event.preventDefault()\n dragDepthRef.current += 1\n setIsDragging(true)\n }}\n onDragLeave={(event) => {\n event.preventDefault()\n dragDepthRef.current = Math.max(0, dragDepthRef.current - 1)\n if (dragDepthRef.current === 0) setIsDragging(false)\n }}\n onDragOver={(event) => event.preventDefault()}\n onDrop={(event) => {\n event.preventDefault()\n dragDepthRef.current = 0\n setIsDragging(false)\n if (event.dataTransfer.files.length > 0) {\n commitFiles(event.dataTransfer.files)\n }\n }}\n onKeyDown={(event) => {\n if (event.key === "Enter" || event.key === " ") {\n event.preventDefault()\n openFileDialog()\n }\n }}\n >\n <UploadIconCluster\n acceptedFileTypes={acceptedFileTypes}\n isDragging={isDragging}\n />\n <div className="space-y-1">\n <div className="text-sm font-medium">{title}</div>\n <div className="text-xs text-muted-foreground">{description}</div>\n {rejectionMessage ? (\n <div className="text-xs text-destructive">{rejectionMessage}</div>\n ) : null}\n </div>\n <div className="inline-flex items-center gap-2 rounded-full border bg-background px-3 py-1 text-xs text-muted-foreground">\n <HugeiconsIcon icon={Upload01Icon} className="size-3.5" />\n <span>{isDragging ? draggingLabel : browseLabel}</span>\n </div>\n <input\n ref={inputRef}\n type="file"\n accept={accept}\n multiple={multiple}\n className="hidden"\n onChange={(event) => {\n if (event.target.files) {\n commitFiles(event.target.files)\n event.currentTarget.value = ""\n }\n }}\n />\n </div>\n )\n\n return (\n <div className={cn("space-y-3", className)}>\n {showBorderBeam ? (\n <BorderBeam\n active={isDragging}\n borderRadius={18}\n brightness={2.4}\n className="rounded-[1.125rem]"\n colorVariant="ocean"\n duration={2.4}\n size="md"\n strength={1}\n theme={borderBeamTheme}\n >\n {dropzone}\n </BorderBeam>\n ) : (\n dropzone\n )}\n {showFileList && files.length > 0 ? (\n <div className="rounded-xl border bg-background">\n {files.map((file) => (\n <div\n key={file.id}\n className="flex items-center gap-3 border-b px-3 py-2.5 last:border-b-0"\n >\n <FileThumbnail\n file={{\n name: file.name,\n type: file.type,\n }}\n previewImageUrl={\n file.type.startsWith("image/") ? file.url : null\n }\n className="size-10 shrink-0 rounded-lg"\n />\n <div className="min-w-0 flex-1">\n <div className="truncate text-sm font-medium">{file.name}</div>\n <div className="truncate text-xs text-muted-foreground">\n {file.type} - {formatBytes(file.size)}\n </div>\n </div>\n <div className="rounded-full bg-muted px-2 py-1 text-xs text-muted-foreground">\n Ready\n </div>\n </div>\n ))}\n </div>\n ) : null}\n </div>\n )\n}\n'
export function FileUploadSource() {
return (
diff --git a/apps/v4/components/ui/file-system.tsx b/apps/v4/components/ui/file-system.tsx
index 9cc74a2..3b16881 100644
--- a/apps/v4/components/ui/file-system.tsx
+++ b/apps/v4/components/ui/file-system.tsx
@@ -771,32 +771,6 @@ export function FileSystem({
selectEntry(null)
}, [selectEntry])
- // Finder shortcuts: ⌘↑ encloses, ⌘↓ opens the selection, ⌘[ / ⌘] navigate
- // history. Fires for keydown anywhere inside the component — including the
- // portaled viewer dialog (React events propagate through portals), so bail
- // while a file is open.
- const handleRootKeyDown = (event: React.KeyboardEvent) => {
- if (openedFile) return
- if (!(event.metaKey || event.ctrlKey)) return
-
- if (event.key === "ArrowUp") {
- if (currentPath === "") return
- navigateTo(pathParent(currentPath))
- } else if (event.key === "ArrowDown") {
- if (!selectedEntry) return
- openEntry(selectedEntry)
- } else if (event.key === "[") {
- if (!canGoBack) return
- goBack()
- } else if (event.key === "]") {
- if (!canGoForward) return
- goForward()
- } else {
- return
- }
- event.preventDefault()
- }
-
const currentEntries = index.children.get(currentPath) ?? []
const currentFolderName =
currentPath === "" ? title : pathName(currentPath) || title
@@ -833,7 +807,6 @@ export function FileSystem({
<div
ref={rootRef}
tabIndex={-1}
- onKeyDown={handleRootKeyDown}
className={cn(
"flex h-[480px] min-h-0 flex-col overflow-hidden rounded-xl border bg-background text-foreground outline-none",
className
@@ -844,7 +817,7 @@ export function FileSystem({
<button
type="button"
aria-label="Back"
- title="Back (⌘[)"
+ title="Back"
disabled={!canGoBack}
onClick={goBack}
className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"
@@ -854,7 +827,7 @@ export function FileSystem({
<button
type="button"
aria-label="Forward"
- title="Forward (⌘])"
+ title="Forward"
disabled={!canGoForward}
onClick={goForward}
className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"