Skip to content

armgit / ui

Public Imported from GitHub
0
TypeScript

Fix theme-aware CSV and XLSX viewer performance

Andrew Luo2cc907613f4c
diff --git a/apps/v4/app/(app)/blocks/layout.tsx b/apps/v4/app/(app)/blocks/layout.tsx
index 7e5a116..2bf8b6a 100644
--- a/apps/v4/app/(app)/blocks/layout.tsx
+++ b/apps/v4/app/(app)/blocks/layout.tsx
@@ -11,7 +11,7 @@ import {
const title = "Document Blocks"
const description =
- "Composed PDF viewer workflows built from citations, OCR blocks, signing fields, and document splits."
+ "Composed PDF viewer workflows built from OCR blocks, signing fields, and document splits."
export const metadata: Metadata = {
title,
diff --git a/apps/v4/app/(app)/blocks/page.tsx b/apps/v4/app/(app)/blocks/page.tsx
index a0e07f0..8340b04 100644
--- a/apps/v4/app/(app)/blocks/page.tsx
+++ b/apps/v4/app/(app)/blocks/page.tsx
@@ -26,7 +26,6 @@ export const revalidate = false
const blockIds = [
"pdf-dropzone",
- "citations",
"ocr-blocks",
"e-signature",
"human-review",
@@ -37,7 +36,6 @@ const blockIds = [
const blockCodeDependencies: Record<string, string[]> = {
"pdf-dropzone": ["file-upload", "pdf-viewer", "file-thumbnail"],
- citations: ["pdf-block-resizable-shell", "pdf-viewer", "file-thumbnail"],
"ocr-blocks": ["pdf-block-resizable-shell", "pdf-viewer", "file-thumbnail"],
"e-signature": ["pdf-block-resizable-shell", "pdf-viewer", "file-thumbnail"],
"human-review": ["pdf-block-resizable-shell", "pdf-viewer", "file-thumbnail"],
diff --git a/apps/v4/components/citations-docs.tsx b/apps/v4/components/citations-docs.tsx
deleted file mode 100644
index 3607296..0000000
--- a/apps/v4/components/citations-docs.tsx
+++ /dev/null
@@ -1,485 +0,0 @@
-"use client"
-
-import * as React from "react"
-
-import { cn } from "@/lib/utils"
-import { Button } from "@/components/ui/button"
-import { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"
-import { ScrollArea } from "@/components/ui/scroll-area"
-import { HighlightedCodeBlock } from "@/components/highlighted-code-block"
-import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"
-
-type Point = {
- x: number
- y: number
-}
-
-type Citation = {
- id: string
- description: string
- value: string
- page: number
- polygon: Point[]
-}
-
-type HighlightArea = {
- left: number
- top: number
- width: number
- height: number
-}
-
-const PDF_URL = "/samples/attention.pdf"
-const ANNOTATION_PAGE_WIDTH = 792
-const ANNOTATION_PAGE_HEIGHT = 612
-const DEFAULT_ZOOM = 0.75
-const CITATION_STYLE = {
- active:
- "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_8%)]",
- overlay:
- "border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_12%)]",
-}
-
-const CITATIONS: Citation[] = [
- {
- id: "title",
- description: "Paper title extracted from the first page heading.",
- value: "Attention Is All You Need",
- page: 1,
- polygon: [
- { x: 246, y: 188 },
- { x: 566, y: 188 },
- { x: 566, y: 222 },
- { x: 246, y: 222 },
- ],
- },
- {
- id: "authors",
- description: "Authors listed beneath the paper title.",
- value:
- "Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser, Polosukhin",
- page: 1,
- polygon: [
- { x: 92, y: 206 },
- { x: 698, y: 206 },
- { x: 698, y: 270 },
- { x: 92, y: 270 },
- ],
- },
- {
- id: "abstract",
- description: "Central model claim from the abstract.",
- value:
- "The Transformer relies entirely on attention mechanisms and avoids recurrence and convolutions.",
- page: 1,
- polygon: [
- { x: 108, y: 346 },
- { x: 692, y: 346 },
- { x: 692, y: 414 },
- { x: 108, y: 414 },
- ],
- },
- {
- id: "bleu",
- description: "Reported machine translation benchmark result.",
- value: "28.4 BLEU on WMT 2014 English-to-German",
- page: 1,
- polygon: [
- { x: 108, y: 412 },
- { x: 692, y: 412 },
- { x: 692, y: 458 },
- { x: 108, y: 458 },
- ],
- },
- {
- id: "architecture",
- description: "Architecture property described in the background section.",
- value:
- "Self-attention connects positions in a sequence through constant-time operations.",
- page: 2,
- polygon: [
- { x: 76, y: 74 },
- { x: 718, y: 74 },
- { x: 718, y: 184 },
- { x: 76, y: 184 },
- ],
- },
-]
-
-function convertPolygonToHighlightArea(polygon: Point[]): HighlightArea {
- const xValues = polygon.map((point) => point.x)
- const yValues = polygon.map((point) => point.y)
- const left = Math.min(...xValues)
- const right = Math.max(...xValues)
- const top = Math.min(...yValues)
- const bottom = Math.max(...yValues)
-
- return {
- left: (left / ANNOTATION_PAGE_WIDTH) * 100,
- top: (top / ANNOTATION_PAGE_HEIGHT) * 100,
- width: ((right - left) / ANNOTATION_PAGE_WIDTH) * 100,
- height: ((bottom - top) / ANNOTATION_PAGE_HEIGHT) * 100,
- }
-}
-
-function CitationHighlight({ citation }: { citation: Citation }) {
- const highlight = convertPolygonToHighlightArea(citation.polygon)
-
- return (
- <div
- className={cn(
- "pointer-events-none absolute z-10 rounded-[3px] border",
- CITATION_STYLE.overlay
- )}
- style={{
- left: `${highlight.left}%`,
- top: `${highlight.top}%`,
- width: `${highlight.width}%`,
- height: `${highlight.height}%`,
- }}
- />
- )
-}
-
-function CitationsPanel({
- activeCitationId,
- className,
- onCitationFocus,
-}: {
- activeCitationId?: string
- className?: string
- onCitationFocus?: (citation: Citation) => void
-}) {
- const [localActiveCitationId, setLocalActiveCitationId] = React.useState(
- activeCitationId ?? CITATIONS[0].id
- )
- const activeCitation =
- CITATIONS.find(
- (citation) => citation.id === (activeCitationId ?? localActiveCitationId)
- ) ?? CITATIONS[0]
-
- const focusCitation = React.useCallback(
- (citation: Citation) => {
- setLocalActiveCitationId(citation.id)
- onCitationFocus?.(citation)
- },
- [onCitationFocus]
- )
-
- return (
- <aside
- className={cn("flex h-[420px] min-h-0 flex-col bg-background", className)}
- >
- <ScrollArea className="min-h-0 flex-1" scrollFade>
- <div className="p-3">
- <div className="space-y-2">
- {CITATIONS.map((citation) => {
- const isActive = citation.id === activeCitation.id
-
- return (
- <button
- key={citation.id}
- type="button"
- onClick={() => focusCitation(citation)}
- onFocus={() => focusCitation(citation)}
- onMouseEnter={() => focusCitation(citation)}
- className={cn(
- "w-full rounded-lg border bg-background p-3 text-left transition-[border-color,background-color,box-shadow] hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:border-blue-500/60 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",
- isActive && CITATION_STYLE.active
- )}
- >
- <div className="mb-3 flex min-h-8 items-start justify-between gap-3">
- <div className="min-w-0">
- <div className="truncate text-sm font-medium">
- {citation.id}
- </div>
- <div className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">
- {citation.description}
- </div>
- </div>
- <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">
- p. {citation.page}
- </div>
- </div>
- <div className="rounded-md border bg-muted/30 p-2">
- <div className="min-h-7 rounded-md bg-background px-2 py-1.5 text-sm">
- {citation.value}
- </div>
- </div>
- </button>
- )
- })}
- </div>
- </div>
- </ScrollArea>
- </aside>
- )
-}
-
-export function Citations() {
- return <CitationsPanel />
-}
-
-export function CitationsBlock() {
- const [activeCitationId, setActiveCitationId] = React.useState(
- CITATIONS[0].id
- )
- const viewerRef = React.useRef<PDFViewerHandle>(null)
- const activeCitation =
- CITATIONS.find((citation) => citation.id === activeCitationId) ??
- CITATIONS[0]
-
- const scrollToCitation = React.useCallback((citation: Citation) => {
- setActiveCitationId(citation.id)
- viewerRef.current?.scrollToPageArea(
- citation.page,
- convertPolygonToHighlightArea(citation.polygon)
- )
- }, [])
-
- return (
- <PdfBlockResizableShell
- autoSaveId="pdf-block-citations"
- left={
- <PDFViewer
- ref={viewerRef}
- file={PDF_URL}
- defaultZoom={DEFAULT_ZOOM}
- renderPageOverlay={({ pageNumber }) =>
- activeCitation.page === pageNumber ? (
- <CitationHighlight citation={activeCitation} />
- ) : null
- }
- />
- }
- right={
- <CitationsPanel
- activeCitationId={activeCitation.id}
- className="h-full"
- onCitationFocus={scrollToCitation}
- />
- }
- />
- )
-}
-
-function CitationExampleCard({
- active,
- accentClassName,
- fieldKey,
- pageLabel,
- description,
- value,
-}: {
- active?: boolean
- accentClassName?: string
- fieldKey: string
- pageLabel: string
- description: string
- value: string
-}) {
- return (
- <button
- type="button"
- className={cn(
- "w-full rounded-lg border bg-background p-3 text-left transition-[border-color,background-color,box-shadow] hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",
- active &&
- (accentClassName ??
- "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_8%)]")
- )}
- >
- <div className="mb-3 flex min-h-8 items-start justify-between gap-3">
- <div className="min-w-0">
- <div className="truncate text-sm font-medium">{fieldKey}</div>
- <div className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">
- {description}
- </div>
- </div>
- <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">
- {pageLabel}
- </div>
- </div>
- <div className="rounded-md border bg-muted/30 p-2">
- <div className="min-h-7 rounded-md bg-background px-2 py-1.5 text-sm">
- {value}
- </div>
- </div>
- </button>
- )
-}
-
-function CitationsExample() {
- return (
- <div className="flex h-[420px] flex-col gap-2 bg-background p-3">
- <CitationExampleCard
- active
- fieldKey="invoice_total"
- pageLabel="p. 1"
- value="$12,480.00"
- description="Total amount due, including tax and service fees."
- />
- <CitationExampleCard
- fieldKey="payment_terms"
- pageLabel="p. 2"
- value="Net 30"
- description="Payment is due within thirty days of receipt."
- accentClassName="border-emerald-500/60 bg-emerald-500/5"
- />
- <CitationExampleCard
- fieldKey="purchase_order"
- pageLabel="p. 3"
- value="PO-1048"
- description="Customer purchase order identifier."
- accentClassName="border-amber-500/60 bg-amber-500/5"
- />
- </div>
- )
-}
-
-export function CitationsDemo() {
- const [isCodeVisible, setIsCodeVisible] = React.useState(false)
-
- return (
- <div
- data-slot="component-preview"
- className="group relative mt-4 mb-12 flex flex-col overflow-hidden rounded-xl border"
- >
- <CitationsExample />
- <div
- data-slot="code"
- data-mobile-code-visible={isCodeVisible}
- className="relative overflow-hidden **:data-[slot=copy-button]:right-4 **:data-[slot=copy-button]:hidden data-[mobile-code-visible=true]:**:data-[slot=copy-button]:flex [&_[data-rehype-pretty-code-figure]]:m-0! [&_[data-rehype-pretty-code-figure]]:rounded-t-none [&_[data-rehype-pretty-code-figure]]:border-t [&_pre]:max-h-72"
- >
- {isCodeVisible ? (
- <HighlightedCodeBlock
- code={citationsUsageCode}
- className="rounded-none border-x-0 border-b-0"
- />
- ) : (
- <div className="relative">
- <HighlightedCodeBlock
- code={citationsUsageCode}
- className="rounded-none border-x-0 border-b-0"
- maxHeightClassName="max-h-56"
- previewLines={10}
- showCopy={false}
- />
- <div className="absolute inset-0 flex items-center justify-center pb-4">
- <div
- className="absolute inset-0"
- style={{
- background:
- "linear-gradient(to top, var(--color-code), color-mix(in oklab, var(--color-code) 60%, transparent), transparent)",
- }}
- />
- <Button
- type="button"
- size="sm"
- variant="outline"
- className="relative z-10 rounded-lg bg-background text-foreground shadow-none hover:bg-muted dark:bg-background dark:text-foreground dark:hover:bg-muted"
- onClick={() => setIsCodeVisible(true)}
- >
- View Code
- </Button>
- </div>
- </div>
- )}
- </div>
- </div>
- )
-}
-
-const citationsUsageCode = `"use client";
-
-import { CitationCard } from "@/components/ui/citation-card";
-
-export function CitationsExample() {
- return (
- <div className="flex h-[420px] flex-col gap-2 bg-background p-3">
- <CitationCard
- active
- fieldKey="invoice_total"
- pageLabel="p. 1"
- value="$12,480.00"
- description="Total amount due, including tax and service fees."
- />
- <CitationCard
- fieldKey="payment_terms"
- pageLabel="p. 2"
- value="Net 30"
- description="Payment is due within thirty days of receipt."
- accentClassName="border-emerald-500/60 bg-emerald-500/5"
- />
- <CitationCard
- fieldKey="purchase_order"
- pageLabel="p. 3"
- value="PO-1048"
- description="Customer purchase order identifier."
- accentClassName="border-amber-500/60 bg-amber-500/5"
- />
- </div>
- );
-}`
-
-const citationsSourceCode = `"use client";
-
-import * as React from "react";
-
-import { cn } from "@/lib/utils";
-
-type CitationCardProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
- fieldKey: string;
- value: string;
- description?: string;
- pageLabel?: string;
- active?: boolean;
- accentClassName?: string;
-};
-
-export function CitationCard({
- fieldKey,
- value,
- description,
- pageLabel,
- active = false,
- accentClassName = "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_8%)]",
- className,
- ...props
-}: CitationCardProps) {
- return (
- <button
- type="button"
- className={cn(
- "w-full rounded-lg border bg-background p-3 text-left transition-[border-color,background-color,box-shadow] hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",
- active && accentClassName,
- className,
- )}
- {...props}
- >
- <div className="mb-3 flex min-h-8 items-start justify-between gap-3">
- <div className="min-w-0">
- <div className="truncate text-sm font-medium">{fieldKey}</div>
- {description ? (
- <div className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">
- {description}
- </div>
- ) : null}
- </div>
- {pageLabel ? (
- <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">
- {pageLabel}
- </div>
- ) : null}
- </div>
- <div className="rounded-md border bg-muted/30 p-2">
- <div className="min-h-7 rounded-md bg-background px-2 py-1.5 text-sm">
- {value}
- </div>
- </div>
- </button>
- );
-}`
-
-export function CitationsSource() {
- return <HighlightedCodeBlock code={citationsSourceCode} />
-}
diff --git a/apps/v4/components/csv-viewer-docs.tsx b/apps/v4/components/csv-viewer-docs.tsx
index b0fc812..5cb4802 100644
--- a/apps/v4/components/csv-viewer-docs.tsx
+++ b/apps/v4/components/csv-viewer-docs.tsx
@@ -264,9 +264,40 @@ function ToolbarTooltip({
)
}
+function readIsDarkTheme() {
+ return (
+ typeof document !== "undefined" &&
+ document.documentElement.classList.contains("dark")
+ )
+}
+
+function useIsDarkTheme() {
+ const [isDark, setIsDark] = React.useState(readIsDarkTheme)
+
+ React.useEffect(() => {
+ if (typeof document === "undefined") return
+
+ const updateTheme = () => setIsDark(readIsDarkTheme())
+
+ updateTheme()
+
+ if (typeof MutationObserver === "undefined") return
+
+ const observer = new MutationObserver(updateTheme)
+ observer.observe(document.documentElement, {
+ attributes: true,
+ attributeFilter: ["class"],
+ })
+
+ return () => observer.disconnect()
+ }, [])
+
+ return isDark
+}
+
export function CsvViewer({ className, data }: CsvViewerProps) {
const inputRef = React.useRef<HTMLInputElement | null>(null)
- const isDark = false
+ const isDark = useIsDarkTheme()
const [glide, setGlide] = React.useState<GlideDataGridModule | null>(null)
const [zoom, setZoom] = React.useState<(typeof ZOOM_OPTIONS)[number]>(1)
const [parsed, setParsed] = React.useState(() =>
diff --git a/apps/v4/components/docx-editor-docs.tsx b/apps/v4/components/docx-editor-docs.tsx
index 68ca5e4..542a076 100644
--- a/apps/v4/components/docx-editor-docs.tsx
+++ b/apps/v4/components/docx-editor-docs.tsx
@@ -90,7 +90,7 @@ export function DocxEditorExample() {
}`
const docxEditorSourceCode =
- '"use client"\n\nimport * as React from "react"\nimport { PreviewCard as PreviewCardPrimitive } from "@base-ui/react/preview-card"\nimport {\n DocxEditorViewer,\n paragraphLetterheadFloatSideAtNodeIndex,\n useDocxBorders,\n useDocxDocumentTheme,\n useDocxEditor,\n useDocxLineSpacing,\n useDocxPageLayout,\n useDocxParagraphStyles,\n useDocxTrackChanges,\n useDocxViewerThumbnails,\n type DocxBorderContext,\n type DocxBorderPreset,\n type DocxDocumentTheme,\n type DocxEditorController,\n type ParagraphStyleDefinition,\n} from "@extend-ai/react-docx"\nimport {\n ArrowExpandDiagonal01Icon,\n ArrowExpandDiagonal02Icon,\n BorderAll01Icon,\n BorderBottom01Icon,\n BorderHorizontalIcon,\n BorderInnerIcon,\n BorderLeft01Icon,\n BorderNone01Icon,\n BorderRight01Icon,\n BorderTop01Icon,\n BorderVerticalIcon,\n ColumnsThreeCogIcon,\n Download01Icon,\n EditOffIcon,\n FileDiffIcon,\n HighlighterIcon,\n ImageAdd01Icon,\n LeftToRightListBulletIcon,\n LeftToRightListNumberIcon,\n LineIcon,\n Link02Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n Redo02Icon,\n SidebarLeftIcon,\n Sun03Icon,\n TableIcon,\n TextAlignCenterIcon,\n TextAlignJustifyLeftIcon,\n TextAlignLeft01Icon,\n TextAlignRight01Icon,\n TextBoldIcon,\n TextColorIcon,\n TextItalicIcon,\n TextStrikethroughIcon,\n TextSubscriptIcon,\n TextSuperscriptIcon,\n TextUnderlineIcon,\n Undo02Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { useTheme } from "next-themes"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Input } from "@/components/ui/input"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/registry/new-york-v4/ui/dropdown-menu"\nimport { Separator } from "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_SOURCE_CACHE_LIMIT = 3\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_EDITOR_DEFAULT_ZOOM_SCALE = 75\nconst ZOOM_OPTIONS = [50, 75, 90, 100, 110, 125, 150, 175, 200] as const\nconst FONT_FAMILIES = [\n "Calibri",\n "Arial",\n "Times New Roman",\n "Georgia",\n "Helvetica",\n "Courier New",\n] as const\nconst FONT_SIZE_OPTIONS = [\n 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48,\n] as const\nconst LINE_SPACING_OPTIONS = [1, 1.15, 1.2, 1.5, 2, 2.5, 3] as const\nconst FALLBACK_PARAGRAPH_STYLE_OPTIONS = [\n { id: "Normal", name: "Body" },\n { id: "Heading1", name: "Heading 1" },\n { id: "Heading2", name: "Heading 2" },\n { id: "Heading3", name: "Heading 3" },\n] as const\nconst HIGHLIGHT_COLORS = [\n { label: "Yellow", value: "yellow", color: "#fff59d" },\n { label: "Green", value: "green", color: "#bbf7d0" },\n { label: "Cyan", value: "cyan", color: "#a5f3fc" },\n { label: "Magenta", value: "magenta", color: "#f5d0fe" },\n { label: "Red", value: "red", color: "#fecaca" },\n { label: "Blue", value: "blue", color: "#bfdbfe" },\n] as const\nconst HIGHLIGHT_PREVIEW_COLORS: Record<string, string> = {\n black: "#111827",\n white: "#ffffff",\n ...Object.fromEntries(\n HIGHLIGHT_COLORS.map((option) => [option.value, option.color])\n ),\n}\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\nconst DEFAULT_HEADING_PREVIEW_RUN_STYLES: Record<\n 1 | 2 | 3 | 4 | 5 | 6,\n NonNullable<ParagraphStyleDefinition["runStyle"]>\n> = {\n 1: {\n fontFamily: "Calibri Light",\n fontSizePt: 16,\n bold: true,\n color: "#2f5496",\n },\n 2: {\n fontFamily: "Calibri Light",\n fontSizePt: 13,\n bold: true,\n color: "#2f5496",\n },\n 3: {\n fontFamily: "Calibri",\n fontSizePt: 12,\n bold: true,\n color: "#1f3763",\n },\n 4: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 5: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 6: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n}\n\nconst docxFileCache = new Map<string, File>()\nconst docxFilePromiseCache = new Map<string, Promise<File>>()\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n}\n\ntype BorderControlOption = {\n id: DocxBorderPreset\n label: string\n contexts?: DocxBorderContext[]\n separatorBefore?: boolean\n}\n\nconst BORDER_CONTROL_OPTIONS: BorderControlOption[] = [\n { id: "bottom", label: "Bottom Border" },\n { id: "top", label: "Top Border" },\n { id: "left", label: "Left Border" },\n { id: "right", label: "Right Border" },\n { id: "none", label: "No Border", separatorBefore: true },\n { id: "all", label: "All Borders" },\n { id: "outside", label: "Outside Borders" },\n { id: "inside", label: "Inside Borders", contexts: ["table"] },\n {\n id: "inside-horizontal",\n label: "Inside Horizontal Border",\n contexts: ["table"],\n },\n {\n id: "inside-vertical",\n label: "Inside Vertical Border",\n contexts: ["table"],\n },\n {\n id: "diagonal-down",\n label: "Diagonal Down Border",\n contexts: ["table"],\n separatorBefore: true,\n },\n { id: "diagonal-up", label: "Diagonal Up Border", contexts: ["table"] },\n { id: "horizontal-line", label: "Horizontal Line", separatorBefore: true },\n]\n\nfunction borderControlOptionIcon(optionId: DocxBorderPreset) {\n switch (optionId) {\n case "bottom":\n return BorderBottom01Icon\n case "top":\n return BorderTop01Icon\n case "left":\n return BorderLeft01Icon\n case "right":\n return BorderRight01Icon\n case "none":\n return BorderNone01Icon\n case "inside":\n return BorderInnerIcon\n case "inside-horizontal":\n return BorderHorizontalIcon\n case "inside-vertical":\n return BorderVerticalIcon\n case "diagonal-down":\n return ArrowExpandDiagonal01Icon\n case "diagonal-up":\n return ArrowExpandDiagonal02Icon\n case "horizontal-line":\n return LineIcon\n default:\n return BorderAll01Icon\n }\n}\n\nfunction getDocumentCacheKey(url: string, fileName?: string) {\n return `${url.split("?")[0] ?? url}::${fileName ?? ""}`\n}\n\nfunction rememberDocxFile(cacheKey: string, file: File) {\n if (docxFileCache.has(cacheKey)) {\n docxFileCache.delete(cacheKey)\n }\n\n docxFileCache.set(cacheKey, file)\n\n while (docxFileCache.size > DOCX_SOURCE_CACHE_LIMIT) {\n const oldestKey = docxFileCache.keys().next().value\n if (!oldestKey) break\n docxFileCache.delete(oldestKey)\n }\n}\n\nasync function loadCachedDocxFile(\n url: string,\n displayFileName: string,\n cacheKey: string\n): Promise<File> {\n const cachedFile = docxFileCache.get(cacheKey)\n if (cachedFile) return cachedFile\n\n const pendingRequest = docxFilePromiseCache.get(cacheKey)\n if (pendingRequest) return pendingRequest\n\n const nextRequest = fetch(url)\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n const docxFile = new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n\n rememberDocxFile(cacheKey, docxFile)\n return docxFile\n })\n .finally(() => {\n docxFilePromiseCache.delete(cacheKey)\n })\n\n docxFilePromiseCache.set(cacheKey, nextRequest)\n return nextRequest\n}\n\nfunction formatDocumentName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "document.docx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {\n const currentIndex = ZOOM_OPTIONS.indexOf(\n currentZoomScale as (typeof ZOOM_OPTIONS)[number]\n )\n let fallbackIndex = -1\n\n if (direction > 0) {\n fallbackIndex = ZOOM_OPTIONS.findIndex((value) => value > currentZoomScale)\n } else {\n for (let index = ZOOM_OPTIONS.length - 1; index >= 0; index -= 1) {\n if (ZOOM_OPTIONS[index] < currentZoomScale) {\n fallbackIndex = index\n break\n }\n }\n }\n\n const resolvedIndex = currentIndex >= 0 ? currentIndex : fallbackIndex\n if (resolvedIndex < 0) return currentZoomScale\n\n const nextIndex = Math.min(\n Math.max(resolvedIndex + direction, 0),\n ZOOM_OPTIONS.length - 1\n )\n\n return ZOOM_OPTIONS[nextIndex] ?? currentZoomScale\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\n}\n\nfunction useDocumentNightRenderPreference() {\n const [nightRenderEnabled, setNightRenderEnabled] = React.useState(false)\n const [nightRenderPrefLoaded, setNightRenderPrefLoaded] =\n React.useState(false)\n\n React.useEffect(() => {\n const storedValue = window.localStorage.getItem("docx-editor-night-render")\n setNightRenderEnabled(storedValue === "true")\n setNightRenderPrefLoaded(true)\n }, [])\n\n const updateNightRenderEnabled = React.useCallback((checked: boolean) => {\n setNightRenderEnabled(checked)\n window.localStorage.setItem("docx-editor-night-render", String(checked))\n }, [])\n\n return {\n nightRenderEnabled,\n nightRenderPrefLoaded,\n setNightRenderEnabled: updateNightRenderEnabled,\n }\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction normalizeHexColor(value?: string, fallback = "#111827") {\n if (!value) return fallback\n\n const trimmed = value.trim()\n const threeDigit = /^#([0-9a-f]{3})$/i.exec(trimmed)\n if (threeDigit?.[1]) {\n const [red, green, blue] = threeDigit[1].split("")\n return `#${red}${red}${green}${green}${blue}${blue}`.toLowerCase()\n }\n\n const sixDigit = /^#([0-9a-f]{6})$/i.exec(trimmed)\n if (sixDigit?.[1]) {\n return `#${sixDigit[1].toLowerCase()}`\n }\n\n return fallback\n}\n\nfunction inferParagraphStyleHeadingLevel(value?: string) {\n if (!value) return undefined\n\n const match = value.match(/(?:^|[\\s_-])(?:heading|h)\\s*([1-6])(?:$|[\\s_-])/i)\n const level = match?.[1] ? Number(match[1]) : NaN\n\n return level >= 1 && level <= 6 ? (level as 1 | 2 | 3 | 4 | 5 | 6) : undefined\n}\n\nfunction resolveParagraphStyleHeadingLevel(option?: ParagraphStyleDefinition) {\n if (\n Number.isFinite(option?.headingLevel) &&\n option?.headingLevel &&\n option.headingLevel >= 1 &&\n option.headingLevel <= 6\n ) {\n return option.headingLevel as 1 | 2 | 3 | 4 | 5 | 6\n }\n\n return (\n inferParagraphStyleHeadingLevel(option?.id) ??\n inferParagraphStyleHeadingLevel(option?.name)\n )\n}\n\nfunction resolveParagraphStyleRunPreview(option?: ParagraphStyleDefinition) {\n if (!option) return undefined\n\n const headingLevel = resolveParagraphStyleHeadingLevel(option)\n const headingRunStyle = headingLevel\n ? DEFAULT_HEADING_PREVIEW_RUN_STYLES[headingLevel]\n : undefined\n\n return headingRunStyle\n ? {\n ...headingRunStyle,\n ...(option.runStyle ?? {}),\n }\n : option.runStyle\n}\n\nfunction resolveHighlightPreview(value?: string) {\n if (!value) return undefined\n\n const normalized = value.trim().toLowerCase()\n if (!normalized) return undefined\n\n const hex = normalizeHexColor(normalized, "")\n if (hex) return hex\n\n return HIGHLIGHT_PREVIEW_COLORS[normalized]\n}\n\nfunction themedPreviewColor(\n color: string | undefined,\n documentTheme: DocxDocumentTheme\n) {\n if (documentTheme !== "dark") return color\n if (!color) return "#f3f4f6"\n\n const normalized = color.trim().toLowerCase()\n if (\n normalized === "#000" ||\n normalized === "#000000" ||\n normalized === "#111111" ||\n normalized === "#111827" ||\n normalized === "black" ||\n normalized === "rgb(0,0,0)" ||\n normalized === "rgb(0, 0, 0)"\n ) {\n return "#f3f4f6"\n }\n\n return color\n}\n\nfunction paragraphStylePreviewStyle(\n option: ParagraphStyleDefinition,\n documentTheme: DocxDocumentTheme\n): React.CSSProperties {\n const runStyle = resolveParagraphStyleRunPreview(option)\n const textDecoration = [\n runStyle?.underline ? "underline" : "",\n runStyle?.strike ? "line-through" : "",\n ]\n .filter(Boolean)\n .join(" ")\n\n return {\n textAlign: option.align ?? "left",\n fontFamily: runStyle?.fontFamily,\n fontSize: runStyle?.fontSizePt ? `${runStyle.fontSizePt}pt` : "11pt",\n fontWeight:\n runStyle?.bold !== undefined ? (runStyle.bold ? 700 : 400) : undefined,\n fontStyle: runStyle?.italic ? "italic" : undefined,\n textDecoration: textDecoration || undefined,\n color:\n runStyle?.color !== undefined\n ? themedPreviewColor(normalizeHexColor(runStyle.color), documentTheme)\n : undefined,\n backgroundColor: resolveHighlightPreview(runStyle?.highlight),\n lineHeight: 1,\n whiteSpace: "pre-wrap",\n }\n}\n\nfunction paragraphStylePreviewTriggerId(prefix: string, styleId: string) {\n return `${prefix}-paragraph-style-preview-${styleId.replace(\n /[^a-zA-Z0-9_-]/g,\n "_"\n )}`\n}\n\nfunction parseToolbarSectionColumns(\n sectionPropertiesXml?: string\n): { count: number; gapPx: number } | undefined {\n if (!sectionPropertiesXml) return undefined\n\n const columnsTag = sectionPropertiesXml.match(/<w:cols\\b[^>]*\\/?>/i)?.[0]\n if (!columnsTag) return undefined\n\n const countRaw = columnsTag.match(/\\bw:num="(\\d+)"/i)?.[1]\n const count = countRaw ? Number(countRaw) : 1\n if (!Number.isFinite(count) || count <= 1) return undefined\n\n const gapRaw = columnsTag.match(/\\bw:space="(\\d+)"/i)?.[1]\n const gapTwips = gapRaw ? Number(gapRaw) : 720\n const gapPx = Math.max(0, Math.round((gapTwips * 96) / 1440))\n\n return {\n count: Math.max(2, Math.round(count)),\n gapPx,\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 EditorLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction ToolbarIconButton({\n active,\n children,\n label,\n ...props\n}: React.ComponentProps<typeof Button> & {\n active?: boolean\n label: string\n}) {\n return (\n <ToolbarTooltip label={label}>\n <Button\n type="button"\n variant={active ? "secondary" : "ghost"}\n size="icon-sm"\n aria-label={label}\n data-pressed={active ? "" : undefined}\n {...props}\n >\n {children}\n </Button>\n </ToolbarTooltip>\n )\n}\n\nfunction ToolbarColorInput({\n color,\n disabled,\n icon,\n label,\n onChange,\n}: {\n color: string\n disabled?: boolean\n icon: typeof TextColorIcon\n label: string\n onChange: (color: string) => void\n}) {\n return (\n <ToolbarTooltip label={label}>\n <label\n className={cn(\n "relative inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-lg border border-transparent text-foreground transition-colors hover:bg-accent",\n disabled && "pointer-events-none opacity-64"\n )}\n aria-label={label}\n >\n <HugeiconsIcon icon={icon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: color }}\n />\n <input\n type="color"\n aria-label={label}\n disabled={disabled}\n value={color}\n className="sr-only"\n onChange={(event) => onChange(event.target.value)}\n />\n </label>\n </ToolbarTooltip>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n showMetadata={false}\n className={cn(\n "w-full rounded-sm border shadow-xs transition-[border-color,box-shadow] duration-150",\n isActive && "border-primary shadow-sm"\n )}\n />\n )\n}\n\nfunction ParagraphStylePreviewCard({\n documentTheme,\n option,\n}: {\n documentTheme: DocxDocumentTheme\n option: ParagraphStyleDefinition\n}) {\n const surfaceStyle: React.CSSProperties =\n documentTheme === "dark"\n ? {\n backgroundColor: "#111827",\n borderColor: "#374151",\n color: "#f3f4f6",\n }\n : {\n backgroundColor: "#ffffff",\n borderColor: "#d4d4d8",\n color: "#111827",\n }\n const secondaryTextColor = documentTheme === "dark" ? "#9ca3af" : "#6b7280"\n\n return (\n <div className="w-[260px] p-3">\n <p className="text-[10px] font-medium tracking-wide text-muted-foreground uppercase">\n Style Preview\n </p>\n <div className="mt-2 rounded-sm border p-2.5" style={surfaceStyle}>\n <p style={paragraphStylePreviewStyle(option, documentTheme)}>\n {option.name}\n </p>\n <p\n className="mt-1 text-[11px]"\n style={{\n color: secondaryTextColor,\n textAlign: option.align ?? "left",\n }}\n >\n The quick brown fox jumps over the lazy dog.\n </p>\n </div>\n </div>\n )\n}\n\nfunction DocxEditorToolbar({\n activePage,\n controlsDisabled,\n editor,\n isReadOnly,\n onImageUploadClick,\n onIsReadOnlyChange,\n onOpenLinkEditor,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n editor: DocxEditorController\n isReadOnly: boolean\n onImageUploadClick: () => void\n onIsReadOnlyChange: (checked: boolean) => void\n onOpenLinkEditor: () => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showNightRenderToggle: boolean\n zoomScale: number\n}) {\n const { documentTheme, setDocumentTheme } = useDocxDocumentTheme(editor)\n const { layout: pageLayout } = useDocxPageLayout(editor)\n const { paragraphStyles, selectedParagraphStyleId, setParagraphStyle } =\n useDocxParagraphStyles(editor)\n const { lineSpacing, setLineSpacing } = useDocxLineSpacing(editor)\n const { borderContext, activeBorderPresets, applyBorderPreset } =\n useDocxBorders(editor)\n const { showTrackedChanges, setShowTrackedChanges } =\n useDocxTrackChanges(editor)\n const selectedRunStyle = editor.selectedRunStyle\n const selectedParagraph = editor.selectedParagraph\n const paragraphStyleOptions: ParagraphStyleDefinition[] =\n paragraphStyles.length > 0\n ? paragraphStyles\n : [...FALLBACK_PARAGRAPH_STYLE_OPTIONS]\n const selectedParagraphStyleValue =\n selectedParagraphStyleId ??\n paragraphStyleOptions.find((option) => "isDefault" in option)?.id ??\n paragraphStyleOptions[0]?.id ??\n "Normal"\n const selectedParagraphStyleOption =\n paragraphStyleOptions.find(\n (option) => option.id === selectedParagraphStyleValue\n ) ??\n paragraphStyleOptions[0] ??\n FALLBACK_PARAGRAPH_STYLE_OPTIONS[0]\n const paragraphStylePreviewHandle = React.useMemo(\n () => PreviewCardPrimitive.createHandle<ParagraphStyleDefinition>(),\n []\n )\n const paragraphStylePreviewIdPrefix = React.useId()\n const [isParagraphStyleMenuOpen, setIsParagraphStyleMenuOpen] =\n React.useState(false)\n const openParagraphStylePreview = React.useCallback(\n (styleId: string) => {\n paragraphStylePreviewHandle.open(\n paragraphStylePreviewTriggerId(paragraphStylePreviewIdPrefix, styleId)\n )\n },\n [paragraphStylePreviewHandle, paragraphStylePreviewIdPrefix]\n )\n const selectedLineSpacingValue = React.useMemo(() => {\n const current = Number.isFinite(lineSpacing.multiple)\n ? lineSpacing.multiple\n : 1\n const nearest = LINE_SPACING_OPTIONS.reduce((closest, candidate) => {\n return Math.abs(candidate - current) < Math.abs(closest - current)\n ? candidate\n : closest\n }, LINE_SPACING_OPTIONS[0])\n return String(nearest)\n }, [lineSpacing.multiple])\n const textColorValue = normalizeHexColor(selectedRunStyle?.color)\n const highlightColor =\n HIGHLIGHT_COLORS.find(\n (option) => option.value === selectedRunStyle?.highlight\n )?.color ?? "#fff59d"\n const activeNodeIndex =\n editor.selection.kind === "paragraph"\n ? editor.selection.nodeIndex\n : editor.selection.tableIndex\n const letterheadColumns =\n editor.selection.kind === "paragraph" &&\n paragraphLetterheadFloatSideAtNodeIndex(\n editor.model.nodes,\n editor.selection.nodeIndex\n )\n ? { count: 2, gapPx: 28 }\n : undefined\n const sections = editor.model.metadata.sections ?? []\n const activeSection = sections\n .filter((section) => section.startNodeIndex <= activeNodeIndex)\n .at(-1)\n const activeColumns =\n letterheadColumns ??\n parseToolbarSectionColumns(activeSection?.sectionPropertiesXml) ??\n parseToolbarSectionColumns(editor.model.metadata.sectionPropertiesXml) ??\n pageLayout.columns\n const activeBorderControlOptions = BORDER_CONTROL_OPTIONS.filter(\n (option) => activeBorderPresets[option.id]\n )\n const borderTriggerLabel =\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].label\n : "Borders"\n const borderTriggerIcon = borderControlOptionIcon(\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].id\n : "all"\n )\n const canEdit = !controlsDisabled && !isReadOnly\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n\n const preserveTextSelection = React.useCallback(\n (event: React.MouseEvent<HTMLElement> | React.PointerEvent<HTMLElement>) =>\n event.preventDefault(),\n []\n )\n\n return (\n <div className="border-b bg-background">\n <TooltipProvider>\n <div className="flex min-h-11 items-center gap-2 overflow-x-auto overflow-y-hidden border-b px-3">\n <ToolbarIconButton\n label="Toggle pages"\n disabled={controlsDisabled}\n onClick={onToggleSidebar}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </ToolbarIconButton>\n <div className="min-w-28 text-sm whitespace-nowrap text-primary">\n Page {pageCount ? activePage : 1} of {pageCount || "-"}\n </div>\n <div className="min-w-0 flex-1" />\n {showNightRenderToggle ? (\n <>\n <ToolbarIconButton\n label={\n documentTheme === "dark"\n ? "Use light document"\n : "Use dark document"\n }\n disabled={controlsDisabled}\n onClick={() =>\n setDocumentTheme(documentTheme === "dark" ? "light" : "dark")\n }\n >\n <HugeiconsIcon\n icon={documentTheme === "dark" ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </ToolbarIconButton>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <ToolbarIconButton\n label="Show tracked changes"\n active={showTrackedChanges}\n disabled={controlsDisabled}\n onClick={() => setShowTrackedChanges(!showTrackedChanges)}\n >\n <HugeiconsIcon icon={FileDiffIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label={isReadOnly ? "Switch to edit mode" : "Switch to read-only"}\n active={isReadOnly}\n disabled={controlsDisabled}\n onClick={() => onIsReadOnlyChange(!isReadOnly)}\n >\n <HugeiconsIcon icon={EditOffIcon} className="size-4" />\n </ToolbarIconButton>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarIconButton\n label="Import DOCX"\n disabled={editor.isImporting}\n onClick={onUploadClick}\n >\n {editor.isImporting ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n )}\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Download DOCX"\n disabled={controlsDisabled || editor.isImporting}\n onClick={editor.exportDocx}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex min-h-12 flex-wrap items-center gap-2 border-b px-3 py-2">\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Undo"\n disabled={!editor.canUndo || isReadOnly}\n onClick={editor.undo}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Redo"\n disabled={!editor.canRedo || isReadOnly}\n onClick={editor.redo}\n >\n <HugeiconsIcon icon={Redo02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <PreviewCardPrimitive.Root handle={paragraphStylePreviewHandle}>\n {({ payload }) => {\n const previewOption = payload ?? selectedParagraphStyleOption\n\n return (\n <>\n <Select\n value={selectedParagraphStyleValue}\n onOpenChange={(open) => {\n setIsParagraphStyleMenuOpen(open)\n\n if (!open) {\n paragraphStylePreviewHandle.close()\n return\n }\n\n window.requestAnimationFrame(() => {\n openParagraphStylePreview(selectedParagraphStyleValue)\n })\n }}\n onValueChange={(value) => {\n if (value) {\n setParagraphStyle(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[136px] min-w-[136px]"\n aria-label="Paragraph style"\n >\n <SelectValue placeholder="Style" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010] min-w-[210px]"\n >\n {paragraphStyleOptions.map((option) => {\n const previewTriggerId = paragraphStylePreviewTriggerId(\n paragraphStylePreviewIdPrefix,\n option.id\n )\n\n return (\n <SelectItem\n key={option.id}\n value={option.id}\n label={option.name}\n className="relative min-w-[190px]"\n onFocus={() => openParagraphStylePreview(option.id)}\n onPointerEnter={() =>\n openParagraphStylePreview(option.id)\n }\n >\n <span className="block truncate">\n {option.name}\n </span>\n <PreviewCardPrimitive.Trigger\n id={previewTriggerId}\n handle={paragraphStylePreviewHandle}\n payload={option}\n delay={0}\n closeDelay={120}\n render={\n <span\n aria-hidden="true"\n className="pointer-events-none absolute inset-0 block"\n />\n }\n />\n </SelectItem>\n )\n })}\n </SelectContent>\n </Select>\n {isParagraphStyleMenuOpen && previewOption ? (\n <PreviewCardPrimitive.Portal>\n <PreviewCardPrimitive.Positioner\n side="right"\n align="start"\n sideOffset={10}\n alignOffset={-4}\n className="z-[100020] transition-[top,left,right,bottom,transform] duration-100 ease-out data-instant:transition-none"\n >\n <PreviewCardPrimitive.Popup\n data-slot="paragraph-style-preview-card"\n className="origin-(--transform-origin) rounded-lg border bg-popover text-popover-foreground shadow-lg/5 transition-opacity duration-100 outline-none not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]"\n >\n <ParagraphStylePreviewCard\n documentTheme={documentTheme}\n option={previewOption}\n />\n </PreviewCardPrimitive.Popup>\n </PreviewCardPrimitive.Positioner>\n </PreviewCardPrimitive.Portal>\n ) : null}\n </>\n )\n }}\n </PreviewCardPrimitive.Root>\n\n <Select\n value={selectedRunStyle?.fontFamily ?? "Calibri"}\n onValueChange={(value) => {\n if (value) {\n editor.setFontFamily(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[156px] min-w-[156px]"\n aria-label="Font family"\n >\n <SelectValue placeholder="Font" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {FONT_FAMILIES.map((fontFamily) => (\n <SelectItem key={fontFamily} value={fontFamily}>\n <span style={{ fontFamily }}>{fontFamily}</span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={String(Math.round(selectedRunStyle?.fontSizePt ?? 12))}\n onValueChange={(value) => {\n const nextSize = Number(value)\n if (Number.isFinite(nextSize)) {\n editor.setFontSize(nextSize)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[86px] min-w-[86px]"\n aria-label="Font size"\n >\n <SelectValue placeholder="Size" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {FONT_SIZE_OPTIONS.map((size) => (\n <SelectItem key={size} value={String(size)}>\n {size} pt\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={selectedLineSpacingValue}\n onValueChange={(value) => {\n const nextSpacing = Number(value)\n if (Number.isFinite(nextSpacing)) {\n setLineSpacing(nextSpacing)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[94px] min-w-[94px]"\n aria-label="Line spacing"\n >\n <SelectValue placeholder="Spacing" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {LINE_SPACING_OPTIONS.map((spacing) => (\n <SelectItem key={spacing} value={String(spacing)}>\n {spacing}x\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bold"\n active={Boolean(selectedRunStyle?.bold)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleBold}\n >\n <HugeiconsIcon icon={TextBoldIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Italic"\n active={Boolean(selectedRunStyle?.italic)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleItalic}\n >\n <HugeiconsIcon icon={TextItalicIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Underline"\n active={Boolean(selectedRunStyle?.underline)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleUnderline}\n >\n <HugeiconsIcon icon={TextUnderlineIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Strikethrough"\n active={Boolean(selectedRunStyle?.strike)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleStrike}\n >\n <HugeiconsIcon icon={TextStrikethroughIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Superscript"\n active={selectedRunStyle?.verticalAlign === "superscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSuperscript}\n >\n <HugeiconsIcon icon={TextSuperscriptIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Subscript"\n active={selectedRunStyle?.verticalAlign === "subscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSubscript}\n >\n <HugeiconsIcon icon={TextSubscriptIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarColorInput\n label="Text color"\n icon={TextColorIcon}\n color={textColorValue}\n disabled={!canEdit}\n onChange={(color) =>\n editor.setTextColor(normalizeHexColor(color))\n }\n />\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!canEdit}\n aria-label="Highlight color"\n className="relative"\n >\n <HugeiconsIcon icon={HighlighterIcon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: highlightColor }}\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-[100010] w-44">\n {HIGHLIGHT_COLORS.map((option) => (\n <DropdownMenuCheckboxItem\n key={option.value}\n checked={selectedRunStyle?.highlight === option.value}\n onCheckedChange={() => editor.setHighlight(option.value)}\n >\n <span\n className="size-3 rounded-full border"\n style={{ backgroundColor: option.color }}\n />\n {option.label}\n </DropdownMenuCheckboxItem>\n ))}\n <DropdownMenuSeparator />\n <DropdownMenuCheckboxItem\n checked={!selectedRunStyle?.highlight}\n onCheckedChange={() => editor.setHighlight(undefined)}\n >\n No highlight\n </DropdownMenuCheckboxItem>\n </DropdownMenuContent>\n </DropdownMenu>\n <ToolbarIconButton\n label="Link"\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={onOpenLinkEditor}\n >\n <HugeiconsIcon icon={Link02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Align left"\n active={\n selectedParagraph?.style?.align === "left" ||\n !selectedParagraph?.style?.align\n }\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("left")}\n >\n <HugeiconsIcon icon={TextAlignLeft01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Align center"\n active={selectedParagraph?.style?.align === "center"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("center")}\n >\n <HugeiconsIcon icon={TextAlignCenterIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Align right"\n active={selectedParagraph?.style?.align === "right"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("right")}\n >\n <HugeiconsIcon icon={TextAlignRight01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Justify"\n active={selectedParagraph?.style?.align === "justify"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("justify")}\n >\n <HugeiconsIcon\n icon={TextAlignJustifyLeftIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bulleted list"\n active={editor.hasUnorderedList}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.toggleList("unordered")}\n >\n <HugeiconsIcon\n icon={LeftToRightListBulletIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Numbered list"\n active={editor.hasOrderedList}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.toggleList("ordered")}\n >\n <HugeiconsIcon\n icon={LeftToRightListNumberIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="sm"\n disabled={!canEdit}\n className="h-7 gap-1 px-2 shadow-none"\n >\n <HugeiconsIcon icon={borderTriggerIcon} className="size-4" />\n {borderTriggerLabel}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-[100010] w-56">\n {BORDER_CONTROL_OPTIONS.map((option) => {\n const enabledForContext =\n !option.contexts || option.contexts.includes(borderContext)\n const BorderOptionIcon = borderControlOptionIcon(option.id)\n\n return (\n <React.Fragment key={option.id}>\n {option.separatorBefore ? <DropdownMenuSeparator /> : null}\n <DropdownMenuCheckboxItem\n checked={activeBorderPresets[option.id]}\n disabled={!enabledForContext}\n onCheckedChange={() => {\n if (enabledForContext) {\n applyBorderPreset(option.id)\n }\n }}\n >\n <HugeiconsIcon\n icon={BorderOptionIcon}\n className="size-4 text-muted-foreground"\n />\n {option.label}\n </DropdownMenuCheckboxItem>\n </React.Fragment>\n )\n })}\n </DropdownMenuContent>\n </DropdownMenu>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Insert image"\n disabled={!canEdit}\n onClick={onImageUploadClick}\n >\n <HugeiconsIcon icon={ImageAdd01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Insert table"\n disabled={!canEdit}\n onClick={editor.insertTable}\n >\n <HugeiconsIcon icon={TableIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarTooltip label="Section columns">\n <div className="flex h-7 shrink-0 items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground">\n <HugeiconsIcon icon={ColumnsThreeCogIcon} className="size-4" />\n {activeColumns ? `${activeColumns.count} cols` : "1 col"}\n </div>\n </ToolbarTooltip>\n </div>\n\n <div className="ml-auto flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Zoom out"\n disabled={controlsDisabled || !canZoomOut}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, -1)\n )\n }\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n <Select\n value={zoomScale.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={controlsDisabled}\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(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="end"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarIconButton\n label="Zoom in"\n disabled={controlsDisabled || !canZoomIn}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function DocxEditorPreview({\n className,\n fileName,\n rounded = false,\n src,\n}: {\n className?: string\n fileName?: string\n rounded?: boolean\n src?: string\n}) {\n const { resolvedTheme } = useTheme()\n const { nightRenderEnabled, nightRenderPrefLoaded, setNightRenderEnabled } =\n useDocumentNightRenderPreference()\n const isViewerHydrated = resolvedTheme !== undefined && nightRenderPrefLoaded\n const shouldShowHydrationSpinner = useDelayedLoadingIndicator(\n !isViewerHydrated,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n\n if (!isViewerHydrated) {\n return (\n <div\n className={cn(\n "flex h-[720px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <div\n className={cn(\n "min-h-0 flex-1 overflow-hidden bg-muted/30 p-4",\n rounded && "rounded-b-lg"\n )}\n >\n <EditorLoadingSurface showSpinner={shouldShowHydrationSpinner} />\n </div>\n </div>\n )\n }\n\n const shouldRenderNightMode = resolvedTheme === "dark"\n const effectiveIsDark = shouldRenderNightMode && nightRenderEnabled\n\n return (\n <DocxEditorContent\n className={className}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setNightRenderEnabled}\n shouldRenderNightMode={shouldRenderNightMode}\n url={src}\n />\n )\n}\n\nfunction DocxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled: _setNightRenderEnabled,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const imageInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const [zoomScale, setZoomScale] = React.useState<number>(\n DOCX_EDITOR_DEFAULT_ZOOM_SCALE\n )\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const [isReadOnly, setIsReadOnly] = React.useState(false)\n const [linkEditorOpen, setLinkEditorOpen] = React.useState(false)\n const [linkDraft, setLinkDraft] = React.useState("")\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const cacheKey = React.useMemo(\n () =>\n uploadedDocxFile?.identity ??\n (url ? getDocumentCacheKey(url, displayFileName) : "docx-empty"),\n [displayFileName, uploadedDocxFile?.identity, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { importDocxFile, setDocumentTheme, status } = editor\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(editor, thumbnailOptions)\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <EditorLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\n ? await loadCachedDocxFile(url, displayFileName, cacheKey)\n : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : "Unknown DOCX load error"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n void load()\n\n return () => {\n isCurrent = false\n }\n }, [cacheKey, displayFileName, importDocxFile, uploadedDocxFile, url])\n\n React.useEffect(() => {\n if (url) {\n setUploadedDocxFile(null)\n }\n }, [url])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n \'[data-docx-page-wrapper="true"][data-index]\'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback((pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport || !page) return\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n }, [])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomScale(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\n setActivePage(1)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n async function handleImageUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n await editor.insertImageFile(file)\n }\n\n function openLinkEditor() {\n setLinkDraft(editor.selectedLink ?? "")\n setLinkEditorOpen(true)\n }\n\n function applyLink() {\n editor.setLink(linkDraft.trim() || undefined)\n setLinkEditorOpen(false)\n }\n\n return (\n <div\n className={cn(\n "flex h-[720px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <input\n ref={imageInputRef}\n type="file"\n accept="image/*"\n className="hidden"\n onChange={handleImageUpload}\n />\n <DocxEditorToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n editor={editor}\n isReadOnly={isReadOnly}\n onImageUploadClick={() => imageInputRef.current?.click()}\n onIsReadOnlyChange={setIsReadOnly}\n onOpenLinkEditor={openLinkEditor}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showNightRenderToggle={shouldRenderNightMode}\n zoomScale={zoomScale}\n />\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {linkEditorOpen ? (\n <div className="absolute top-3 left-1/2 z-50 flex w-[min(420px,calc(100%-2rem))] -translate-x-1/2 items-center gap-2 rounded-lg border bg-background p-2 shadow-lg">\n <Input\n value={linkDraft}\n onChange={(event) => setLinkDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n event.preventDefault()\n applyLink()\n }\n if (event.key === "Escape") {\n setLinkEditorOpen(false)\n }\n }}\n placeholder="https://example.com"\n aria-label="Link URL"\n />\n <Button type="button" size="sm" onClick={applyLink}>\n Apply\n </Button>\n <Button\n type="button"\n size="sm"\n variant="ghost"\n onClick={() => {\n editor.setLink(undefined)\n setLinkEditorOpen(false)\n }}\n >\n Clear\n </Button>\n </div>\n ) : null}\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <ScrollArea className="h-full" scrollFade>\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 rounded-sm border 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 </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs text-muted-foreground shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </ScrollArea>\n </DocumentViewerThumbnailSidebar>\n <div\n ref={viewportRef}\n className={cn(\n "min-h-0 flex-1 overflow-auto p-4",\n rounded && "rounded-b-lg"\n )}\n style={{ backgroundColor: viewerBackgroundColor }}\n >\n {!url && !uploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">Upload a DOCX to edit</div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to edit DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="mx-auto flex min-h-full justify-center">\n <div\n className={cn(\n "origin-top",\n editor.documentTheme === "dark" && "docx-night-reader-shell"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode={isReadOnly ? "read-only" : "edit"}\n showTrackedChanges={editor.showTrackedChanges}\n loadingState={loadingState}\n pageBackgroundColor={\n editor.documentTheme === "dark" ? "#0a0a0a" : undefined\n }\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n'
+ '"use client"\n\nimport * as React from "react"\nimport { PreviewCard as PreviewCardPrimitive } from "@base-ui/react/preview-card"\nimport {\n DocxEditorViewer,\n paragraphLetterheadFloatSideAtNodeIndex,\n useDocxBorders,\n useDocxDocumentTheme,\n useDocxEditor,\n useDocxLineSpacing,\n useDocxPageLayout,\n useDocxParagraphStyles,\n useDocxTrackChanges,\n useDocxViewerThumbnails,\n type DocxBorderContext,\n type DocxBorderPreset,\n type DocxDocumentTheme,\n type DocxEditorController,\n type ParagraphStyleDefinition,\n} from "@extend-ai/react-docx"\nimport {\n ArrowExpandDiagonal01Icon,\n ArrowExpandDiagonal02Icon,\n BorderAll01Icon,\n BorderBottom01Icon,\n BorderHorizontalIcon,\n BorderInnerIcon,\n BorderLeft01Icon,\n BorderNone01Icon,\n BorderRight01Icon,\n BorderTop01Icon,\n BorderVerticalIcon,\n ColumnsThreeCogIcon,\n Download01Icon,\n EditOffIcon,\n FileDiffIcon,\n HighlighterIcon,\n ImageAdd01Icon,\n LeftToRightListBulletIcon,\n LeftToRightListNumberIcon,\n LineIcon,\n Link02Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n Redo02Icon,\n SidebarLeftIcon,\n Sun03Icon,\n TableIcon,\n TextAlignCenterIcon,\n TextAlignJustifyLeftIcon,\n TextAlignLeft01Icon,\n TextAlignRight01Icon,\n TextBoldIcon,\n TextColorIcon,\n TextItalicIcon,\n TextStrikethroughIcon,\n TextSubscriptIcon,\n TextSuperscriptIcon,\n TextUnderlineIcon,\n Undo02Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { useTheme } from "next-themes"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Input } from "@/components/ui/input"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/registry/new-york-v4/ui/dropdown-menu"\nimport { Separator } from "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_SOURCE_CACHE_LIMIT = 3\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_EDITOR_DEFAULT_ZOOM_SCALE = 75\nconst ZOOM_OPTIONS = [50, 75, 90, 100, 110, 125, 150, 175, 200] as const\nconst FONT_FAMILIES = [\n "Calibri",\n "Arial",\n "Times New Roman",\n "Georgia",\n "Helvetica",\n "Courier New",\n] as const\nconst FONT_SIZE_OPTIONS = [\n 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48,\n] as const\nconst LINE_SPACING_OPTIONS = [1, 1.15, 1.2, 1.5, 2, 2.5, 3] as const\nconst FALLBACK_PARAGRAPH_STYLE_OPTIONS = [\n { id: "Normal", name: "Body" },\n { id: "Heading1", name: "Heading 1" },\n { id: "Heading2", name: "Heading 2" },\n { id: "Heading3", name: "Heading 3" },\n] as const\nconst HIGHLIGHT_COLORS = [\n { label: "Yellow", value: "yellow", color: "#fff59d" },\n { label: "Green", value: "green", color: "#bbf7d0" },\n { label: "Cyan", value: "cyan", color: "#a5f3fc" },\n { label: "Magenta", value: "magenta", color: "#f5d0fe" },\n { label: "Red", value: "red", color: "#fecaca" },\n { label: "Blue", value: "blue", color: "#bfdbfe" },\n] as const\nconst HIGHLIGHT_PREVIEW_COLORS: Record<string, string> = {\n black: "#111827",\n white: "#ffffff",\n ...Object.fromEntries(\n HIGHLIGHT_COLORS.map((option) => [option.value, option.color])\n ),\n}\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\nconst DEFAULT_HEADING_PREVIEW_RUN_STYLES: Record<\n 1 | 2 | 3 | 4 | 5 | 6,\n NonNullable<ParagraphStyleDefinition["runStyle"]>\n> = {\n 1: {\n fontFamily: "Calibri Light",\n fontSizePt: 16,\n bold: true,\n color: "#2f5496",\n },\n 2: {\n fontFamily: "Calibri Light",\n fontSizePt: 13,\n bold: true,\n color: "#2f5496",\n },\n 3: {\n fontFamily: "Calibri",\n fontSizePt: 12,\n bold: true,\n color: "#1f3763",\n },\n 4: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 5: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 6: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n}\n\nconst docxFileCache = new Map<string, File>()\nconst docxFilePromiseCache = new Map<string, Promise<File>>()\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n}\n\ntype BorderControlOption = {\n id: DocxBorderPreset\n label: string\n contexts?: DocxBorderContext[]\n separatorBefore?: boolean\n}\n\nconst BORDER_CONTROL_OPTIONS: BorderControlOption[] = [\n { id: "bottom", label: "Bottom Border" },\n { id: "top", label: "Top Border" },\n { id: "left", label: "Left Border" },\n { id: "right", label: "Right Border" },\n { id: "none", label: "No Border", separatorBefore: true },\n { id: "all", label: "All Borders" },\n { id: "outside", label: "Outside Borders" },\n { id: "inside", label: "Inside Borders", contexts: ["table"] },\n {\n id: "inside-horizontal",\n label: "Inside Horizontal Border",\n contexts: ["table"],\n },\n {\n id: "inside-vertical",\n label: "Inside Vertical Border",\n contexts: ["table"],\n },\n {\n id: "diagonal-down",\n label: "Diagonal Down Border",\n contexts: ["table"],\n separatorBefore: true,\n },\n { id: "diagonal-up", label: "Diagonal Up Border", contexts: ["table"] },\n { id: "horizontal-line", label: "Horizontal Line", separatorBefore: true },\n]\n\nfunction borderControlOptionIcon(optionId: DocxBorderPreset) {\n switch (optionId) {\n case "bottom":\n return BorderBottom01Icon\n case "top":\n return BorderTop01Icon\n case "left":\n return BorderLeft01Icon\n case "right":\n return BorderRight01Icon\n case "none":\n return BorderNone01Icon\n case "inside":\n return BorderInnerIcon\n case "inside-horizontal":\n return BorderHorizontalIcon\n case "inside-vertical":\n return BorderVerticalIcon\n case "diagonal-down":\n return ArrowExpandDiagonal01Icon\n case "diagonal-up":\n return ArrowExpandDiagonal02Icon\n case "horizontal-line":\n return LineIcon\n default:\n return BorderAll01Icon\n }\n}\n\nfunction getDocumentCacheKey(url: string, fileName?: string) {\n return `${url.split("?")[0] ?? url}::${fileName ?? ""}`\n}\n\nfunction rememberDocxFile(cacheKey: string, file: File) {\n if (docxFileCache.has(cacheKey)) {\n docxFileCache.delete(cacheKey)\n }\n\n docxFileCache.set(cacheKey, file)\n\n while (docxFileCache.size > DOCX_SOURCE_CACHE_LIMIT) {\n const oldestKey = docxFileCache.keys().next().value\n if (!oldestKey) break\n docxFileCache.delete(oldestKey)\n }\n}\n\nasync function loadCachedDocxFile(\n url: string,\n displayFileName: string,\n cacheKey: string\n): Promise<File> {\n const cachedFile = docxFileCache.get(cacheKey)\n if (cachedFile) return cachedFile\n\n const pendingRequest = docxFilePromiseCache.get(cacheKey)\n if (pendingRequest) return pendingRequest\n\n const nextRequest = fetch(url)\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n const docxFile = new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n\n rememberDocxFile(cacheKey, docxFile)\n return docxFile\n })\n .finally(() => {\n docxFilePromiseCache.delete(cacheKey)\n })\n\n docxFilePromiseCache.set(cacheKey, nextRequest)\n return nextRequest\n}\n\nfunction formatDocumentName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "document.docx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {\n const currentIndex = ZOOM_OPTIONS.indexOf(\n currentZoomScale as (typeof ZOOM_OPTIONS)[number]\n )\n let fallbackIndex = -1\n\n if (direction > 0) {\n fallbackIndex = ZOOM_OPTIONS.findIndex((value) => value > currentZoomScale)\n } else {\n for (let index = ZOOM_OPTIONS.length - 1; index >= 0; index -= 1) {\n if (ZOOM_OPTIONS[index] < currentZoomScale) {\n fallbackIndex = index\n break\n }\n }\n }\n\n const resolvedIndex = currentIndex >= 0 ? currentIndex : fallbackIndex\n if (resolvedIndex < 0) return currentZoomScale\n\n const nextIndex = Math.min(\n Math.max(resolvedIndex + direction, 0),\n ZOOM_OPTIONS.length - 1\n )\n\n return ZOOM_OPTIONS[nextIndex] ?? currentZoomScale\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\n}\n\nfunction useDocumentNightRenderPreference() {\n const [nightRenderEnabled, setNightRenderEnabled] = React.useState(false)\n const [nightRenderPrefLoaded, setNightRenderPrefLoaded] =\n React.useState(false)\n\n React.useEffect(() => {\n const storedValue = window.localStorage.getItem("docx-editor-night-render")\n setNightRenderEnabled(storedValue === "true")\n setNightRenderPrefLoaded(true)\n }, [])\n\n const updateNightRenderEnabled = React.useCallback((checked: boolean) => {\n setNightRenderEnabled(checked)\n window.localStorage.setItem("docx-editor-night-render", String(checked))\n }, [])\n\n return {\n nightRenderEnabled,\n nightRenderPrefLoaded,\n setNightRenderEnabled: updateNightRenderEnabled,\n }\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction normalizeHexColor(value?: string, fallback = "#111827") {\n if (!value) return fallback\n\n const trimmed = value.trim()\n const threeDigit = /^#([0-9a-f]{3})$/i.exec(trimmed)\n if (threeDigit?.[1]) {\n const [red, green, blue] = threeDigit[1].split("")\n return `#${red}${red}${green}${green}${blue}${blue}`.toLowerCase()\n }\n\n const sixDigit = /^#([0-9a-f]{6})$/i.exec(trimmed)\n if (sixDigit?.[1]) {\n return `#${sixDigit[1].toLowerCase()}`\n }\n\n return fallback\n}\n\nfunction inferParagraphStyleHeadingLevel(value?: string) {\n if (!value) return undefined\n\n const match = value.match(/(?:^|[\\s_-])(?:heading|h)\\s*([1-6])(?:$|[\\s_-])/i)\n const level = match?.[1] ? Number(match[1]) : NaN\n\n return level >= 1 && level <= 6 ? (level as 1 | 2 | 3 | 4 | 5 | 6) : undefined\n}\n\nfunction resolveParagraphStyleHeadingLevel(option?: ParagraphStyleDefinition) {\n if (\n Number.isFinite(option?.headingLevel) &&\n option?.headingLevel &&\n option.headingLevel >= 1 &&\n option.headingLevel <= 6\n ) {\n return option.headingLevel as 1 | 2 | 3 | 4 | 5 | 6\n }\n\n return (\n inferParagraphStyleHeadingLevel(option?.id) ??\n inferParagraphStyleHeadingLevel(option?.name)\n )\n}\n\nfunction resolveParagraphStyleRunPreview(option?: ParagraphStyleDefinition) {\n if (!option) return undefined\n\n const headingLevel = resolveParagraphStyleHeadingLevel(option)\n const headingRunStyle = headingLevel\n ? DEFAULT_HEADING_PREVIEW_RUN_STYLES[headingLevel]\n : undefined\n\n return headingRunStyle\n ? {\n ...headingRunStyle,\n ...(option.runStyle ?? {}),\n }\n : option.runStyle\n}\n\nfunction resolveHighlightPreview(value?: string) {\n if (!value) return undefined\n\n const normalized = value.trim().toLowerCase()\n if (!normalized) return undefined\n\n const hex = normalizeHexColor(normalized, "")\n if (hex) return hex\n\n return HIGHLIGHT_PREVIEW_COLORS[normalized]\n}\n\nfunction themedPreviewColor(\n color: string | undefined,\n documentTheme: DocxDocumentTheme\n) {\n if (documentTheme !== "dark") return color\n if (!color) return "#f3f4f6"\n\n const normalized = color.trim().toLowerCase()\n if (\n normalized === "#000" ||\n normalized === "#000000" ||\n normalized === "#111111" ||\n normalized === "#111827" ||\n normalized === "black" ||\n normalized === "rgb(0,0,0)" ||\n normalized === "rgb(0, 0, 0)"\n ) {\n return "#f3f4f6"\n }\n\n return color\n}\n\nfunction paragraphStylePreviewStyle(\n option: ParagraphStyleDefinition,\n documentTheme: DocxDocumentTheme\n): React.CSSProperties {\n const runStyle = resolveParagraphStyleRunPreview(option)\n const textDecoration = [\n runStyle?.underline ? "underline" : "",\n runStyle?.strike ? "line-through" : "",\n ]\n .filter(Boolean)\n .join(" ")\n\n return {\n textAlign: option.align ?? "left",\n fontFamily: runStyle?.fontFamily,\n fontSize: runStyle?.fontSizePt ? `${runStyle.fontSizePt}pt` : "11pt",\n fontWeight:\n runStyle?.bold !== undefined ? (runStyle.bold ? 700 : 400) : undefined,\n fontStyle: runStyle?.italic ? "italic" : undefined,\n textDecoration: textDecoration || undefined,\n color:\n runStyle?.color !== undefined\n ? themedPreviewColor(normalizeHexColor(runStyle.color), documentTheme)\n : undefined,\n backgroundColor: resolveHighlightPreview(runStyle?.highlight),\n lineHeight: 1,\n whiteSpace: "pre-wrap",\n }\n}\n\nfunction paragraphStylePreviewTriggerId(prefix: string, styleId: string) {\n return `${prefix}-paragraph-style-preview-${styleId.replace(\n /[^a-zA-Z0-9_-]/g,\n "_"\n )}`\n}\n\nfunction parseToolbarSectionColumns(\n sectionPropertiesXml?: string\n): { count: number; gapPx: number } | undefined {\n if (!sectionPropertiesXml) return undefined\n\n const columnsTag = sectionPropertiesXml.match(/<w:cols\\b[^>]*\\/?>/i)?.[0]\n if (!columnsTag) return undefined\n\n const countRaw = columnsTag.match(/\\bw:num="(\\d+)"/i)?.[1]\n const count = countRaw ? Number(countRaw) : 1\n if (!Number.isFinite(count) || count <= 1) return undefined\n\n const gapRaw = columnsTag.match(/\\bw:space="(\\d+)"/i)?.[1]\n const gapTwips = gapRaw ? Number(gapRaw) : 720\n const gapPx = Math.max(0, Math.round((gapTwips * 96) / 1440))\n\n return {\n count: Math.max(2, Math.round(count)),\n gapPx,\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 EditorLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction ToolbarIconButton({\n active,\n children,\n label,\n ...props\n}: React.ComponentProps<typeof Button> & {\n active?: boolean\n label: string\n}) {\n return (\n <ToolbarTooltip label={label}>\n <Button\n type="button"\n variant={active ? "secondary" : "ghost"}\n size="icon-sm"\n aria-label={label}\n data-pressed={active ? "" : undefined}\n {...props}\n >\n {children}\n </Button>\n </ToolbarTooltip>\n )\n}\n\nfunction ToolbarColorInput({\n color,\n disabled,\n icon,\n label,\n onChange,\n}: {\n color: string\n disabled?: boolean\n icon: typeof TextColorIcon\n label: string\n onChange: (color: string) => void\n}) {\n return (\n <ToolbarTooltip label={label}>\n <label\n className={cn(\n "relative inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-lg border border-transparent text-foreground transition-colors hover:bg-accent",\n disabled && "pointer-events-none opacity-64"\n )}\n aria-label={label}\n >\n <HugeiconsIcon icon={icon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: color }}\n />\n <input\n type="color"\n aria-label={label}\n disabled={disabled}\n value={color}\n className="sr-only"\n onChange={(event) => onChange(event.target.value)}\n />\n </label>\n </ToolbarTooltip>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n showMetadata={false}\n className={cn(\n "w-full rounded-sm border shadow-xs transition-[border-color,box-shadow] duration-150",\n isActive && "border-primary shadow-sm"\n )}\n />\n )\n}\n\nfunction ParagraphStylePreviewCard({\n documentTheme,\n option,\n}: {\n documentTheme: DocxDocumentTheme\n option: ParagraphStyleDefinition\n}) {\n const surfaceStyle: React.CSSProperties =\n documentTheme === "dark"\n ? {\n backgroundColor: "#111827",\n borderColor: "#374151",\n color: "#f3f4f6",\n }\n : {\n backgroundColor: "#ffffff",\n borderColor: "#d4d4d8",\n color: "#111827",\n }\n const secondaryTextColor = documentTheme === "dark" ? "#9ca3af" : "#6b7280"\n\n return (\n <div className="w-[260px] p-3">\n <p className="text-[10px] font-medium tracking-wide text-muted-foreground uppercase">\n Style Preview\n </p>\n <div className="mt-2 rounded-sm border p-2.5" style={surfaceStyle}>\n <p style={paragraphStylePreviewStyle(option, documentTheme)}>\n {option.name}\n </p>\n <p\n className="mt-1 text-[11px]"\n style={{\n color: secondaryTextColor,\n textAlign: option.align ?? "left",\n }}\n >\n The quick brown fox jumps over the lazy dog.\n </p>\n </div>\n </div>\n )\n}\n\nfunction DocxEditorToolbar({\n activePage,\n controlsDisabled,\n editor,\n isReadOnly,\n onImageUploadClick,\n onIsReadOnlyChange,\n onOpenLinkEditor,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n editor: DocxEditorController\n isReadOnly: boolean\n onImageUploadClick: () => void\n onIsReadOnlyChange: (checked: boolean) => void\n onOpenLinkEditor: () => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showNightRenderToggle: boolean\n zoomScale: number\n}) {\n const { documentTheme, setDocumentTheme } = useDocxDocumentTheme(editor)\n const { layout: pageLayout } = useDocxPageLayout(editor)\n const { paragraphStyles, selectedParagraphStyleId, setParagraphStyle } =\n useDocxParagraphStyles(editor)\n const { lineSpacing, setLineSpacing } = useDocxLineSpacing(editor)\n const { borderContext, activeBorderPresets, applyBorderPreset } =\n useDocxBorders(editor)\n const { showTrackedChanges, setShowTrackedChanges } =\n useDocxTrackChanges(editor)\n const selectedRunStyle = editor.selectedRunStyle\n const selectedParagraph = editor.selectedParagraph\n const paragraphStyleOptions: ParagraphStyleDefinition[] =\n paragraphStyles.length > 0\n ? paragraphStyles\n : [...FALLBACK_PARAGRAPH_STYLE_OPTIONS]\n const selectedParagraphStyleValue =\n selectedParagraphStyleId ??\n paragraphStyleOptions.find((option) => "isDefault" in option)?.id ??\n paragraphStyleOptions[0]?.id ??\n "Normal"\n const selectedParagraphStyleOption =\n paragraphStyleOptions.find(\n (option) => option.id === selectedParagraphStyleValue\n ) ??\n paragraphStyleOptions[0] ??\n FALLBACK_PARAGRAPH_STYLE_OPTIONS[0]\n const paragraphStylePreviewHandle = React.useMemo(\n () => PreviewCardPrimitive.createHandle<ParagraphStyleDefinition>(),\n []\n )\n const paragraphStylePreviewIdPrefix = React.useId()\n const [isParagraphStyleMenuOpen, setIsParagraphStyleMenuOpen] =\n React.useState(false)\n const openParagraphStylePreview = React.useCallback(\n (styleId: string) => {\n paragraphStylePreviewHandle.open(\n paragraphStylePreviewTriggerId(paragraphStylePreviewIdPrefix, styleId)\n )\n },\n [paragraphStylePreviewHandle, paragraphStylePreviewIdPrefix]\n )\n const selectedLineSpacingValue = React.useMemo(() => {\n const current = Number.isFinite(lineSpacing.multiple)\n ? lineSpacing.multiple\n : 1\n const nearest = LINE_SPACING_OPTIONS.reduce((closest, candidate) => {\n return Math.abs(candidate - current) < Math.abs(closest - current)\n ? candidate\n : closest\n }, LINE_SPACING_OPTIONS[0])\n return String(nearest)\n }, [lineSpacing.multiple])\n const textColorValue = normalizeHexColor(selectedRunStyle?.color)\n const highlightColor =\n HIGHLIGHT_COLORS.find(\n (option) => option.value === selectedRunStyle?.highlight\n )?.color ?? "#fff59d"\n const activeNodeIndex =\n editor.selection.kind === "paragraph"\n ? editor.selection.nodeIndex\n : editor.selection.tableIndex\n const letterheadColumns =\n editor.selection.kind === "paragraph" &&\n paragraphLetterheadFloatSideAtNodeIndex(\n editor.model.nodes,\n editor.selection.nodeIndex\n )\n ? { count: 2, gapPx: 28 }\n : undefined\n const sections = editor.model.metadata.sections ?? []\n const activeSection = sections\n .filter((section) => section.startNodeIndex <= activeNodeIndex)\n .at(-1)\n const activeColumns =\n letterheadColumns ??\n parseToolbarSectionColumns(activeSection?.sectionPropertiesXml) ??\n parseToolbarSectionColumns(editor.model.metadata.sectionPropertiesXml) ??\n pageLayout.columns\n const activeBorderControlOptions = BORDER_CONTROL_OPTIONS.filter(\n (option) => activeBorderPresets[option.id]\n )\n const borderTriggerLabel =\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].label\n : "Borders"\n const borderTriggerIcon = borderControlOptionIcon(\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].id\n : "all"\n )\n const canEdit = !controlsDisabled && !isReadOnly\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n\n const preserveTextSelection = React.useCallback(\n (event: React.MouseEvent<HTMLElement> | React.PointerEvent<HTMLElement>) =>\n event.preventDefault(),\n []\n )\n\n return (\n <div className="border-b bg-background">\n <TooltipProvider>\n <div className="flex min-h-11 items-center gap-2 overflow-x-auto overflow-y-hidden border-b px-3">\n <ToolbarIconButton\n label="Toggle pages"\n disabled={controlsDisabled}\n onClick={onToggleSidebar}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </ToolbarIconButton>\n <div className="min-w-28 text-sm whitespace-nowrap text-primary">\n Page {pageCount ? activePage : 1} of {pageCount || "-"}\n </div>\n <div className="min-w-0 flex-1" />\n {showNightRenderToggle ? (\n <>\n <ToolbarIconButton\n label={\n documentTheme === "dark"\n ? "Use light document"\n : "Use dark document"\n }\n disabled={controlsDisabled}\n onClick={() =>\n setDocumentTheme(documentTheme === "dark" ? "light" : "dark")\n }\n >\n <HugeiconsIcon\n icon={documentTheme === "dark" ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </ToolbarIconButton>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <ToolbarIconButton\n label="Show tracked changes"\n active={showTrackedChanges}\n disabled={controlsDisabled}\n onClick={() => setShowTrackedChanges(!showTrackedChanges)}\n >\n <HugeiconsIcon icon={FileDiffIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label={isReadOnly ? "Switch to edit mode" : "Switch to read-only"}\n active={isReadOnly}\n disabled={controlsDisabled}\n onClick={() => onIsReadOnlyChange(!isReadOnly)}\n >\n <HugeiconsIcon icon={EditOffIcon} className="size-4" />\n </ToolbarIconButton>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarIconButton\n label="Import DOCX"\n disabled={editor.isImporting}\n onClick={onUploadClick}\n >\n {editor.isImporting ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n )}\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Download DOCX"\n disabled={controlsDisabled || editor.isImporting}\n onClick={editor.exportDocx}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex min-h-12 flex-wrap items-center gap-2 border-b px-3 py-2">\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Undo"\n disabled={!editor.canUndo || isReadOnly}\n onClick={editor.undo}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Redo"\n disabled={!editor.canRedo || isReadOnly}\n onClick={editor.redo}\n >\n <HugeiconsIcon icon={Redo02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <PreviewCardPrimitive.Root handle={paragraphStylePreviewHandle}>\n {({ payload }) => {\n const previewOption = payload ?? selectedParagraphStyleOption\n\n return (\n <>\n <Select\n value={selectedParagraphStyleValue}\n onOpenChange={(open) => {\n setIsParagraphStyleMenuOpen(open)\n\n if (!open) {\n paragraphStylePreviewHandle.close()\n return\n }\n\n window.requestAnimationFrame(() => {\n openParagraphStylePreview(selectedParagraphStyleValue)\n })\n }}\n onValueChange={(value) => {\n if (value) {\n setParagraphStyle(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[136px] min-w-[136px]"\n aria-label="Paragraph style"\n >\n <SelectValue placeholder="Style" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010] min-w-[210px]"\n >\n {paragraphStyleOptions.map((option) => {\n const previewTriggerId = paragraphStylePreviewTriggerId(\n paragraphStylePreviewIdPrefix,\n option.id\n )\n\n return (\n <SelectItem\n key={option.id}\n value={option.id}\n label={option.name}\n className="relative min-w-[190px]"\n onFocus={() => openParagraphStylePreview(option.id)}\n onPointerEnter={() =>\n openParagraphStylePreview(option.id)\n }\n >\n <span className="block truncate">\n {option.name}\n </span>\n <PreviewCardPrimitive.Trigger\n id={previewTriggerId}\n handle={paragraphStylePreviewHandle}\n payload={option}\n delay={0}\n closeDelay={120}\n render={\n <span\n aria-hidden="true"\n className="pointer-events-none absolute inset-0 block"\n />\n }\n />\n </SelectItem>\n )\n })}\n </SelectContent>\n </Select>\n {isParagraphStyleMenuOpen && previewOption ? (\n <PreviewCardPrimitive.Portal>\n <PreviewCardPrimitive.Positioner\n side="right"\n align="start"\n sideOffset={10}\n alignOffset={-4}\n className="z-[100020] transition-[top,left,right,bottom,transform] duration-100 ease-out data-instant:transition-none"\n >\n <PreviewCardPrimitive.Popup\n data-slot="paragraph-style-preview-card"\n className="origin-(--transform-origin) rounded-lg border bg-popover text-popover-foreground shadow-lg/5 transition-opacity duration-100 outline-none not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]"\n >\n <ParagraphStylePreviewCard\n documentTheme={documentTheme}\n option={previewOption}\n />\n </PreviewCardPrimitive.Popup>\n </PreviewCardPrimitive.Positioner>\n </PreviewCardPrimitive.Portal>\n ) : null}\n </>\n )\n }}\n </PreviewCardPrimitive.Root>\n\n <Select\n value={selectedRunStyle?.fontFamily ?? "Calibri"}\n onValueChange={(value) => {\n if (value) {\n editor.setFontFamily(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[156px] min-w-[156px]"\n aria-label="Font family"\n >\n <SelectValue placeholder="Font" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {FONT_FAMILIES.map((fontFamily) => (\n <SelectItem key={fontFamily} value={fontFamily}>\n <span style={{ fontFamily }}>{fontFamily}</span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={String(Math.round(selectedRunStyle?.fontSizePt ?? 12))}\n onValueChange={(value) => {\n const nextSize = Number(value)\n if (Number.isFinite(nextSize)) {\n editor.setFontSize(nextSize)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[86px] min-w-[86px]"\n aria-label="Font size"\n >\n <SelectValue placeholder="Size" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {FONT_SIZE_OPTIONS.map((size) => (\n <SelectItem key={size} value={String(size)}>\n {size} pt\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={selectedLineSpacingValue}\n onValueChange={(value) => {\n const nextSpacing = Number(value)\n if (Number.isFinite(nextSpacing)) {\n setLineSpacing(nextSpacing)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[94px] min-w-[94px]"\n aria-label="Line spacing"\n >\n <SelectValue placeholder="Spacing" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {LINE_SPACING_OPTIONS.map((spacing) => (\n <SelectItem key={spacing} value={String(spacing)}>\n {spacing}x\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bold"\n active={Boolean(selectedRunStyle?.bold)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleBold}\n >\n <HugeiconsIcon icon={TextBoldIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Italic"\n active={Boolean(selectedRunStyle?.italic)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleItalic}\n >\n <HugeiconsIcon icon={TextItalicIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Underline"\n active={Boolean(selectedRunStyle?.underline)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleUnderline}\n >\n <HugeiconsIcon icon={TextUnderlineIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Strikethrough"\n active={Boolean(selectedRunStyle?.strike)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleStrike}\n >\n <HugeiconsIcon icon={TextStrikethroughIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Superscript"\n active={selectedRunStyle?.verticalAlign === "superscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSuperscript}\n >\n <HugeiconsIcon icon={TextSuperscriptIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Subscript"\n active={selectedRunStyle?.verticalAlign === "subscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSubscript}\n >\n <HugeiconsIcon icon={TextSubscriptIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarColorInput\n label="Text color"\n icon={TextColorIcon}\n color={textColorValue}\n disabled={!canEdit}\n onChange={(color) =>\n editor.setTextColor(normalizeHexColor(color))\n }\n />\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!canEdit}\n aria-label="Highlight color"\n className="relative"\n >\n <HugeiconsIcon icon={HighlighterIcon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: highlightColor }}\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-[100010] w-44">\n {HIGHLIGHT_COLORS.map((option) => (\n <DropdownMenuCheckboxItem\n key={option.value}\n checked={selectedRunStyle?.highlight === option.value}\n onCheckedChange={() => editor.setHighlight(option.value)}\n >\n <span\n className="size-3 rounded-full border"\n style={{ backgroundColor: option.color }}\n />\n {option.label}\n </DropdownMenuCheckboxItem>\n ))}\n <DropdownMenuSeparator />\n <DropdownMenuCheckboxItem\n checked={!selectedRunStyle?.highlight}\n onCheckedChange={() => editor.setHighlight(undefined)}\n >\n No highlight\n </DropdownMenuCheckboxItem>\n </DropdownMenuContent>\n </DropdownMenu>\n <ToolbarIconButton\n label="Link"\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={onOpenLinkEditor}\n >\n <HugeiconsIcon icon={Link02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Align left"\n active={\n selectedParagraph?.style?.align === "left" ||\n !selectedParagraph?.style?.align\n }\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("left")}\n >\n <HugeiconsIcon icon={TextAlignLeft01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Align center"\n active={selectedParagraph?.style?.align === "center"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("center")}\n >\n <HugeiconsIcon icon={TextAlignCenterIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Align right"\n active={selectedParagraph?.style?.align === "right"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("right")}\n >\n <HugeiconsIcon icon={TextAlignRight01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Justify"\n active={selectedParagraph?.style?.align === "justify"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("justify")}\n >\n <HugeiconsIcon\n icon={TextAlignJustifyLeftIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bulleted list"\n active={editor.hasUnorderedList}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.toggleList("unordered")}\n >\n <HugeiconsIcon\n icon={LeftToRightListBulletIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Numbered list"\n active={editor.hasOrderedList}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.toggleList("ordered")}\n >\n <HugeiconsIcon\n icon={LeftToRightListNumberIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="sm"\n disabled={!canEdit}\n className="h-7 gap-1 px-2 shadow-none"\n >\n <HugeiconsIcon icon={borderTriggerIcon} className="size-4" />\n {borderTriggerLabel}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-[100010] w-56">\n {BORDER_CONTROL_OPTIONS.map((option) => {\n const enabledForContext =\n !option.contexts || option.contexts.includes(borderContext)\n const BorderOptionIcon = borderControlOptionIcon(option.id)\n\n return (\n <React.Fragment key={option.id}>\n {option.separatorBefore ? <DropdownMenuSeparator /> : null}\n <DropdownMenuCheckboxItem\n checked={activeBorderPresets[option.id]}\n disabled={!enabledForContext}\n onCheckedChange={() => {\n if (enabledForContext) {\n applyBorderPreset(option.id)\n }\n }}\n >\n <HugeiconsIcon\n icon={BorderOptionIcon}\n className="size-4 text-muted-foreground"\n />\n {option.label}\n </DropdownMenuCheckboxItem>\n </React.Fragment>\n )\n })}\n </DropdownMenuContent>\n </DropdownMenu>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Insert image"\n disabled={!canEdit}\n onClick={onImageUploadClick}\n >\n <HugeiconsIcon icon={ImageAdd01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Insert table"\n disabled={!canEdit}\n onClick={editor.insertTable}\n >\n <HugeiconsIcon icon={TableIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarTooltip label="Section columns">\n <div className="flex h-7 shrink-0 items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground">\n <HugeiconsIcon icon={ColumnsThreeCogIcon} className="size-4" />\n {activeColumns ? `${activeColumns.count} cols` : "1 col"}\n </div>\n </ToolbarTooltip>\n </div>\n\n <div className="ml-auto flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Zoom out"\n disabled={controlsDisabled || !canZoomOut}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, -1)\n )\n }\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n <Select\n value={zoomScale.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={controlsDisabled}\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(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="end"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarIconButton\n label="Zoom in"\n disabled={controlsDisabled || !canZoomIn}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function DocxEditorPreview({\n className,\n fileName,\n rounded = false,\n src,\n}: {\n className?: string\n fileName?: string\n rounded?: boolean\n src?: string\n}) {\n const { resolvedTheme } = useTheme()\n const { nightRenderEnabled, nightRenderPrefLoaded, setNightRenderEnabled } =\n useDocumentNightRenderPreference()\n const isViewerHydrated = resolvedTheme !== undefined && nightRenderPrefLoaded\n const shouldShowHydrationSpinner = useDelayedLoadingIndicator(\n !isViewerHydrated,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n\n if (!isViewerHydrated) {\n return (\n <div\n className={cn(\n "flex h-[720px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <div\n className={cn(\n "min-h-0 flex-1 overflow-hidden bg-muted/30 p-4",\n rounded && "rounded-b-lg"\n )}\n >\n <EditorLoadingSurface showSpinner={shouldShowHydrationSpinner} />\n </div>\n </div>\n )\n }\n\n const shouldRenderNightMode = resolvedTheme === "dark"\n const effectiveIsDark = shouldRenderNightMode && nightRenderEnabled\n\n return (\n <DocxEditorContent\n className={className}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setNightRenderEnabled}\n shouldRenderNightMode={shouldRenderNightMode}\n url={src}\n />\n )\n}\n\nfunction DocxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled: _setNightRenderEnabled,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const imageInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const [zoomScale, setZoomScale] = React.useState<number>(\n DOCX_EDITOR_DEFAULT_ZOOM_SCALE\n )\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const [isReadOnly, setIsReadOnly] = React.useState(false)\n const [linkEditorOpen, setLinkEditorOpen] = React.useState(false)\n const [linkDraft, setLinkDraft] = React.useState("")\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const cacheKey = React.useMemo(\n () =>\n uploadedDocxFile?.identity ??\n (url ? getDocumentCacheKey(url, displayFileName) : "docx-empty"),\n [displayFileName, uploadedDocxFile?.identity, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { importDocxFile, setDocumentTheme, status } = editor\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(editor, thumbnailOptions)\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <EditorLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\n ? await loadCachedDocxFile(url, displayFileName, cacheKey)\n : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : "Unknown DOCX load error"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n void load()\n\n return () => {\n isCurrent = false\n }\n }, [cacheKey, displayFileName, importDocxFile, uploadedDocxFile, url])\n\n React.useEffect(() => {\n if (url) {\n setUploadedDocxFile(null)\n }\n }, [url])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n \'[data-docx-page-wrapper="true"][data-index]\'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback((pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport || !page) return\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n }, [])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomScale(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\n setActivePage(1)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n async function handleImageUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n await editor.insertImageFile(file)\n }\n\n function openLinkEditor() {\n setLinkDraft(editor.selectedLink ?? "")\n setLinkEditorOpen(true)\n }\n\n function applyLink() {\n editor.setLink(linkDraft.trim() || undefined)\n setLinkEditorOpen(false)\n }\n\n return (\n <div\n className={cn(\n "flex h-[720px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <input\n ref={imageInputRef}\n type="file"\n accept="image/*"\n className="hidden"\n onChange={handleImageUpload}\n />\n <DocxEditorToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n editor={editor}\n isReadOnly={isReadOnly}\n onImageUploadClick={() => imageInputRef.current?.click()}\n onIsReadOnlyChange={setIsReadOnly}\n onOpenLinkEditor={openLinkEditor}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showNightRenderToggle={shouldRenderNightMode}\n zoomScale={zoomScale}\n />\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {linkEditorOpen ? (\n <div className="absolute top-3 left-1/2 z-50 flex w-[min(420px,calc(100%-2rem))] -translate-x-1/2 items-center gap-2 rounded-lg border bg-background p-2 shadow-lg">\n <Input\n value={linkDraft}\n onChange={(event) => setLinkDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n event.preventDefault()\n applyLink()\n }\n if (event.key === "Escape") {\n setLinkEditorOpen(false)\n }\n }}\n placeholder="https://example.com"\n aria-label="Link URL"\n />\n <Button type="button" size="sm" onClick={applyLink}>\n Apply\n </Button>\n <Button\n type="button"\n size="sm"\n variant="ghost"\n onClick={() => {\n editor.setLink(undefined)\n setLinkEditorOpen(false)\n }}\n >\n Clear\n </Button>\n </div>\n ) : null}\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <div className="h-full overflow-auto">\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 rounded-sm border 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 </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs text-muted-foreground shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </div>\n </DocumentViewerThumbnailSidebar>\n <div\n ref={viewportRef}\n className={cn(\n "min-h-0 flex-1 overflow-auto p-4",\n rounded && "rounded-b-lg"\n )}\n style={{ backgroundColor: viewerBackgroundColor }}\n >\n {!url && !uploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">Upload a DOCX to edit</div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to edit DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="mx-auto flex min-h-full justify-center">\n <div\n className={cn(\n "origin-top",\n editor.documentTheme === "dark" && "docx-night-reader-shell"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode={isReadOnly ? "read-only" : "edit"}\n showTrackedChanges={editor.showTrackedChanges}\n loadingState={loadingState}\n pageBackgroundColor={\n editor.documentTheme === "dark" ? "#0a0a0a" : undefined\n }\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n'
export function DocxEditorSource() {
return <HighlightedCodeBlock code={docxEditorSourceCode} />
diff --git a/apps/v4/components/docx-viewer-docs.tsx b/apps/v4/components/docx-viewer-docs.tsx
index ecda382..df8dd0c 100644
--- a/apps/v4/components/docx-viewer-docs.tsx
+++ b/apps/v4/components/docx-viewer-docs.tsx
@@ -94,7 +94,7 @@ export function DocxViewerExample() {
}`
const docxViewerSourceCode =
- '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n useDocxEditor,\n useDocxViewerThumbnails,\n type DocxDocumentTheme,\n} from "@extend-ai/react-docx"\nimport {\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n SidebarLeftIcon,\n Sun03Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { useTheme } from "next-themes"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { ScrollArea } from "@/components/ui/scroll-area"\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 "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_SOURCE_CACHE_LIMIT = 3\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst ZOOM_OPTIONS = [10, 25, 50, 75, 100, 125, 150, 175, 200, 400] as const\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\n\nconst docxFileCache = new Map<string, File>()\nconst docxFilePromiseCache = new Map<string, Promise<File>>()\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n}\n\nfunction getDocumentCacheKey(url: string, fileName?: string) {\n return `${url.split("?")[0] ?? url}::${fileName ?? ""}`\n}\n\nfunction rememberDocxFile(cacheKey: string, file: File) {\n if (docxFileCache.has(cacheKey)) {\n docxFileCache.delete(cacheKey)\n }\n\n docxFileCache.set(cacheKey, file)\n\n while (docxFileCache.size > DOCX_SOURCE_CACHE_LIMIT) {\n const oldestKey = docxFileCache.keys().next().value\n if (!oldestKey) break\n docxFileCache.delete(oldestKey)\n }\n}\n\nasync function loadCachedDocxFile(\n url: string,\n displayFileName: string,\n cacheKey: string\n): Promise<File> {\n const cachedFile = docxFileCache.get(cacheKey)\n if (cachedFile) return cachedFile\n\n const pendingRequest = docxFilePromiseCache.get(cacheKey)\n if (pendingRequest) return pendingRequest\n\n const nextRequest = fetch(url)\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n const docxFile = new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n\n rememberDocxFile(cacheKey, docxFile)\n return docxFile\n })\n .finally(() => {\n docxFilePromiseCache.delete(cacheKey)\n })\n\n docxFilePromiseCache.set(cacheKey, nextRequest)\n return nextRequest\n}\n\nfunction formatDocumentName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "document.docx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {\n const currentIndex = ZOOM_OPTIONS.indexOf(\n currentZoomScale as (typeof ZOOM_OPTIONS)[number]\n )\n let fallbackIndex = -1\n\n if (direction > 0) {\n fallbackIndex = ZOOM_OPTIONS.findIndex((value) => value > currentZoomScale)\n } else {\n for (let index = ZOOM_OPTIONS.length - 1; index >= 0; index -= 1) {\n if (ZOOM_OPTIONS[index] < currentZoomScale) {\n fallbackIndex = index\n break\n }\n }\n }\n\n const resolvedIndex = currentIndex >= 0 ? currentIndex : fallbackIndex\n if (resolvedIndex < 0) return currentZoomScale\n\n const nextIndex = Math.min(\n Math.max(resolvedIndex + direction, 0),\n ZOOM_OPTIONS.length - 1\n )\n\n return ZOOM_OPTIONS[nextIndex] ?? currentZoomScale\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\n}\n\nfunction useDocumentNightRenderPreference() {\n const [nightRenderEnabled, setNightRenderEnabled] = React.useState(false)\n const [nightRenderPrefLoaded, setNightRenderPrefLoaded] =\n React.useState(false)\n\n React.useEffect(() => {\n const storedValue = window.localStorage.getItem("docx-night-render")\n setNightRenderEnabled(storedValue === "true")\n setNightRenderPrefLoaded(true)\n }, [])\n\n const updateNightRenderEnabled = React.useCallback((checked: boolean) => {\n setNightRenderEnabled(checked)\n window.localStorage.setItem("docx-night-render", String(checked))\n }, [])\n\n return {\n nightRenderEnabled,\n nightRenderPrefLoaded,\n setNightRenderEnabled: updateNightRenderEnabled,\n }\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\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 ViewerLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction DocxToolbar({\n activePage,\n controlsDisabled,\n isDark,\n onIsDarkChange,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showNightRenderToggle: boolean\n zoomScale: number\n}) {\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n\n return (\n <div className="flex min-h-12 items-center justify-between gap-3 overflow-x-auto overflow-y-hidden border-b bg-background px-3">\n <TooltipProvider>\n <div className="flex items-center gap-2">\n <ToolbarTooltip label="Toggle thumbnails">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Toggle thumbnails"\n disabled={controlsDisabled}\n onClick={onToggleSidebar}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <div className="text-sm whitespace-nowrap text-primary">\n Page {pageCount ? activePage : 1} of {pageCount || "-"}\n </div>\n </div>\n <div className="ml-auto flex shrink-0 items-center gap-1">\n {showNightRenderToggle ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <ToolbarTooltip\n label={isDark ? "Use light document" : "Use dark document"}\n >\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled}\n aria-label={\n isDark ? "Use light document" : "Use dark document"\n }\n onClick={() => onIsDarkChange(!isDark)}\n >\n <HugeiconsIcon\n icon={isDark ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled || !canZoomOut}\n aria-label="Zoom out"\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, -1)\n )\n }\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={zoomScale.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={controlsDisabled}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align="end">\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled || !canZoomIn}\n aria-label="Zoom in"\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarTooltip label="Upload DOCX">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Upload DOCX"\n onClick={onUploadClick}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n showMetadata={false}\n className={cn(\n "w-full rounded-sm border shadow-xs transition-[border-color,box-shadow] duration-150",\n isActive && "border-primary shadow-sm"\n )}\n />\n )\n}\n\nexport function DocxViewerPreview({\n className,\n defaultThumbnailSidebarOpen = true,\n fileName,\n rounded = false,\n src,\n}: {\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n fileName?: string\n rounded?: boolean\n src?: string\n}) {\n const { resolvedTheme } = useTheme()\n const { nightRenderEnabled, nightRenderPrefLoaded, setNightRenderEnabled } =\n useDocumentNightRenderPreference()\n const isViewerHydrated = resolvedTheme !== undefined && nightRenderPrefLoaded\n const shouldShowHydrationSpinner = useDelayedLoadingIndicator(\n !isViewerHydrated,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n\n if (!isViewerHydrated) {\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <div\n className={cn(\n "min-h-0 flex-1 overflow-hidden bg-muted/30 p-4",\n rounded && "rounded-b-lg"\n )}\n >\n <ViewerLoadingSurface showSpinner={shouldShowHydrationSpinner} />\n </div>\n </div>\n )\n }\n\n const shouldRenderNightMode = resolvedTheme === "dark"\n const effectiveIsDark = shouldRenderNightMode && nightRenderEnabled\n\n return (\n <DocxViewerContent\n className={className}\n defaultThumbnailSidebarOpen={defaultThumbnailSidebarOpen}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setNightRenderEnabled}\n shouldRenderNightMode={shouldRenderNightMode}\n url={src}\n />\n )\n}\n\nfunction DocxViewerContent({\n className,\n defaultThumbnailSidebarOpen,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n defaultThumbnailSidebarOpen: boolean\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(\n defaultThumbnailSidebarOpen\n )\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const cacheKey = React.useMemo(\n () =>\n uploadedDocxFile?.identity ??\n (url ? getDocumentCacheKey(url, displayFileName) : "docx-empty"),\n [displayFileName, uploadedDocxFile?.identity, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { importDocxFile, setDocumentTheme, status } = editor\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(editor, thumbnailOptions)\n const [zoomScale, setZoomScale] = React.useState(50)\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <ViewerLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(50)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\n ? await loadCachedDocxFile(url, displayFileName, cacheKey)\n : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : "Unknown DOCX load error"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n void load()\n\n return () => {\n isCurrent = false\n }\n }, [cacheKey, displayFileName, importDocxFile, uploadedDocxFile, url])\n\n React.useEffect(() => {\n if (url) {\n setUploadedDocxFile(null)\n }\n }, [url])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n \'[data-docx-page-wrapper="true"][data-index]\'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback((pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport || !page) return\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n }, [])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomScale(50)\n setActivePage(1)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <DocxToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n isDark={effectiveIsDark}\n onIsDarkChange={setNightRenderEnabled}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showNightRenderToggle={shouldRenderNightMode}\n zoomScale={zoomScale}\n />\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <ScrollArea className="h-full" scrollFade>\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 rounded-sm border 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 </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs text-muted-foreground shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </ScrollArea>\n </DocumentViewerThumbnailSidebar>\n <div\n ref={viewportRef}\n className={cn(\n "min-h-0 flex-1 overflow-auto p-4",\n rounded && "rounded-b-lg"\n )}\n style={{ backgroundColor: viewerBackgroundColor }}\n >\n {!url && !uploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">Upload a DOCX to preview</div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to display DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="mx-auto flex min-h-full justify-center">\n <div\n className={cn(\n "origin-top",\n effectiveIsDark && "docx-night-reader-shell"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode="read-only"\n loadingState={loadingState}\n pageBackgroundColor={effectiveIsDark ? "#0a0a0a" : undefined}\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n'
+ '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n useDocxEditor,\n useDocxViewerThumbnails,\n type DocxDocumentTheme,\n} from "@extend-ai/react-docx"\nimport {\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n SidebarLeftIcon,\n Sun03Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { useTheme } from "next-themes"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\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 "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_SOURCE_CACHE_LIMIT = 3\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst ZOOM_OPTIONS = [10, 25, 50, 75, 100, 125, 150, 175, 200, 400] as const\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\n\nconst docxFileCache = new Map<string, File>()\nconst docxFilePromiseCache = new Map<string, Promise<File>>()\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n}\n\nfunction getDocumentCacheKey(url: string, fileName?: string) {\n return `${url.split("?")[0] ?? url}::${fileName ?? ""}`\n}\n\nfunction rememberDocxFile(cacheKey: string, file: File) {\n if (docxFileCache.has(cacheKey)) {\n docxFileCache.delete(cacheKey)\n }\n\n docxFileCache.set(cacheKey, file)\n\n while (docxFileCache.size > DOCX_SOURCE_CACHE_LIMIT) {\n const oldestKey = docxFileCache.keys().next().value\n if (!oldestKey) break\n docxFileCache.delete(oldestKey)\n }\n}\n\nasync function loadCachedDocxFile(\n url: string,\n displayFileName: string,\n cacheKey: string\n): Promise<File> {\n const cachedFile = docxFileCache.get(cacheKey)\n if (cachedFile) return cachedFile\n\n const pendingRequest = docxFilePromiseCache.get(cacheKey)\n if (pendingRequest) return pendingRequest\n\n const nextRequest = fetch(url)\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n const docxFile = new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n\n rememberDocxFile(cacheKey, docxFile)\n return docxFile\n })\n .finally(() => {\n docxFilePromiseCache.delete(cacheKey)\n })\n\n docxFilePromiseCache.set(cacheKey, nextRequest)\n return nextRequest\n}\n\nfunction formatDocumentName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "document.docx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {\n const currentIndex = ZOOM_OPTIONS.indexOf(\n currentZoomScale as (typeof ZOOM_OPTIONS)[number]\n )\n let fallbackIndex = -1\n\n if (direction > 0) {\n fallbackIndex = ZOOM_OPTIONS.findIndex((value) => value > currentZoomScale)\n } else {\n for (let index = ZOOM_OPTIONS.length - 1; index >= 0; index -= 1) {\n if (ZOOM_OPTIONS[index] < currentZoomScale) {\n fallbackIndex = index\n break\n }\n }\n }\n\n const resolvedIndex = currentIndex >= 0 ? currentIndex : fallbackIndex\n if (resolvedIndex < 0) return currentZoomScale\n\n const nextIndex = Math.min(\n Math.max(resolvedIndex + direction, 0),\n ZOOM_OPTIONS.length - 1\n )\n\n return ZOOM_OPTIONS[nextIndex] ?? currentZoomScale\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\n}\n\nfunction useDocumentNightRenderPreference() {\n const [nightRenderEnabled, setNightRenderEnabled] = React.useState(false)\n const [nightRenderPrefLoaded, setNightRenderPrefLoaded] =\n React.useState(false)\n\n React.useEffect(() => {\n const storedValue = window.localStorage.getItem("docx-night-render")\n setNightRenderEnabled(storedValue === "true")\n setNightRenderPrefLoaded(true)\n }, [])\n\n const updateNightRenderEnabled = React.useCallback((checked: boolean) => {\n setNightRenderEnabled(checked)\n window.localStorage.setItem("docx-night-render", String(checked))\n }, [])\n\n return {\n nightRenderEnabled,\n nightRenderPrefLoaded,\n setNightRenderEnabled: updateNightRenderEnabled,\n }\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\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 ViewerLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction DocxToolbar({\n activePage,\n controlsDisabled,\n isDark,\n onIsDarkChange,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showNightRenderToggle: boolean\n zoomScale: number\n}) {\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n\n return (\n <div className="flex min-h-12 items-center justify-between gap-3 overflow-x-auto overflow-y-hidden border-b bg-background px-3">\n <TooltipProvider>\n <div className="flex items-center gap-2">\n <ToolbarTooltip label="Toggle thumbnails">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Toggle thumbnails"\n disabled={controlsDisabled}\n onClick={onToggleSidebar}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <div className="text-sm whitespace-nowrap text-primary">\n Page {pageCount ? activePage : 1} of {pageCount || "-"}\n </div>\n </div>\n <div className="ml-auto flex shrink-0 items-center gap-1">\n {showNightRenderToggle ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <ToolbarTooltip\n label={isDark ? "Use light document" : "Use dark document"}\n >\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled}\n aria-label={\n isDark ? "Use light document" : "Use dark document"\n }\n onClick={() => onIsDarkChange(!isDark)}\n >\n <HugeiconsIcon\n icon={isDark ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled || !canZoomOut}\n aria-label="Zoom out"\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, -1)\n )\n }\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={zoomScale.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={controlsDisabled}\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(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align="end" alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled || !canZoomIn}\n aria-label="Zoom in"\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarTooltip label="Upload DOCX">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Upload DOCX"\n onClick={onUploadClick}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n showMetadata={false}\n className={cn(\n "w-full rounded-sm border shadow-xs transition-[border-color,box-shadow] duration-150",\n isActive && "border-primary shadow-sm"\n )}\n />\n )\n}\n\nexport function DocxViewerPreview({\n className,\n defaultThumbnailSidebarOpen = true,\n fileName,\n rounded = false,\n src,\n}: {\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n fileName?: string\n rounded?: boolean\n src?: string\n}) {\n const { resolvedTheme } = useTheme()\n const { nightRenderEnabled, nightRenderPrefLoaded, setNightRenderEnabled } =\n useDocumentNightRenderPreference()\n const isViewerHydrated = resolvedTheme !== undefined && nightRenderPrefLoaded\n const shouldShowHydrationSpinner = useDelayedLoadingIndicator(\n !isViewerHydrated,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n\n if (!isViewerHydrated) {\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <div\n className={cn(\n "min-h-0 flex-1 overflow-hidden bg-muted/30 p-4",\n rounded && "rounded-b-lg"\n )}\n >\n <ViewerLoadingSurface showSpinner={shouldShowHydrationSpinner} />\n </div>\n </div>\n )\n }\n\n const shouldRenderNightMode = resolvedTheme === "dark"\n const effectiveIsDark = shouldRenderNightMode && nightRenderEnabled\n\n return (\n <DocxViewerContent\n className={className}\n defaultThumbnailSidebarOpen={defaultThumbnailSidebarOpen}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setNightRenderEnabled}\n shouldRenderNightMode={shouldRenderNightMode}\n url={src}\n />\n )\n}\n\nfunction DocxViewerContent({\n className,\n defaultThumbnailSidebarOpen,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n defaultThumbnailSidebarOpen: boolean\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(\n defaultThumbnailSidebarOpen\n )\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const cacheKey = React.useMemo(\n () =>\n uploadedDocxFile?.identity ??\n (url ? getDocumentCacheKey(url, displayFileName) : "docx-empty"),\n [displayFileName, uploadedDocxFile?.identity, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { importDocxFile, setDocumentTheme, status } = editor\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(editor, thumbnailOptions)\n const [zoomScale, setZoomScale] = React.useState(50)\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <ViewerLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(50)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\n ? await loadCachedDocxFile(url, displayFileName, cacheKey)\n : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : "Unknown DOCX load error"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n void load()\n\n return () => {\n isCurrent = false\n }\n }, [cacheKey, displayFileName, importDocxFile, uploadedDocxFile, url])\n\n React.useEffect(() => {\n if (url) {\n setUploadedDocxFile(null)\n }\n }, [url])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n \'[data-docx-page-wrapper="true"][data-index]\'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback((pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport || !page) return\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n }, [])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomScale(50)\n setActivePage(1)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <DocxToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n isDark={effectiveIsDark}\n onIsDarkChange={setNightRenderEnabled}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showNightRenderToggle={shouldRenderNightMode}\n zoomScale={zoomScale}\n />\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <div className="h-full overflow-auto">\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 rounded-sm border 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 </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs text-muted-foreground shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </div>\n </DocumentViewerThumbnailSidebar>\n <div\n ref={viewportRef}\n className={cn(\n "min-h-0 flex-1 overflow-auto p-4",\n rounded && "rounded-b-lg"\n )}\n style={{ backgroundColor: viewerBackgroundColor }}\n >\n {!url && !uploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">Upload a DOCX to preview</div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to display DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="mx-auto flex min-h-full justify-center">\n <div\n className={cn(\n "origin-top",\n effectiveIsDark && "docx-night-reader-shell"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode="read-only"\n loadingState={loadingState}\n pageBackgroundColor={effectiveIsDark ? "#0a0a0a" : undefined}\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n'
export function DocxViewerSource() {
return <HighlightedCodeBlock code={docxViewerSourceCode} />
diff --git a/apps/v4/components/human-review-docs.tsx b/apps/v4/components/human-review-docs.tsx
index 2307f4c..95ff113 100644
--- a/apps/v4/components/human-review-docs.tsx
+++ b/apps/v4/components/human-review-docs.tsx
@@ -2,10 +2,25 @@
import * as React from "react"
import {
+ DataEditor,
+ emptyGridSelection,
+ GridCellKind,
+ type DrawCellCallback,
+ type EditableGridCell,
+ type GridCell,
+ type GridColumn,
+ type GridSelection,
+ type Item,
+ type Rectangle,
+ type Theme,
+} from "@glideapps/glide-data-grid"
+import {
+ ArrowLeft01Icon,
CancelCircleIcon,
FileDiffIcon,
InputNumericIcon,
InputTextIcon,
+ SecondBracketIcon,
SourceCodeSquareIcon,
TextCheckIcon,
Undo02Icon,
@@ -33,10 +48,19 @@ import {
TooltipTrigger,
} from "@/registry/new-york-v4/ui/tooltip"
+import "@glideapps/glide-data-grid/dist/index.css"
+
type JsonPrimitive = string | number | boolean | null
-type JsonValue = JsonPrimitive | JsonObject
+type JsonValue = JsonPrimitive | JsonObject | JsonArray
type JsonObject = { [key: string]: JsonValue }
-type SchemaPropertyType = "string" | "number" | "integer" | "boolean" | "object"
+type JsonArray = JsonValue[]
+type SchemaPropertyType =
+ | "string"
+ | "number"
+ | "integer"
+ | "boolean"
+ | "object"
+ | "array"
type ReviewFieldSchema = {
type: SchemaPropertyType
@@ -44,6 +68,7 @@ type ReviewFieldSchema = {
description?: string
enum?: Array<string | number>
properties?: Record<string, ReviewFieldSchema>
+ items?: ReviewFieldSchema
}
type ReviewFieldDefinition = {
@@ -99,6 +124,62 @@ const DIFF_VIEWER_THEME = {
"--diffs-line-height": "20px",
} as React.CSSProperties
+function useIsDarkTheme() {
+ const [isDark, setIsDark] = React.useState(false)
+
+ React.useEffect(() => {
+ if (typeof document === "undefined") return
+
+ const root = document.documentElement
+ const updateTheme = () => setIsDark(root.classList.contains("dark"))
+
+ updateTheme()
+
+ if (typeof MutationObserver === "undefined") return
+
+ const observer = new MutationObserver(updateTheme)
+ observer.observe(root, { attributes: true, attributeFilter: ["class"] })
+
+ return () => observer.disconnect()
+ }, [])
+
+ return isDark
+}
+
+function useHumanReviewGridTheme() {
+ const isDark = useIsDarkTheme()
+
+ return React.useMemo<Partial<Theme>>(
+ () => ({
+ accentColor: isDark ? "rgb(96, 165, 250)" : "rgb(37, 99, 235)",
+ accentLight: isDark ? "rgba(29, 78, 216, 0.15)" : "rgb(219, 234, 254)",
+ accentFg: "rgb(255, 255, 255)",
+ textDark: isDark ? "rgb(229, 229, 229)" : "rgb(23, 23, 23)",
+ textMedium: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",
+ textLight: isDark ? "rgb(115, 115, 115)" : "rgb(163, 163, 163)",
+ textBubble: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",
+ textHeader: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",
+ textGroupHeader: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",
+ bgCell: isDark ? "rgb(10, 10, 10)" : "rgb(255, 255, 255)",
+ bgCellMedium: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",
+ bgHeader: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",
+ bgHeaderHasFocus: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",
+ bgHeaderHovered: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",
+ borderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",
+ horizontalBorderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",
+ cellHorizontalPadding: 8,
+ cellVerticalPadding: 3,
+ headerIconSize: 18,
+ baseFontStyle: "13px",
+ headerFontStyle: "600 13px",
+ markerFontStyle: "11px",
+ fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
+ editorFontSize: "13px",
+ }),
+ [isDark]
+ )
+}
+
const REVIEW_SCHEMA: ReviewFieldDefinition[] = [
{
key: "vendor_name",
@@ -142,6 +223,104 @@ const REVIEW_SCHEMA: ReviewFieldDefinition[] = [
area: { left: 13.5, top: 55.5, width: 73.5, height: 7.5 },
},
},
+ {
+ key: "line_items",
+ schema: {
+ type: "array",
+ title: "Line items",
+ description: "Invoice rows with nested allocation details.",
+ items: {
+ type: "object",
+ properties: {
+ description: {
+ type: "string",
+ title: "Description",
+ },
+ quantity: {
+ type: "number",
+ title: "Qty",
+ },
+ unit_price: {
+ type: "number",
+ title: "Unit price",
+ },
+ tax_detail: {
+ type: "object",
+ title: "Tax detail",
+ properties: {
+ code: {
+ type: "string",
+ title: "Code",
+ },
+ jurisdiction: {
+ type: "string",
+ title: "Jurisdiction",
+ },
+ },
+ },
+ allocations: {
+ type: "array",
+ title: "Allocations",
+ items: {
+ type: "object",
+ properties: {
+ department: {
+ type: "string",
+ title: "Department",
+ },
+ percent: {
+ type: "number",
+ title: "Percent",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ actual: [
+ {
+ description: "Transformer implementation support",
+ quantity: 2,
+ unit_price: 4200,
+ tax_detail: { code: "TX-CA", jurisdiction: "CA" },
+ allocations: [
+ { department: "Research", percent: 70 },
+ { department: "Platform", percent: 20 },
+ ],
+ },
+ {
+ description: "Attention model review",
+ quantity: 1,
+ unit_price: 4080,
+ tax_detail: { code: "TX-NY", jurisdiction: "NY" },
+ allocations: [{ department: "Research", percent: 100 }],
+ },
+ ],
+ expected: [
+ {
+ description: "Transformer implementation support",
+ quantity: 2,
+ unit_price: 4200,
+ tax_detail: { code: "TX-CA", jurisdiction: "CA" },
+ allocations: [
+ { department: "Research", percent: 70 },
+ { department: "Platform", percent: 30 },
+ ],
+ },
+ {
+ description: "Attention model review",
+ quantity: 1,
+ unit_price: 4080.75,
+ tax_detail: { code: "TX-NY", jurisdiction: "NY" },
+ allocations: [{ department: "Research", percent: 100 }],
+ },
+ ],
+ location: {
+ page: 1,
+ area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },
+ },
+ },
{
key: "requires_review",
schema: {
@@ -211,6 +390,10 @@ function isJsonObject(value: JsonValue): value is JsonObject {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
+function isJsonArray(value: JsonValue): value is JsonArray {
+ return Array.isArray(value)
+}
+
function getObjectValue(value: JsonValue, key: string): JsonValue {
if (!isJsonObject(value)) return null
return value[key] ?? null
@@ -227,8 +410,22 @@ function setObjectValue(
}
}
+function getArrayValue(value: JsonValue): JsonArray {
+ return isJsonArray(value) ? value : []
+}
+
+function setArrayItemValue(
+ value: JsonValue,
+ index: number,
+ childValue: JsonValue
+): JsonArray {
+ const nextValue = getArrayValue(value).slice()
+ nextValue[index] = childValue
+ return nextValue
+}
+
function getPrimitiveValue(value: JsonValue): JsonPrimitive {
- return isJsonObject(value) ? null : value
+ return isJsonObject(value) || isJsonArray(value) ? null : value
}
function jsonValuesEqual(left: JsonValue, right: JsonValue) {
@@ -281,7 +478,7 @@ function findReviewField(
function formatValue(value: JsonValue) {
if (value === null) return "NULL"
- if (isJsonObject(value)) return formatJson(value)
+ if (isJsonObject(value) || isJsonArray(value)) return formatJson(value)
if (typeof value === "boolean") return value ? "true" : "false"
return String(value)
}
@@ -289,15 +486,18 @@ function formatValue(value: JsonValue) {
function getFieldIcon(type: SchemaPropertyType) {
if (type === "number" || type === "integer") return InputNumericIcon
if (type === "boolean") return TextCheckIcon
+ if (type === "array") return SecondBracketIcon
if (type === "object") return SourceCodeSquareIcon
return InputTextIcon
}
function HumanReviewValueInput({
+ readOnly = false,
schema,
value,
onChange,
}: {
+ readOnly?: boolean
schema: ReviewFieldSchema
value: JsonPrimitive
onChange: (value: JsonPrimitive) => void
@@ -306,6 +506,7 @@ function HumanReviewValueInput({
return (
<span className="relative inline-flex w-full rounded-lg border border-input bg-background text-sm text-foreground shadow-xs/5 dark:bg-input/32">
<select
+ disabled={readOnly}
value={value === null ? "" : String(value)}
onChange={(event) => onChange(event.target.value)}
className="h-8.5 w-full appearance-none rounded-[inherit] bg-transparent px-3 text-sm outline-none sm:h-7.5"
@@ -324,6 +525,7 @@ function HumanReviewValueInput({
return (
<Input
nativeInput
+ readOnly={readOnly}
type="number"
value={value === null ? "" : String(value)}
onChange={(event) => {
@@ -347,6 +549,7 @@ function HumanReviewValueInput({
"h-7 shadow-none",
value === option && "bg-background dark:bg-input"
)}
+ disabled={readOnly}
onClick={() => onChange(option)}
>
{option ? "True" : "False"}
@@ -359,38 +562,828 @@ function HumanReviewValueInput({
return (
<Input
nativeInput
+ readOnly={readOnly}
value={value === null ? "" : String(value)}
onChange={(event) => onChange(event.currentTarget.value)}
/>
)
}
-function HumanReviewFieldCard({
- field,
+function getArrayItemSchema(schema: ReviewFieldSchema): ReviewFieldSchema {
+ return schema.items ?? { type: "string" }
+}
+
+function isComplexSchema(schema: ReviewFieldSchema) {
+ return schema.type === "object" || schema.type === "array"
+}
+
+function summarizeComplexValue(value: JsonValue) {
+ if (isJsonArray(value)) return `${value.length} items`
+ if (isJsonObject(value)) return `${Object.keys(value).length} fields`
+ return formatValue(value)
+}
+
+function getCellValueForArrayColumn(
+ rowValue: JsonValue,
+ itemSchema: ReviewFieldSchema,
+ columnId: string
+) {
+ if (itemSchema.type === "object") {
+ return getObjectValue(rowValue, columnId)
+ }
+
+ return rowValue
+}
+
+function getCellSchemaForArrayColumn(
+ itemSchema: ReviewFieldSchema,
+ columnId: string
+) {
+ if (itemSchema.type === "object") {
+ return itemSchema.properties?.[columnId] ?? { type: "string" }
+ }
+
+ return itemSchema
+}
+
+function applyPrimitiveEdit(
+ schema: ReviewFieldSchema,
+ value: EditableGridCell
+): JsonValue | undefined {
+ if (schema.type === "boolean" && value.kind === GridCellKind.Boolean) {
+ return value.data
+ }
+
+ if (
+ (schema.type === "number" || schema.type === "integer") &&
+ value.kind === GridCellKind.Number
+ ) {
+ return value.data ?? null
+ }
+
+ if (value.kind === GridCellKind.Text) {
+ if (schema.type === "number" || schema.type === "integer") {
+ return value.data.trim() === "" ? null : Number(value.data)
+ }
+
+ return value.data
+ }
+
+ return undefined
+}
+
+type ArrayNestedView = {
+ rowIndex: number
+ columnId: string
+ title: string
+ schema: ReviewFieldSchema
+ value: JsonValue
+}
+
+type ArrayReviewSide = "actual" | "expected"
+
+type SyncedArrayNestedView = {
+ activeSide: ArrayReviewSide | null
+ stack: ArrayNestedView[]
+}
+
+type SyncedArraySelection = {
+ activeSide: ArrayReviewSide | null
+ depth: number
+ gridSelection: GridSelection
+}
+
+const EMPTY_SYNCED_ARRAY_NESTED_VIEW: SyncedArrayNestedView = {
+ activeSide: null,
+ stack: [],
+}
+
+const EMPTY_SYNCED_ARRAY_SELECTION: SyncedArraySelection = {
+ activeSide: null,
+ depth: 0,
+ gridSelection: emptyGridSelection,
+}
+
+function setNestedArrayValue({
+ value,
+ schema,
+ nestedStack,
+ nextNestedValue,
+}: {
+ value: JsonValue
+ schema: ReviewFieldSchema
+ nestedStack: ArrayNestedView[]
+ nextNestedValue: JsonValue
+}): JsonValue {
+ const [currentView, ...remainingViews] = nestedStack
+
+ if (!currentView) return nextNestedValue
+
+ const itemSchema = getArrayItemSchema(schema)
+ const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null
+ const cellSchema = getCellSchemaForArrayColumn(
+ itemSchema,
+ currentView.columnId
+ )
+ const currentCellValue = getCellValueForArrayColumn(
+ rowValue,
+ itemSchema,
+ currentView.columnId
+ )
+ const nextCellValue: JsonValue = remainingViews.length
+ ? setNestedArrayValue({
+ value: currentCellValue,
+ schema: cellSchema,
+ nestedStack: remainingViews,
+ nextNestedValue,
+ })
+ : nextNestedValue
+ const nextRowValue: JsonValue =
+ itemSchema.type === "object"
+ ? setObjectValue(rowValue, currentView.columnId, nextCellValue)
+ : nextCellValue
+
+ return setArrayItemValue(value, currentView.rowIndex, nextRowValue)
+}
+
+function getNestedArrayValue({
+ value,
+ schema,
+ nestedStack,
+}: {
+ value: JsonValue
+ schema: ReviewFieldSchema
+ nestedStack: ArrayNestedView[]
+}): JsonValue {
+ const [currentView, ...remainingViews] = nestedStack
+
+ if (!currentView) return value
+
+ const itemSchema = getArrayItemSchema(schema)
+ const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null
+ const cellSchema = getCellSchemaForArrayColumn(
+ itemSchema,
+ currentView.columnId
+ )
+ const cellValue = getCellValueForArrayColumn(
+ rowValue,
+ itemSchema,
+ currentView.columnId
+ )
+
+ if (!remainingViews.length) return cellValue
+
+ return getNestedArrayValue({
+ value: cellValue,
+ schema: cellSchema,
+ nestedStack: remainingViews,
+ })
+}
+
+function isCellInRange(col: number, row: number, range: Rectangle) {
+ return (
+ col >= range.x &&
+ col < range.x + range.width &&
+ row >= range.y &&
+ row < range.y + range.height
+ )
+}
+
+function getRangeEdges(col: number, row: number, range: Rectangle) {
+ return {
+ bottom: row === range.y + range.height - 1,
+ left: col === range.x,
+ right: col === range.x + range.width - 1,
+ top: row === range.y,
+ }
+}
+
+function HumanReviewArrayValueGrid({
+ activeNestedSide = null,
+ activeSelectionSide = null,
+ label,
+ nestedStackBaseDepth = 0,
+ readOnly = false,
+ schema,
+ selectionDepth = 0,
+ sharedGridSelection,
+ sharedNestedStack,
+ value,
+ viewSide = "expected",
+ onChange,
+ onGridSelectionChange,
+ onNestedStackChange,
+}: {
+ activeNestedSide?: ArrayReviewSide | null
+ activeSelectionSide?: ArrayReviewSide | null
+ label: string
+ nestedStackBaseDepth?: number
+ readOnly?: boolean
+ schema: ReviewFieldSchema
+ selectionDepth?: number
+ sharedGridSelection?: GridSelection
+ sharedNestedStack?: ArrayNestedView[]
+ value: JsonValue
+ viewSide?: ArrayReviewSide
+ onChange?: (value: JsonValue) => void
+ onGridSelectionChange?: (
+ selection: GridSelection,
+ side: ArrayReviewSide,
+ depth: number
+ ) => void
+ onNestedStackChange?: (
+ stack: ArrayNestedView[],
+ side: ArrayReviewSide
+ ) => void
+}) {
+ const rows = getArrayValue(value)
+ const itemSchema = getArrayItemSchema(schema)
+ const gridTheme = useHumanReviewGridTheme()
+ const isDark = useIsDarkTheme()
+ const [localNestedStack, setLocalNestedStack] = React.useState<
+ ArrayNestedView[]
+ >([])
+ const [localGridSelection, setLocalGridSelection] =
+ React.useState<GridSelection>(emptyGridSelection)
+ const nestedStack = sharedNestedStack ?? localNestedStack
+ const syncedGridSelection = sharedGridSelection ?? localGridSelection
+ const gridSelection =
+ sharedGridSelection &&
+ (activeSelectionSide !== viewSide ||
+ selectionDepth !== nestedStackBaseDepth)
+ ? emptyGridSelection
+ : syncedGridSelection
+ const sharedSelectionRange = sharedGridSelection?.current?.range
+ const sharedSelectionRangeStack = sharedGridSelection?.current?.rangeStack
+ const mirroredSelectionRanges = React.useMemo<readonly Rectangle[]>(() => {
+ if (
+ !activeSelectionSide ||
+ activeSelectionSide === viewSide ||
+ selectionDepth !== nestedStackBaseDepth ||
+ !sharedSelectionRange ||
+ !sharedSelectionRangeStack
+ ) {
+ return []
+ }
+
+ return [...sharedSelectionRangeStack, sharedSelectionRange]
+ }, [
+ activeSelectionSide,
+ nestedStackBaseDepth,
+ selectionDepth,
+ sharedSelectionRange,
+ sharedSelectionRangeStack,
+ viewSide,
+ ])
+ const visibleNestedStack = nestedStack.slice(nestedStackBaseDepth)
+ const activeNestedView = visibleNestedStack[0] ?? null
+ const activeNestedValue = activeNestedView
+ ? getNestedArrayValue({
+ value,
+ schema,
+ nestedStack: [activeNestedView],
+ })
+ : null
+ const isActiveNestedSource =
+ Boolean(activeNestedView) && activeNestedSide === viewSide
+ const isMirroredNestedTarget =
+ Boolean(activeNestedView) &&
+ activeNestedSide !== null &&
+ activeNestedSide !== viewSide
+ const blueCellText = isDark ? "rgb(147, 197, 253)" : "rgb(37, 99, 235)"
+ const selectedCellBackground = isDark
+ ? "rgba(37, 99, 235, 0.2)"
+ : "rgba(219, 234, 254, 0.85)"
+ const mirroredCellBackground = isDark
+ ? "rgba(167, 139, 250, 0.18)"
+ : "rgba(237, 233, 254, 0.9)"
+ const mirroredCellBorder = isDark ? "rgb(196, 181, 253)" : "rgb(124, 58, 237)"
+
+ const setNestedStack = React.useCallback(
+ (
+ updater:
+ | ArrayNestedView[]
+ | ((current: ArrayNestedView[]) => ArrayNestedView[])
+ ) => {
+ if (onNestedStackChange) {
+ const nextStack =
+ typeof updater === "function" ? updater(nestedStack) : updater
+
+ onNestedStackChange(nextStack, viewSide)
+ return
+ }
+
+ setLocalNestedStack(updater)
+ },
+ [nestedStack, onNestedStackChange, viewSide]
+ )
+
+ const handleGridSelectionChange = React.useCallback(
+ (selection: GridSelection) => {
+ if (onGridSelectionChange) {
+ onGridSelectionChange(selection, viewSide, nestedStackBaseDepth)
+ return
+ }
+
+ setLocalGridSelection(selection)
+ },
+ [nestedStackBaseDepth, onGridSelectionChange, viewSide]
+ )
+
+ const columns = React.useMemo<GridColumn[]>(() => {
+ if (itemSchema.type === "object") {
+ const propertyEntries = Object.entries(itemSchema.properties ?? {})
+
+ if (propertyEntries.length) {
+ return propertyEntries.map(([key, propertySchema]) => ({
+ id: key,
+ title: propertySchema.title ?? key,
+ width: isComplexSchema(propertySchema) ? 148 : 132,
+ }))
+ }
+ }
+
+ return [
+ {
+ id: "value",
+ title: itemSchema.title ?? "Value",
+ width: isComplexSchema(itemSchema) ? 148 : 180,
+ },
+ ]
+ }, [itemSchema])
+
+ const getCellContent = React.useCallback(
+ ([col, row]: Item): GridCell => {
+ const column = columns[col]
+ const columnId = String(column?.id ?? "value")
+ const rowValue = rows[row] ?? null
+ const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)
+ const cellValue = getCellValueForArrayColumn(
+ rowValue,
+ itemSchema,
+ columnId
+ )
+ const matchedNestedCell =
+ activeNestedView?.rowIndex === row &&
+ activeNestedView.columnId === columnId
+ const matchesMirroredSelection = mirroredSelectionRanges.some((range) =>
+ isCellInRange(col, row, range)
+ )
+ const nestedCellTheme: Partial<Theme> | undefined = matchedNestedCell
+ ? {
+ bgCell: isMirroredNestedTarget
+ ? mirroredCellBackground
+ : selectedCellBackground,
+ textDark: blueCellText,
+ }
+ : undefined
+ const selectionCellTheme: Partial<Theme> | undefined =
+ matchesMirroredSelection
+ ? {
+ bgCell: mirroredCellBackground,
+ textDark: isDark ? "rgb(233, 213, 255)" : "rgb(91, 33, 182)",
+ }
+ : undefined
+
+ if (isComplexSchema(cellSchema)) {
+ return {
+ kind: GridCellKind.Text,
+ data: summarizeComplexValue(cellValue),
+ displayData: summarizeComplexValue(cellValue),
+ allowOverlay: false,
+ readonly: true,
+ cursor: "pointer",
+ activationBehaviorOverride: "double-click",
+ themeOverride: {
+ textDark: blueCellText,
+ ...(selectionCellTheme ?? {}),
+ ...(nestedCellTheme ?? {}),
+ },
+ }
+ }
+
+ if (cellSchema.type === "boolean") {
+ return {
+ kind: GridCellKind.Boolean,
+ data: typeof cellValue === "boolean" ? cellValue : false,
+ allowOverlay: false,
+ readonly: readOnly,
+ ...(selectionCellTheme ? { themeOverride: selectionCellTheme } : {}),
+ }
+ }
+
+ if (cellSchema.type === "number" || cellSchema.type === "integer") {
+ return {
+ kind: GridCellKind.Number,
+ data: typeof cellValue === "number" ? cellValue : undefined,
+ displayData: typeof cellValue === "number" ? String(cellValue) : "",
+ allowOverlay: !readOnly,
+ readonly: readOnly,
+ ...(selectionCellTheme ? { themeOverride: selectionCellTheme } : {}),
+ }
+ }
+
+ return {
+ kind: GridCellKind.Text,
+ data:
+ cellValue === null ||
+ isJsonObject(cellValue) ||
+ isJsonArray(cellValue)
+ ? ""
+ : String(cellValue),
+ displayData:
+ cellValue === null ||
+ isJsonObject(cellValue) ||
+ isJsonArray(cellValue)
+ ? ""
+ : String(cellValue),
+ allowOverlay: !readOnly,
+ readonly: readOnly,
+ ...(selectionCellTheme ? { themeOverride: selectionCellTheme } : {}),
+ }
+ },
+ [
+ activeNestedView,
+ blueCellText,
+ columns,
+ isMirroredNestedTarget,
+ isDark,
+ itemSchema,
+ mirroredCellBackground,
+ mirroredSelectionRanges,
+ readOnly,
+ rows,
+ selectedCellBackground,
+ ]
+ )
+
+ const updateCellValue = React.useCallback(
+ ([col, row]: Item, nextCell: EditableGridCell) => {
+ if (readOnly || !onChange) return
+
+ const column = columns[col]
+ const columnId = String(column?.id ?? "value")
+ const rowValue = rows[row] ?? null
+ const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)
+ const nextValue = applyPrimitiveEdit(cellSchema, nextCell)
+
+ if (nextValue === undefined) return
+
+ const nextRowValue =
+ itemSchema.type === "object"
+ ? setObjectValue(rowValue, columnId, nextValue)
+ : nextValue
+
+ onChange(setArrayItemValue(value, row, nextRowValue))
+ },
+ [columns, itemSchema, onChange, readOnly, rows, value]
+ )
+
+ const drawCell = React.useCallback<DrawCellCallback>(
+ (args, drawContent) => {
+ drawContent()
+
+ const selectionRange = mirroredSelectionRanges.find((range) =>
+ isCellInRange(args.col, args.row, range)
+ )
+
+ if (!selectionRange) {
+ return
+ }
+
+ const { ctx, rect } = args
+ const edges = getRangeEdges(args.col, args.row, selectionRange)
+
+ ctx.save()
+ ctx.strokeStyle = mirroredCellBorder
+ ctx.lineWidth = 1.5
+ ctx.setLineDash([4, 3])
+
+ if (edges.top) {
+ ctx.beginPath()
+ ctx.moveTo(rect.x + 1.5, rect.y + 1.5)
+ ctx.lineTo(rect.x + rect.width - 1.5, rect.y + 1.5)
+ ctx.stroke()
+ }
+
+ if (edges.right) {
+ ctx.beginPath()
+ ctx.moveTo(rect.x + rect.width - 1.5, rect.y + 1.5)
+ ctx.lineTo(rect.x + rect.width - 1.5, rect.y + rect.height - 1.5)
+ ctx.stroke()
+ }
+
+ if (edges.bottom) {
+ ctx.beginPath()
+ ctx.moveTo(rect.x + 1.5, rect.y + rect.height - 1.5)
+ ctx.lineTo(rect.x + rect.width - 1.5, rect.y + rect.height - 1.5)
+ ctx.stroke()
+ }
+
+ if (edges.left) {
+ ctx.beginPath()
+ ctx.moveTo(rect.x + 1.5, rect.y + 1.5)
+ ctx.lineTo(rect.x + 1.5, rect.y + rect.height - 1.5)
+ ctx.stroke()
+ }
+
+ ctx.restore()
+ },
+ [mirroredCellBorder, mirroredSelectionRanges]
+ )
+
+ const openNestedCell = React.useCallback(
+ ([col, row]: Item) => {
+ const column = columns[col]
+ const columnId = String(column?.id ?? "value")
+ const rowValue = rows[row] ?? null
+ const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)
+
+ if (!isComplexSchema(cellSchema)) return
+
+ setNestedStack((current) => {
+ const nextView = {
+ rowIndex: row,
+ columnId,
+ title: `${column?.title ?? columnId} / row ${row + 1}`,
+ schema: cellSchema,
+ value: getCellValueForArrayColumn(rowValue, itemSchema, columnId),
+ }
+ const currentView = current[nestedStackBaseDepth]
+
+ if (
+ currentView?.rowIndex === nextView.rowIndex &&
+ currentView.columnId === nextView.columnId
+ ) {
+ return current
+ }
+
+ return [...current.slice(0, nestedStackBaseDepth), nextView]
+ })
+ },
+ [columns, itemSchema, nestedStackBaseDepth, rows, setNestedStack]
+ )
+
+ const updateNestedValue = React.useCallback(
+ (nextNestedValue: JsonValue) => {
+ if (!activeNestedView || readOnly || !onChange) return
+
+ onChange(
+ setNestedArrayValue({
+ value,
+ schema,
+ nestedStack: visibleNestedStack.slice(0, 1),
+ nextNestedValue,
+ })
+ )
+ setNestedStack((current) =>
+ current.map((view, index) =>
+ index === nestedStackBaseDepth
+ ? { ...view, value: nextNestedValue }
+ : view
+ )
+ )
+ },
+ [
+ activeNestedView,
+ nestedStackBaseDepth,
+ onChange,
+ readOnly,
+ schema,
+ setNestedStack,
+ value,
+ visibleNestedStack,
+ ]
+ )
+
+ return (
+ <div
+ className={cn(
+ "relative overflow-hidden rounded-md border bg-background transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:shadow-[0_0_0_1px_rgb(59_130_246_/_8%)] hover:border-blue-500/50",
+ isActiveNestedSource &&
+ "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_10%)]"
+ )}
+ >
+ <div>
+ <div className="flex h-8 items-center justify-between gap-2 border-b px-2 text-[11px] font-medium text-muted-foreground">
+ <span>{label}</span>
+ <span>{rows.length} rows</span>
+ </div>
+ <div className="h-[220px]">
+ <DataEditor
+ columns={columns}
+ rows={rows.length}
+ getCellContent={getCellContent}
+ cellActivationBehavior="double-click"
+ drawCell={drawCell}
+ gridSelection={gridSelection}
+ onCellEdited={updateCellValue}
+ onCellActivated={openNestedCell}
+ onGridSelectionChange={handleGridSelectionChange}
+ rowMarkers="number"
+ smoothScrollX
+ smoothScrollY
+ theme={gridTheme}
+ width="100%"
+ height="100%"
+ rowHeight={32}
+ headerHeight={34}
+ />
+ </div>
+ </div>
+ {activeNestedView ? (
+ <div className="absolute inset-0 z-10 flex flex-col bg-background">
+ <div className="flex h-8 items-center gap-2 border-b px-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="size-6 text-muted-foreground"
+ onClick={() =>
+ setNestedStack((current) =>
+ current.slice(
+ 0,
+ Math.max(nestedStackBaseDepth, current.length - 1)
+ )
+ )
+ }
+ aria-label="Back to parent array"
+ >
+ <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />
+ </Button>
+ <div className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">
+ {activeNestedView.title}
+ </div>
+ </div>
+ <div className="min-h-0 flex-1 overflow-auto p-2">
+ {activeNestedView.schema.type === "array" ? (
+ <HumanReviewArrayValueGrid
+ label={
+ activeNestedView.schema.title ?? activeNestedView.columnId
+ }
+ nestedStackBaseDepth={nestedStackBaseDepth + 1}
+ readOnly={readOnly}
+ schema={activeNestedView.schema}
+ sharedGridSelection={sharedGridSelection}
+ sharedNestedStack={sharedNestedStack}
+ value={activeNestedValue}
+ viewSide={viewSide}
+ activeNestedSide={activeNestedSide}
+ activeSelectionSide={activeSelectionSide}
+ selectionDepth={selectionDepth}
+ onChange={updateNestedValue}
+ onGridSelectionChange={onGridSelectionChange}
+ onNestedStackChange={onNestedStackChange}
+ />
+ ) : (
+ <HumanReviewObjectValueEditor
+ schema={activeNestedView.schema}
+ value={activeNestedValue}
+ originalValue={activeNestedValue}
+ readOnly={readOnly}
+ onChange={updateNestedValue}
+ />
+ )}
+ </div>
+ </div>
+ ) : null}
+ </div>
+ )
+}
+
+function HumanReviewObjectValueEditor({
+ schema,
value,
originalValue,
- active,
- activeFieldKey,
+ readOnly = false,
onChange,
- onFieldFocus,
- onUndo,
- onSetNull,
}: {
+ schema: ReviewFieldSchema
+ value: JsonValue
+ originalValue: JsonValue
+ readOnly?: boolean
+ onChange: (value: JsonValue) => void
+}) {
+ const propertyEntries = Object.entries(schema.properties ?? {})
+
+ if (!propertyEntries.length) {
+ return (
+ <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">
+ No properties
+ </div>
+ )
+ }
+
+ return (
+ <div className="space-y-2">
+ {propertyEntries.map(([propertyKey, propertySchema]) => (
+ <HumanReviewFieldCard
+ key={propertyKey}
+ field={{
+ key: propertyKey,
+ schema: propertySchema,
+ actual: getObjectValue(originalValue, propertyKey),
+ expected: getObjectValue(originalValue, propertyKey),
+ }}
+ value={getObjectValue(value, propertyKey)}
+ originalValue={getObjectValue(originalValue, propertyKey)}
+ readOnly={readOnly}
+ onChange={(childValue) =>
+ !readOnly &&
+ onChange(setObjectValue(value, propertyKey, childValue))
+ }
+ onUndo={() =>
+ !readOnly &&
+ onChange(
+ setObjectValue(
+ value,
+ propertyKey,
+ getObjectValue(originalValue, propertyKey)
+ )
+ )
+ }
+ onSetNull={() =>
+ !readOnly && onChange(setObjectValue(value, propertyKey, null))
+ }
+ />
+ ))}
+ </div>
+ )
+}
+
+type HumanReviewFieldCardProps = {
field: ReviewFieldDefinition
value: JsonValue
originalValue: JsonValue
active?: boolean
activeFieldKey?: string
+ readOnly?: boolean
onChange: (value: JsonValue) => void
onFieldFocus?: (field: ReviewFieldDefinition) => void
onUndo: () => void
onSetNull: () => void
-}) {
+}
+
+function areHumanReviewFieldCardPropsEqual(
+ previous: HumanReviewFieldCardProps,
+ next: HumanReviewFieldCardProps
+) {
+ return (
+ previous.field === next.field &&
+ Object.is(previous.value, next.value) &&
+ Object.is(previous.originalValue, next.originalValue) &&
+ previous.active === next.active &&
+ previous.activeFieldKey === next.activeFieldKey &&
+ previous.readOnly === next.readOnly &&
+ previous.onFieldFocus === next.onFieldFocus
+ )
+}
+
+const HumanReviewFieldCard = React.memo(
+ HumanReviewFieldCardBase,
+ areHumanReviewFieldCardPropsEqual
+)
+
+function HumanReviewFieldCardBase({
+ field,
+ value,
+ originalValue,
+ active,
+ activeFieldKey,
+ readOnly = false,
+ onChange,
+ onFieldFocus,
+ onUndo,
+ onSetNull,
+}: HumanReviewFieldCardProps) {
const modified = !jsonValuesEqual(value, originalValue)
const Icon = getFieldIcon(field.schema.type)
const propertyEntries = Object.entries(field.schema.properties ?? {})
-
- return (
+ const [syncedArrayNestedView, setSyncedArrayNestedView] =
+ React.useState<SyncedArrayNestedView>(EMPTY_SYNCED_ARRAY_NESTED_VIEW)
+ const [syncedArraySelection, setSyncedArraySelection] =
+ React.useState<SyncedArraySelection>(EMPTY_SYNCED_ARRAY_SELECTION)
+ const updateSyncedArrayNestedView = React.useCallback(
+ (stack: ArrayNestedView[], side: ArrayReviewSide) => {
+ setSyncedArrayNestedView({
+ activeSide: stack.length ? side : null,
+ stack,
+ })
+ },
+ []
+ )
+ const updateSyncedArraySelection = React.useCallback(
+ (gridSelection: GridSelection, side: ArrayReviewSide, depth: number) => {
+ setSyncedArraySelection({
+ activeSide: gridSelection.current ? side : null,
+ depth,
+ gridSelection,
+ })
+ },
+ []
+ )
+
+ return (
<div
tabIndex={0}
onFocusCapture={() => onFieldFocus?.(field)}
@@ -423,7 +1416,7 @@ function HumanReviewFieldCard({
) : null}
</div>
<div className="flex shrink-0 items-center gap-1">
- {modified ? (
+ {!readOnly && modified ? (
<Tooltip>
<TooltipTrigger asChild>
<Button
@@ -440,21 +1433,23 @@ function HumanReviewFieldCard({
<TooltipContent>Revert changes</TooltipContent>
</Tooltip>
) : null}
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- className="text-muted-foreground"
- onClick={onSetNull}
- aria-label={`Set ${field.key} to null`}
- >
- <HugeiconsIcon icon={CancelCircleIcon} className="size-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>Set to NULL</TooltipContent>
- </Tooltip>
+ {!readOnly ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="text-muted-foreground"
+ onClick={onSetNull}
+ aria-label={`Set ${field.key} to null`}
+ >
+ <HugeiconsIcon icon={CancelCircleIcon} className="size-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Set to NULL</TooltipContent>
+ </Tooltip>
+ ) : null}
<div className="flex h-6 items-center gap-1 rounded-md border bg-muted/50 px-1.5 text-xs text-muted-foreground">
<HugeiconsIcon icon={Icon} className="size-3.5" />
{field.schema.type}
@@ -485,6 +1480,7 @@ function HumanReviewFieldCard({
originalValue={childField.expected}
active={childField.key === activeFieldKey}
activeFieldKey={activeFieldKey}
+ readOnly={readOnly}
onChange={(childValue) =>
onChange(setObjectValue(value, propertyKey, childValue))
}
@@ -507,6 +1503,38 @@ function HumanReviewFieldCard({
)}
</div>
</div>
+ ) : field.schema.type === "array" ? (
+ <div className="grid gap-2">
+ <HumanReviewArrayValueGrid
+ activeNestedSide={syncedArrayNestedView.activeSide}
+ activeSelectionSide={syncedArraySelection.activeSide}
+ label="Actual"
+ readOnly
+ schema={field.schema}
+ selectionDepth={syncedArraySelection.depth}
+ sharedGridSelection={syncedArraySelection.gridSelection}
+ sharedNestedStack={syncedArrayNestedView.stack}
+ value={field.actual}
+ viewSide="actual"
+ onGridSelectionChange={updateSyncedArraySelection}
+ onNestedStackChange={updateSyncedArrayNestedView}
+ />
+ <HumanReviewArrayValueGrid
+ activeNestedSide={syncedArrayNestedView.activeSide}
+ activeSelectionSide={syncedArraySelection.activeSide}
+ label="Expected"
+ readOnly={readOnly}
+ schema={field.schema}
+ selectionDepth={syncedArraySelection.depth}
+ sharedGridSelection={syncedArraySelection.gridSelection}
+ sharedNestedStack={syncedArrayNestedView.stack}
+ value={value}
+ viewSide="expected"
+ onChange={onChange}
+ onGridSelectionChange={updateSyncedArraySelection}
+ onNestedStackChange={updateSyncedArrayNestedView}
+ />
+ </div>
) : (
<div className="grid gap-2 sm:grid-cols-2">
<div className="rounded-md border bg-muted/30 p-2">
@@ -522,6 +1550,7 @@ function HumanReviewFieldCard({
Expected
</div>
<HumanReviewValueInput
+ readOnly={readOnly}
schema={field.schema}
value={getPrimitiveValue(value)}
onChange={onChange}
@@ -606,19 +1635,23 @@ function HumanReviewPanel({
className?: string
onFieldFocus?: (field: ReviewFieldDefinition) => void
} = {}) {
+ const [activeTab, setActiveTab] = React.useState("form")
const [expected, setExpected] = React.useState<JsonObject>(
INITIAL_EXPECTED_VALUES
)
const updateValue = React.useCallback((key: string, value: JsonValue) => {
- setExpected((current) => ({ ...current, [key]: value }))
+ setExpected((current) =>
+ Object.is(current[key], value) ? current : { ...current, [key]: value }
+ )
}, [])
const fieldCount = React.useMemo(() => countReviewFields(REVIEW_SCHEMA), [])
return (
<TooltipProvider delay={200}>
<Tabs
- defaultValue="form"
+ value={activeTab}
+ onValueChange={setActiveTab}
className={cn("flex h-[560px] flex-col gap-0 bg-background", className)}
>
<div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">
@@ -661,7 +1694,9 @@ function HumanReviewPanel({
</ScrollArea>
</TabsContent>
<TabsContent value="json" className="min-h-0 flex-1">
- <JsonDiffView actual={ACTUAL_VALUES} expected={expected} />
+ {activeTab === "json" ? (
+ <JsonDiffView actual={ACTUAL_VALUES} expected={expected} />
+ ) : null}
</TabsContent>
</Tabs>
</TooltipProvider>
@@ -803,6 +1838,58 @@ const fields: ReviewField[] = [
actual: "Net 15",
expected: "Net 30",
},
+ {
+ key: "line_items",
+ schema: {
+ type: "array",
+ title: "Line items",
+ items: {
+ type: "object",
+ properties: {
+ description: { type: "string", title: "Description" },
+ quantity: { type: "number", title: "Qty" },
+ unit_price: { type: "number", title: "Unit price" },
+ tax_detail: {
+ type: "object",
+ title: "Tax detail",
+ properties: {
+ code: { type: "string", title: "Code" },
+ jurisdiction: { type: "string", title: "Jurisdiction" },
+ },
+ },
+ allocations: {
+ type: "array",
+ title: "Allocations",
+ items: {
+ type: "object",
+ properties: {
+ department: { type: "string", title: "Department" },
+ percent: { type: "number", title: "Percent" },
+ },
+ },
+ },
+ },
+ },
+ },
+ actual: [
+ {
+ description: "Transformer implementation support",
+ quantity: 2,
+ unit_price: 4200,
+ tax_detail: { code: "TX-CA", jurisdiction: "CA" },
+ allocations: [{ department: "Platform", percent: 20 }],
+ },
+ ],
+ expected: [
+ {
+ description: "Transformer implementation support",
+ quantity: 2,
+ unit_price: 4200,
+ tax_detail: { code: "TX-CA", jurisdiction: "CA" },
+ allocations: [{ department: "Platform", percent: 30 }],
+ },
+ ],
+ },
{
key: "requires_review",
schema: {
@@ -862,424 +1949,8 @@ export function HumanReviewExample() {
);
}`
-const humanReviewSourceCode = `"use client";
-
-import * as React from "react";
-import {
- CancelCircleIcon,
- FileDiffIcon,
- InputNumericIcon,
- InputTextIcon,
- SourceCodeSquareIcon,
- TextCheckIcon,
- Undo02Icon,
-} from "@hugeicons/core-free-icons";
-import { HugeiconsIcon } from "@hugeicons/react";
-import { MultiFileDiff, Virtualizer } from "@pierre/diffs/react";
-
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { ScrollArea } from "@/components/ui/scroll-area";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
-import { cn } from "@/lib/utils";
-
-export type JsonPrimitive = string | number | boolean | null;
-export type JsonValue = JsonPrimitive | JsonObject;
-export type JsonObject = { [key: string]: JsonValue };
-export type ReviewFieldType = "string" | "number" | "integer" | "boolean" | "object";
-
-export type ReviewFieldSchema = {
- type: ReviewFieldType;
- title?: string;
- description?: string;
- enum?: Array<string | number>;
- properties?: Record<string, ReviewFieldSchema>;
-};
-
-export type ReviewField = {
- key: string;
- schema: ReviewFieldSchema;
- actual: JsonValue;
- expected: JsonValue;
-};
-
-function formatJson(value: unknown) {
- return JSON.stringify(value, null, 2);
-}
-
-function isJsonObject(value: JsonValue): value is JsonObject {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-
-function getObjectValue(value: JsonValue, key: string): JsonValue {
- if (!isJsonObject(value)) return null;
- return value[key] ?? null;
-}
-
-function setObjectValue(value: JsonValue, key: string, childValue: JsonValue): JsonObject {
- return {
- ...(isJsonObject(value) ? value : {}),
- [key]: childValue,
- };
-}
-
-function getPrimitiveValue(value: JsonValue): JsonPrimitive {
- return isJsonObject(value) ? null : value;
-}
-
-function jsonValuesEqual(left: JsonValue, right: JsonValue) {
- return formatJson(left) === formatJson(right);
-}
-
-function countReviewFields(fields: ReviewField[]): number {
- return fields.reduce((count, field) => {
- if (field.schema.type !== "object") return count + 1;
-
- const childFields = Object.entries(field.schema.properties ?? {}).map(
- ([key, schema]): ReviewField => ({
- key: \`\${field.key}.\${key}\`,
- schema,
- actual: getObjectValue(field.actual, key),
- expected: getObjectValue(field.expected, key),
- }),
- );
-
- return count + Math.max(countReviewFields(childFields), 1);
- }, 0);
-}
-
-function formatValue(value: JsonValue) {
- if (value === null) return "NULL";
- if (isJsonObject(value)) return formatJson(value);
- if (typeof value === "boolean") return value ? "true" : "false";
- return String(value);
-}
-
-function getFieldIcon(type: ReviewFieldType) {
- if (type === "number" || type === "integer") return InputNumericIcon;
- if (type === "boolean") return TextCheckIcon;
- if (type === "object") return SourceCodeSquareIcon;
- return InputTextIcon;
-}
-
-const DIFF_VIEWER_THEME = {
- "--diffs-light-bg": "oklch(0.985 0.002 247)",
- "--diffs-dark-bg": "oklch(0.18 0.003 247)",
- "--diffs-light": "oklch(0.22 0.01 247)",
- "--diffs-dark": "oklch(0.92 0.006 247)",
- "--diffs-bg-context-override":
- "light-dark(oklch(0.967 0.003 247), oklch(0.235 0.004 247))",
- "--diffs-bg-context-gutter-override":
- "light-dark(oklch(0.948 0.004 247), oklch(0.205 0.004 247))",
- "--diffs-bg-separator-override":
- "light-dark(oklch(0.94 0.004 247), oklch(0.255 0.005 247))",
- "--diffs-bg-buffer-override":
- "light-dark(oklch(0.955 0.004 247), oklch(0.225 0.004 247))",
- "--diffs-light-addition-color": "oklch(0.54 0.13 158)",
- "--diffs-dark-addition-color": "oklch(0.72 0.13 158)",
- "--diffs-light-deletion-color": "oklch(0.55 0.16 28)",
- "--diffs-dark-deletion-color": "oklch(0.72 0.14 28)",
- "--diffs-bg-addition-override":
- "light-dark(oklch(0.957 0.032 158), oklch(0.255 0.052 158))",
- "--diffs-bg-addition-emphasis-override":
- "light-dark(oklch(0.88 0.06 158), oklch(0.36 0.08 158))",
- "--diffs-bg-deletion-override":
- "light-dark(oklch(0.958 0.03 28), oklch(0.255 0.047 28))",
- "--diffs-bg-deletion-emphasis-override":
- "light-dark(oklch(0.9 0.052 28), oklch(0.36 0.075 28))",
- "--diffs-fg-number-override":
- "light-dark(oklch(0.56 0.018 247), oklch(0.66 0.012 247))",
- "--diffs-font-size": "12px",
- "--diffs-line-height": "20px",
-} as React.CSSProperties;
-
-function ReviewValueInput({
- field,
- value,
- onChange,
-}: {
- field: ReviewField;
- value: JsonPrimitive;
- onChange: (value: JsonPrimitive) => void;
-}) {
- if (field.schema.enum?.length) {
- return (
- <select
- value={value === null ? "" : String(value)}
- onChange={(event) => onChange(event.target.value)}
- className="h-8 w-full rounded-lg border border-input bg-background px-3 text-sm"
- >
- {field.schema.enum.map((option) => (
- <option key={String(option)} value={String(option)}>
- {String(option)}
- </option>
- ))}
- </select>
- );
- }
-
- if (field.schema.type === "number" || field.schema.type === "integer") {
- return (
- <Input
- nativeInput
- type="number"
- value={value === null ? "" : String(value)}
- onChange={(event) => {
- const nextValue = event.currentTarget.value;
- onChange(nextValue === "" ? null : Number(nextValue));
- }}
- />
- );
- }
-
- if (field.schema.type === "boolean") {
- return (
- <div className="grid grid-cols-2 gap-1 rounded-lg bg-muted p-0.5">
- {[true, false].map((option) => (
- <Button
- key={String(option)}
- type="button"
- size="sm"
- variant={value === option ? "outline" : "ghost"}
- onClick={() => onChange(option)}
- >
- {option ? "True" : "False"}
- </Button>
- ))}
- </div>
- );
- }
-
- return (
- <Input
- nativeInput
- value={value === null ? "" : String(value)}
- onChange={(event) => onChange(event.currentTarget.value)}
- />
- );
-}
-
-export function HumanReviewFieldCard({
- field,
- value,
- onChange,
- onUndo,
- onSetNull,
-}: {
- field: ReviewField;
- value: JsonValue;
- onChange: (value: JsonValue) => void;
- onUndo: () => void;
- onSetNull: () => void;
-}) {
- const modified = !jsonValuesEqual(value, field.expected);
- const Icon = getFieldIcon(field.schema.type);
- const propertyEntries = Object.entries(field.schema.properties ?? {});
-
- return (
- <div className="rounded-lg border bg-background p-3">
- <div className="mb-3 flex min-h-8 items-start justify-between gap-3">
- <div className="min-w-0">
- <div className="flex min-w-0 items-center gap-2">
- <div className="truncate text-sm font-medium">
- {field.schema.title ?? field.key}
- </div>
- <span className={cn("size-2 shrink-0 rounded-full bg-amber-400", !modified && "opacity-0")} />
- </div>
- {field.schema.description ? (
- <div className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">
- {field.schema.description}
- </div>
- ) : null}
- </div>
- <div className="flex shrink-0 items-center gap-1">
- {modified ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button type="button" variant="ghost" size="icon-sm" onClick={onUndo}>
- <HugeiconsIcon icon={Undo02Icon} className="size-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>Revert changes</TooltipContent>
- </Tooltip>
- ) : null}
- <Tooltip>
- <TooltipTrigger asChild>
- <Button type="button" variant="ghost" size="icon-sm" onClick={onSetNull}>
- <HugeiconsIcon icon={CancelCircleIcon} className="size-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>Set to NULL</TooltipContent>
- </Tooltip>
- <div className="flex h-6 items-center gap-1 rounded-md border bg-muted/50 px-1.5 text-xs text-muted-foreground">
- <HugeiconsIcon icon={Icon} className="size-3.5" />
- {field.schema.type}
- </div>
- </div>
- </div>
- {field.schema.type === "object" ? (
- <div className="rounded-md border bg-muted/25 p-2">
- <div className="mb-2 flex items-center justify-between gap-3 text-[11px] font-medium text-muted-foreground">
- <span>Properties</span>
- <span>{propertyEntries.length} fields</span>
- </div>
- <div className="space-y-2">
- {propertyEntries.length ? (
- propertyEntries.map(([propertyKey, schema]) => {
- const childField: ReviewField = {
- key: \`\${field.key}.\${propertyKey}\`,
- schema,
- actual: getObjectValue(field.actual, propertyKey),
- expected: getObjectValue(field.expected, propertyKey),
- };
-
- return (
- <HumanReviewFieldCard
- key={childField.key}
- field={childField}
- value={getObjectValue(value, propertyKey)}
- onChange={(childValue) =>
- onChange(setObjectValue(value, propertyKey, childValue))
- }
- onUndo={() =>
- onChange(setObjectValue(value, propertyKey, childField.expected))
- }
- onSetNull={() =>
- onChange(setObjectValue(value, propertyKey, null))
- }
- />
- );
- })
- ) : (
- <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">
- No properties
- </div>
- )}
- </div>
- </div>
- ) : (
- <div className="grid gap-2 sm:grid-cols-2">
- <div className="rounded-md border bg-muted/30 p-2">
- <div className="mb-1 text-[11px] font-medium text-muted-foreground">
- Actual
- </div>
- <div className="min-h-7 rounded-md bg-background px-2 py-1.5 text-sm">
- {formatValue(field.actual)}
- </div>
- </div>
- <div className="rounded-md border bg-muted/30 p-2">
- <div className="mb-1 text-[11px] font-medium text-muted-foreground">
- Expected
- </div>
- <ReviewValueInput
- field={field}
- value={getPrimitiveValue(value)}
- onChange={onChange}
- />
- </div>
- </div>
- )}
- </div>
- );
-}
-
-export function JsonDiffView({
- actual,
- expected,
-}: {
- actual: JsonObject;
- expected: JsonObject;
-}) {
- return (
- <Virtualizer
- className="h-full overflow-auto bg-surface/60"
- contentClassName="min-w-full"
- >
- <MultiFileDiff
- className="block min-w-full"
- style={DIFF_VIEWER_THEME}
- oldFile={{ name: "actual.json", contents: formatJson(actual), lang: "json" }}
- newFile={{ name: "expected.json", contents: formatJson(expected), lang: "json" }}
- disableWorkerPool
- options={{
- diffStyle: "split",
- diffIndicators: "bars",
- hunkSeparators: "line-info-basic",
- overflow: "wrap",
- theme: { light: "pierre-light", dark: "pierre-dark" },
- }}
- />
- </Virtualizer>
- );
-}
-
-export function HumanReviewPanel({
- fields,
- values,
- onValuesChange,
- className,
-}: {
- fields: ReviewField[];
- values: JsonObject;
- onValuesChange: (values: JsonObject) => void;
- className?: string;
-}) {
- const actual = React.useMemo(
- () => Object.fromEntries(fields.map((field) => [field.key, field.actual])),
- [fields],
- );
-
- const updateValue = React.useCallback(
- (key: string, value: JsonValue) => {
- onValuesChange({ ...values, [key]: value });
- },
- [onValuesChange, values],
- );
- const fieldCount = React.useMemo(() => countReviewFields(fields), [fields]);
-
- return (
- <TooltipProvider delay={200}>
- <Tabs defaultValue="form" className={cn("flex flex-col gap-0 bg-background", className)}>
- <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">
- <TabsList className="h-8 sm:h-7">
- <TabsTrigger value="form" className="h-7 sm:h-6">
- <HugeiconsIcon icon={TextCheckIcon} className="size-4" />
- Form
- </TabsTrigger>
- <TabsTrigger value="json" className="h-7 sm:h-6">
- <HugeiconsIcon icon={SourceCodeSquareIcon} className="size-4" />
- JSON
- </TabsTrigger>
- </TabsList>
- <div className="flex h-8 items-center gap-1 rounded-md border bg-muted/40 px-2 text-xs text-muted-foreground sm:h-7">
- <HugeiconsIcon icon={FileDiffIcon} className="size-3.5" />
- {fieldCount} fields
- </div>
- </div>
- <TabsContent value="form" className="min-h-0 flex-1">
- <ScrollArea className="h-full" scrollFade>
- <div className="space-y-3 p-3">
- {fields.map((field) => (
- <HumanReviewFieldCard
- key={field.key}
- field={field}
- value={values[field.key] ?? null}
- onChange={(value) => updateValue(field.key, value)}
- onUndo={() => updateValue(field.key, field.expected)}
- onSetNull={() => updateValue(field.key, null)}
- />
- ))}
- </div>
- </ScrollArea>
- </TabsContent>
- <TabsContent value="json" className="min-h-0 flex-1">
- <JsonDiffView actual={actual} expected={values} />
- </TabsContent>
- </Tabs>
- </TooltipProvider>
- );
-}`
+const humanReviewSourceCode =
+ '"use client"\n\nimport * as React from "react"\nimport {\n DataEditor,\n emptyGridSelection,\n GridCellKind,\n type DrawCellCallback,\n type EditableGridCell,\n type GridCell,\n type GridColumn,\n type GridSelection,\n type Item,\n type Rectangle,\n type Theme,\n} from "@glideapps/glide-data-grid"\nimport {\n ArrowLeft01Icon,\n CancelCircleIcon,\n FileDiffIcon,\n InputNumericIcon,\n InputTextIcon,\n SecondBracketIcon,\n SourceCodeSquareIcon,\n TextCheckIcon,\n Undo02Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { MultiFileDiff, Virtualizer } from "@pierre/diffs/react"\n\nimport { cn } from "@/lib/utils"\nimport { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"\nimport { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"\nimport { Button } from "@/registry/new-york-v4/ui/button"\nimport { Input } from "@/registry/new-york-v4/ui/input"\nimport { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"\nimport {\n Tabs,\n TabsContent,\n TabsList,\n TabsTrigger,\n} from "@/registry/new-york-v4/ui/tabs"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nimport "@glideapps/glide-data-grid/dist/index.css"\n\nexport type JsonPrimitive = string | number | boolean | null\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray\nexport type JsonObject = { [key: string]: JsonValue }\nexport type JsonArray = JsonValue[]\nexport type SchemaPropertyType =\n | "string"\n | "number"\n | "integer"\n | "boolean"\n | "object"\n | "array"\n\nexport type ReviewFieldSchema = {\n type: SchemaPropertyType\n title?: string\n description?: string\n enum?: Array<string | number>\n properties?: Record<string, ReviewFieldSchema>\n items?: ReviewFieldSchema\n}\n\nexport type HighlightArea = {\n left: number\n top: number\n width: number\n height: number\n}\n\nexport type ReviewField = {\n key: string\n schema: ReviewFieldSchema\n actual: JsonValue\n expected: JsonValue\n location?: {\n page: number\n area: HighlightArea\n }\n}\n\nconst DEFAULT_ZOOM = 0.75\nconst REVIEW_HIGHLIGHT_STYLE =\n "border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_10%)]"\nconst DIFF_VIEWER_THEME = {\n "--diffs-light-bg": "oklch(0.985 0.002 247)",\n "--diffs-dark-bg": "oklch(0.18 0.003 247)",\n "--diffs-light": "oklch(0.22 0.01 247)",\n "--diffs-dark": "oklch(0.92 0.006 247)",\n "--diffs-bg-context-override":\n "light-dark(oklch(0.967 0.003 247), oklch(0.235 0.004 247))",\n "--diffs-bg-context-gutter-override":\n "light-dark(oklch(0.948 0.004 247), oklch(0.205 0.004 247))",\n "--diffs-bg-separator-override":\n "light-dark(oklch(0.94 0.004 247), oklch(0.255 0.005 247))",\n "--diffs-bg-buffer-override":\n "light-dark(oklch(0.955 0.004 247), oklch(0.225 0.004 247))",\n "--diffs-light-addition-color": "oklch(0.54 0.13 158)",\n "--diffs-dark-addition-color": "oklch(0.72 0.13 158)",\n "--diffs-light-deletion-color": "oklch(0.55 0.16 28)",\n "--diffs-dark-deletion-color": "oklch(0.72 0.14 28)",\n "--diffs-bg-addition-override":\n "light-dark(oklch(0.957 0.032 158), oklch(0.255 0.052 158))",\n "--diffs-bg-addition-emphasis-override":\n "light-dark(oklch(0.88 0.06 158), oklch(0.36 0.08 158))",\n "--diffs-bg-deletion-override":\n "light-dark(oklch(0.958 0.03 28), oklch(0.255 0.047 28))",\n "--diffs-bg-deletion-emphasis-override":\n "light-dark(oklch(0.9 0.052 28), oklch(0.36 0.075 28))",\n "--diffs-fg-number-override":\n "light-dark(oklch(0.56 0.018 247), oklch(0.66 0.012 247))",\n "--diffs-font-size": "12px",\n "--diffs-line-height": "20px",\n} as React.CSSProperties\n\nfunction useIsDarkTheme() {\n const [isDark, setIsDark] = React.useState(false)\n\n React.useEffect(() => {\n if (typeof document === "undefined") return\n\n const root = document.documentElement\n const updateTheme = () => setIsDark(root.classList.contains("dark"))\n\n updateTheme()\n\n if (typeof MutationObserver === "undefined") return\n\n const observer = new MutationObserver(updateTheme)\n observer.observe(root, { attributes: true, attributeFilter: ["class"] })\n\n return () => observer.disconnect()\n }, [])\n\n return isDark\n}\n\nfunction useHumanReviewGridTheme() {\n const isDark = useIsDarkTheme()\n\n return React.useMemo<Partial<Theme>>(\n () => ({\n accentColor: isDark ? "rgb(96, 165, 250)" : "rgb(37, 99, 235)",\n accentLight: isDark ? "rgba(29, 78, 216, 0.15)" : "rgb(219, 234, 254)",\n accentFg: "rgb(255, 255, 255)",\n textDark: isDark ? "rgb(229, 229, 229)" : "rgb(23, 23, 23)",\n textMedium: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n textLight: isDark ? "rgb(115, 115, 115)" : "rgb(163, 163, 163)",\n textBubble: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n textHeader: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n textGroupHeader: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n bgCell: isDark ? "rgb(10, 10, 10)" : "rgb(255, 255, 255)",\n bgCellMedium: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n bgHeader: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n bgHeaderHasFocus: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n bgHeaderHovered: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n borderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n horizontalBorderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n cellHorizontalPadding: 8,\n cellVerticalPadding: 3,\n headerIconSize: 18,\n baseFontStyle: "13px",\n headerFontStyle: "600 13px",\n markerFontStyle: "11px",\n fontFamily: \'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif\',\n editorFontSize: "13px",\n }),\n [isDark]\n )\n}\n\nconst REVIEW_FIELDS: ReviewField[] = [\n {\n key: "vendor_name",\n schema: {\n type: "string",\n title: "Vendor name",\n description: "Supplier shown on the invoice header.",\n },\n actual: "Acme Supplies LLC",\n expected: "Acme Supply LLC",\n location: {\n page: 1,\n area: { left: 31, top: 30, width: 40, height: 5.8 },\n },\n },\n {\n key: "total_amount",\n schema: {\n type: "number",\n title: "Total amount",\n description: "Final amount due including tax.",\n },\n actual: 12480,\n expected: 12480.75,\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "payment_terms",\n schema: {\n type: "string",\n title: "Payment terms",\n enum: ["Due on receipt", "Net 15", "Net 30"],\n },\n actual: "Net 15",\n expected: "Net 30",\n location: {\n page: 1,\n area: { left: 13.5, top: 55.5, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "line_items",\n schema: {\n type: "array",\n title: "Line items",\n description: "Invoice rows with nested allocation details.",\n items: {\n type: "object",\n properties: {\n description: {\n type: "string",\n title: "Description",\n },\n quantity: {\n type: "number",\n title: "Qty",\n },\n unit_price: {\n type: "number",\n title: "Unit price",\n },\n tax_detail: {\n type: "object",\n title: "Tax detail",\n properties: {\n code: {\n type: "string",\n title: "Code",\n },\n jurisdiction: {\n type: "string",\n title: "Jurisdiction",\n },\n },\n },\n allocations: {\n type: "array",\n title: "Allocations",\n items: {\n type: "object",\n properties: {\n department: {\n type: "string",\n title: "Department",\n },\n percent: {\n type: "number",\n title: "Percent",\n },\n },\n },\n },\n },\n },\n },\n actual: [\n {\n description: "Transformer implementation support",\n quantity: 2,\n unit_price: 4200,\n tax_detail: { code: "TX-CA", jurisdiction: "CA" },\n allocations: [\n { department: "Research", percent: 70 },\n { department: "Platform", percent: 20 },\n ],\n },\n {\n description: "Attention model review",\n quantity: 1,\n unit_price: 4080,\n tax_detail: { code: "TX-NY", jurisdiction: "NY" },\n allocations: [{ department: "Research", percent: 100 }],\n },\n ],\n expected: [\n {\n description: "Transformer implementation support",\n quantity: 2,\n unit_price: 4200,\n tax_detail: { code: "TX-CA", jurisdiction: "CA" },\n allocations: [\n { department: "Research", percent: 70 },\n { department: "Platform", percent: 30 },\n ],\n },\n {\n description: "Attention model review",\n quantity: 1,\n unit_price: 4080.75,\n tax_detail: { code: "TX-NY", jurisdiction: "NY" },\n allocations: [{ department: "Research", percent: 100 }],\n },\n ],\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "requires_review",\n schema: {\n type: "boolean",\n title: "Requires review",\n description: "Whether a human should verify this document before export.",\n },\n actual: false,\n expected: true,\n location: {\n page: 2,\n area: { left: 9.5, top: 12, width: 81, height: 11.5 },\n },\n },\n {\n key: "remittance",\n schema: {\n type: "object",\n title: "Remittance details",\n description: "Payment destination used for invoice reconciliation.",\n properties: {\n account_holder: {\n type: "string",\n title: "Account holder",\n },\n routing_number: {\n type: "string",\n title: "Routing number",\n },\n verified: {\n type: "boolean",\n title: "Verified",\n },\n },\n },\n actual: {\n account_holder: "Acme Supplies LLC",\n routing_number: "021000021",\n verified: false,\n },\n expected: {\n account_holder: "Acme Supply LLC",\n routing_number: "021000021",\n verified: true,\n },\n },\n]\n\nfunction valuesFromFields(\n fields: ReviewField[],\n valueKey: "actual" | "expected"\n) {\n return fields.reduce<JsonObject>((values, field) => {\n values[field.key] = field[valueKey]\n return values\n }, {})\n}\n\nfunction formatJson(value: unknown) {\n return JSON.stringify(value, null, 2)\n}\n\nfunction isJsonObject(value: JsonValue): value is JsonObject {\n return typeof value === "object" && value !== null && !Array.isArray(value)\n}\n\nfunction isJsonArray(value: JsonValue): value is JsonArray {\n return Array.isArray(value)\n}\n\nfunction getObjectValue(value: JsonValue, key: string): JsonValue {\n if (!isJsonObject(value)) return null\n return value[key] ?? null\n}\n\nfunction setObjectValue(\n value: JsonValue,\n key: string,\n childValue: JsonValue\n): JsonObject {\n return {\n ...(isJsonObject(value) ? value : {}),\n [key]: childValue,\n }\n}\n\nfunction getArrayValue(value: JsonValue): JsonArray {\n return isJsonArray(value) ? value : []\n}\n\nfunction setArrayItemValue(\n value: JsonValue,\n index: number,\n childValue: JsonValue\n): JsonArray {\n const nextValue = getArrayValue(value).slice()\n nextValue[index] = childValue\n return nextValue\n}\n\nfunction getPrimitiveValue(value: JsonValue): JsonPrimitive {\n return isJsonObject(value) || isJsonArray(value) ? null : value\n}\n\nfunction jsonValuesEqual(left: JsonValue, right: JsonValue) {\n return formatJson(left) === formatJson(right)\n}\n\nfunction countReviewFields(fields: ReviewField[]): number {\n return fields.reduce((count, field) => {\n if (field.schema.type !== "object") return count + 1\n\n const properties = field.schema.properties ?? {}\n const childFields = Object.entries(properties).map(\n ([key, schema]): ReviewField => ({\n key: `${field.key}.${key}`,\n schema,\n actual: getObjectValue(field.actual, key),\n expected: getObjectValue(field.expected, key),\n })\n )\n\n return count + Math.max(countReviewFields(childFields), 1)\n }, 0)\n}\n\nfunction findReviewField(\n fields: ReviewField[],\n fieldKey: string | undefined\n): ReviewField | undefined {\n if (!fieldKey) return undefined\n\n for (const field of fields) {\n if (field.key === fieldKey) return field\n\n if (field.schema.type === "object") {\n const childFields = Object.entries(field.schema.properties ?? {}).map(\n ([key, schema]): ReviewField => ({\n key: `${field.key}.${key}`,\n schema,\n actual: getObjectValue(field.actual, key),\n expected: getObjectValue(field.expected, key),\n })\n )\n const childField = findReviewField(childFields, fieldKey)\n if (childField) return childField\n }\n }\n\n return undefined\n}\n\nfunction formatValue(value: JsonValue) {\n if (value === null) return "NULL"\n if (isJsonObject(value) || isJsonArray(value)) return formatJson(value)\n if (typeof value === "boolean") return value ? "true" : "false"\n return String(value)\n}\n\nfunction getFieldIcon(type: SchemaPropertyType) {\n if (type === "number" || type === "integer") return InputNumericIcon\n if (type === "boolean") return TextCheckIcon\n if (type === "array") return SecondBracketIcon\n if (type === "object") return SourceCodeSquareIcon\n return InputTextIcon\n}\n\nfunction HumanReviewValueInput({\n readOnly = false,\n schema,\n value,\n onChange,\n}: {\n readOnly?: boolean\n schema: ReviewFieldSchema\n value: JsonPrimitive\n onChange: (value: JsonPrimitive) => void\n}) {\n if (schema.enum?.length) {\n return (\n <span className="relative inline-flex w-full rounded-lg border border-input bg-background text-sm text-foreground shadow-xs/5 dark:bg-input/32">\n <select\n disabled={readOnly}\n value={value === null ? "" : String(value)}\n onChange={(event) => onChange(event.target.value)}\n className="h-8.5 w-full appearance-none rounded-[inherit] bg-transparent px-3 text-sm outline-none sm:h-7.5"\n >\n {schema.enum.map((option) => (\n <option key={String(option)} value={String(option)}>\n {String(option)}\n </option>\n ))}\n </select>\n </span>\n )\n }\n\n if (schema.type === "number" || schema.type === "integer") {\n return (\n <Input\n nativeInput\n readOnly={readOnly}\n type="number"\n value={value === null ? "" : String(value)}\n onChange={(event) => {\n const nextValue = event.currentTarget.value\n onChange(nextValue === "" ? null : Number(nextValue))\n }}\n />\n )\n }\n\n if (schema.type === "boolean") {\n return (\n <div className="grid grid-cols-2 gap-1 rounded-lg bg-muted p-0.5">\n {[true, false].map((option) => (\n <Button\n key={String(option)}\n type="button"\n size="sm"\n variant={value === option ? "outline" : "ghost"}\n className={cn(\n "h-7 shadow-none",\n value === option && "bg-background dark:bg-input"\n )}\n disabled={readOnly}\n onClick={() => onChange(option)}\n >\n {option ? "True" : "False"}\n </Button>\n ))}\n </div>\n )\n }\n\n return (\n <Input\n nativeInput\n readOnly={readOnly}\n value={value === null ? "" : String(value)}\n onChange={(event) => onChange(event.currentTarget.value)}\n />\n )\n}\n\nfunction getArrayItemSchema(schema: ReviewFieldSchema): ReviewFieldSchema {\n return schema.items ?? { type: "string" }\n}\n\nfunction isComplexSchema(schema: ReviewFieldSchema) {\n return schema.type === "object" || schema.type === "array"\n}\n\nfunction summarizeComplexValue(value: JsonValue) {\n if (isJsonArray(value)) return `${value.length} items`\n if (isJsonObject(value)) return `${Object.keys(value).length} fields`\n return formatValue(value)\n}\n\nfunction getCellValueForArrayColumn(\n rowValue: JsonValue,\n itemSchema: ReviewFieldSchema,\n columnId: string\n) {\n if (itemSchema.type === "object") {\n return getObjectValue(rowValue, columnId)\n }\n\n return rowValue\n}\n\nfunction getCellSchemaForArrayColumn(\n itemSchema: ReviewFieldSchema,\n columnId: string\n) {\n if (itemSchema.type === "object") {\n return itemSchema.properties?.[columnId] ?? { type: "string" }\n }\n\n return itemSchema\n}\n\nfunction applyPrimitiveEdit(\n schema: ReviewFieldSchema,\n value: EditableGridCell\n): JsonValue | undefined {\n if (schema.type === "boolean" && value.kind === GridCellKind.Boolean) {\n return value.data\n }\n\n if (\n (schema.type === "number" || schema.type === "integer") &&\n value.kind === GridCellKind.Number\n ) {\n return value.data ?? null\n }\n\n if (value.kind === GridCellKind.Text) {\n if (schema.type === "number" || schema.type === "integer") {\n return value.data.trim() === "" ? null : Number(value.data)\n }\n\n return value.data\n }\n\n return undefined\n}\n\ntype ArrayNestedView = {\n rowIndex: number\n columnId: string\n title: string\n schema: ReviewFieldSchema\n value: JsonValue\n}\n\ntype ArrayReviewSide = "actual" | "expected"\n\ntype SyncedArrayNestedView = {\n activeSide: ArrayReviewSide | null\n stack: ArrayNestedView[]\n}\n\ntype SyncedArraySelection = {\n activeSide: ArrayReviewSide | null\n depth: number\n gridSelection: GridSelection\n}\n\nconst EMPTY_SYNCED_ARRAY_NESTED_VIEW: SyncedArrayNestedView = {\n activeSide: null,\n stack: [],\n}\n\nconst EMPTY_SYNCED_ARRAY_SELECTION: SyncedArraySelection = {\n activeSide: null,\n depth: 0,\n gridSelection: emptyGridSelection,\n}\n\nfunction setNestedArrayValue({\n value,\n schema,\n nestedStack,\n nextNestedValue,\n}: {\n value: JsonValue\n schema: ReviewFieldSchema\n nestedStack: ArrayNestedView[]\n nextNestedValue: JsonValue\n}): JsonValue {\n const [currentView, ...remainingViews] = nestedStack\n\n if (!currentView) return nextNestedValue\n\n const itemSchema = getArrayItemSchema(schema)\n const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n const cellSchema = getCellSchemaForArrayColumn(\n itemSchema,\n currentView.columnId\n )\n const currentCellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n currentView.columnId\n )\n const nextCellValue: JsonValue = remainingViews.length\n ? setNestedArrayValue({\n value: currentCellValue,\n schema: cellSchema,\n nestedStack: remainingViews,\n nextNestedValue,\n })\n : nextNestedValue\n const nextRowValue: JsonValue =\n itemSchema.type === "object"\n ? setObjectValue(rowValue, currentView.columnId, nextCellValue)\n : nextCellValue\n\n return setArrayItemValue(value, currentView.rowIndex, nextRowValue)\n}\n\nfunction getNestedArrayValue({\n value,\n schema,\n nestedStack,\n}: {\n value: JsonValue\n schema: ReviewFieldSchema\n nestedStack: ArrayNestedView[]\n}): JsonValue {\n const [currentView, ...remainingViews] = nestedStack\n\n if (!currentView) return value\n\n const itemSchema = getArrayItemSchema(schema)\n const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n const cellSchema = getCellSchemaForArrayColumn(\n itemSchema,\n currentView.columnId\n )\n const cellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n currentView.columnId\n )\n\n if (!remainingViews.length) return cellValue\n\n return getNestedArrayValue({\n value: cellValue,\n schema: cellSchema,\n nestedStack: remainingViews,\n })\n}\n\nfunction isCellInRange(col: number, row: number, range: Rectangle) {\n return (\n col >= range.x &&\n col < range.x + range.width &&\n row >= range.y &&\n row < range.y + range.height\n )\n}\n\nfunction getRangeEdges(col: number, row: number, range: Rectangle) {\n return {\n bottom: row === range.y + range.height - 1,\n left: col === range.x,\n right: col === range.x + range.width - 1,\n top: row === range.y,\n }\n}\n\nfunction HumanReviewArrayValueGrid({\n activeNestedSide = null,\n activeSelectionSide = null,\n label,\n nestedStackBaseDepth = 0,\n readOnly = false,\n schema,\n selectionDepth = 0,\n sharedGridSelection,\n sharedNestedStack,\n value,\n viewSide = "expected",\n onChange,\n onGridSelectionChange,\n onNestedStackChange,\n}: {\n activeNestedSide?: ArrayReviewSide | null\n activeSelectionSide?: ArrayReviewSide | null\n label: string\n nestedStackBaseDepth?: number\n readOnly?: boolean\n schema: ReviewFieldSchema\n selectionDepth?: number\n sharedGridSelection?: GridSelection\n sharedNestedStack?: ArrayNestedView[]\n value: JsonValue\n viewSide?: ArrayReviewSide\n onChange?: (value: JsonValue) => void\n onGridSelectionChange?: (\n selection: GridSelection,\n side: ArrayReviewSide,\n depth: number\n ) => void\n onNestedStackChange?: (\n stack: ArrayNestedView[],\n side: ArrayReviewSide\n ) => void\n}) {\n const rows = getArrayValue(value)\n const itemSchema = getArrayItemSchema(schema)\n const gridTheme = useHumanReviewGridTheme()\n const isDark = useIsDarkTheme()\n const [localNestedStack, setLocalNestedStack] = React.useState<\n ArrayNestedView[]\n >([])\n const [localGridSelection, setLocalGridSelection] =\n React.useState<GridSelection>(emptyGridSelection)\n const nestedStack = sharedNestedStack ?? localNestedStack\n const syncedGridSelection = sharedGridSelection ?? localGridSelection\n const gridSelection =\n sharedGridSelection &&\n (activeSelectionSide !== viewSide ||\n selectionDepth !== nestedStackBaseDepth)\n ? emptyGridSelection\n : syncedGridSelection\n const sharedSelectionRange = sharedGridSelection?.current?.range\n const sharedSelectionRangeStack = sharedGridSelection?.current?.rangeStack\n const mirroredSelectionRanges = React.useMemo<readonly Rectangle[]>(() => {\n if (\n !activeSelectionSide ||\n activeSelectionSide === viewSide ||\n selectionDepth !== nestedStackBaseDepth ||\n !sharedSelectionRange ||\n !sharedSelectionRangeStack\n ) {\n return []\n }\n\n return [...sharedSelectionRangeStack, sharedSelectionRange]\n }, [\n activeSelectionSide,\n nestedStackBaseDepth,\n selectionDepth,\n sharedSelectionRange,\n sharedSelectionRangeStack,\n viewSide,\n ])\n const visibleNestedStack = nestedStack.slice(nestedStackBaseDepth)\n const activeNestedView = visibleNestedStack[0] ?? null\n const activeNestedValue = activeNestedView\n ? getNestedArrayValue({\n value,\n schema,\n nestedStack: [activeNestedView],\n })\n : null\n const isActiveNestedSource =\n Boolean(activeNestedView) && activeNestedSide === viewSide\n const isMirroredNestedTarget =\n Boolean(activeNestedView) &&\n activeNestedSide !== null &&\n activeNestedSide !== viewSide\n const blueCellText = isDark ? "rgb(147, 197, 253)" : "rgb(37, 99, 235)"\n const selectedCellBackground = isDark\n ? "rgba(37, 99, 235, 0.2)"\n : "rgba(219, 234, 254, 0.85)"\n const mirroredCellBackground = isDark\n ? "rgba(167, 139, 250, 0.18)"\n : "rgba(237, 233, 254, 0.9)"\n const mirroredCellBorder = isDark ? "rgb(196, 181, 253)" : "rgb(124, 58, 237)"\n\n const setNestedStack = React.useCallback(\n (\n updater:\n | ArrayNestedView[]\n | ((current: ArrayNestedView[]) => ArrayNestedView[])\n ) => {\n if (onNestedStackChange) {\n const nextStack =\n typeof updater === "function" ? updater(nestedStack) : updater\n\n onNestedStackChange(nextStack, viewSide)\n return\n }\n\n setLocalNestedStack(updater)\n },\n [nestedStack, onNestedStackChange, viewSide]\n )\n\n const handleGridSelectionChange = React.useCallback(\n (selection: GridSelection) => {\n if (onGridSelectionChange) {\n onGridSelectionChange(selection, viewSide, nestedStackBaseDepth)\n return\n }\n\n setLocalGridSelection(selection)\n },\n [nestedStackBaseDepth, onGridSelectionChange, viewSide]\n )\n\n const columns = React.useMemo<GridColumn[]>(() => {\n if (itemSchema.type === "object") {\n const propertyEntries = Object.entries(itemSchema.properties ?? {})\n\n if (propertyEntries.length) {\n return propertyEntries.map(([key, propertySchema]) => ({\n id: key,\n title: propertySchema.title ?? key,\n width: isComplexSchema(propertySchema) ? 148 : 132,\n }))\n }\n }\n\n return [\n {\n id: "value",\n title: itemSchema.title ?? "Value",\n width: isComplexSchema(itemSchema) ? 148 : 180,\n },\n ]\n }, [itemSchema])\n\n const getCellContent = React.useCallback(\n ([col, row]: Item): GridCell => {\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n const cellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n columnId\n )\n const matchedNestedCell =\n activeNestedView?.rowIndex === row &&\n activeNestedView.columnId === columnId\n const matchesMirroredSelection = mirroredSelectionRanges.some((range) =>\n isCellInRange(col, row, range)\n )\n const nestedCellTheme: Partial<Theme> | undefined = matchedNestedCell\n ? {\n bgCell: isMirroredNestedTarget\n ? mirroredCellBackground\n : selectedCellBackground,\n textDark: blueCellText,\n }\n : undefined\n const selectionCellTheme: Partial<Theme> | undefined =\n matchesMirroredSelection\n ? {\n bgCell: mirroredCellBackground,\n textDark: isDark ? "rgb(233, 213, 255)" : "rgb(91, 33, 182)",\n }\n : undefined\n\n if (isComplexSchema(cellSchema)) {\n return {\n kind: GridCellKind.Text,\n data: summarizeComplexValue(cellValue),\n displayData: summarizeComplexValue(cellValue),\n allowOverlay: false,\n readonly: true,\n cursor: "pointer",\n activationBehaviorOverride: "double-click",\n themeOverride: {\n textDark: blueCellText,\n ...(selectionCellTheme ?? {}),\n ...(nestedCellTheme ?? {}),\n },\n }\n }\n\n if (cellSchema.type === "boolean") {\n return {\n kind: GridCellKind.Boolean,\n data: typeof cellValue === "boolean" ? cellValue : false,\n allowOverlay: false,\n readonly: readOnly,\n ...(selectionCellTheme ? { themeOverride: selectionCellTheme } : {}),\n }\n }\n\n if (cellSchema.type === "number" || cellSchema.type === "integer") {\n return {\n kind: GridCellKind.Number,\n data: typeof cellValue === "number" ? cellValue : undefined,\n displayData: typeof cellValue === "number" ? String(cellValue) : "",\n allowOverlay: !readOnly,\n readonly: readOnly,\n ...(selectionCellTheme ? { themeOverride: selectionCellTheme } : {}),\n }\n }\n\n return {\n kind: GridCellKind.Text,\n data:\n cellValue === null ||\n isJsonObject(cellValue) ||\n isJsonArray(cellValue)\n ? ""\n : String(cellValue),\n displayData:\n cellValue === null ||\n isJsonObject(cellValue) ||\n isJsonArray(cellValue)\n ? ""\n : String(cellValue),\n allowOverlay: !readOnly,\n readonly: readOnly,\n ...(selectionCellTheme ? { themeOverride: selectionCellTheme } : {}),\n }\n },\n [\n activeNestedView,\n blueCellText,\n columns,\n isMirroredNestedTarget,\n isDark,\n itemSchema,\n mirroredCellBackground,\n mirroredSelectionRanges,\n readOnly,\n rows,\n selectedCellBackground,\n ]\n )\n\n const updateCellValue = React.useCallback(\n ([col, row]: Item, nextCell: EditableGridCell) => {\n if (readOnly || !onChange) return\n\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n const nextValue = applyPrimitiveEdit(cellSchema, nextCell)\n\n if (nextValue === undefined) return\n\n const nextRowValue =\n itemSchema.type === "object"\n ? setObjectValue(rowValue, columnId, nextValue)\n : nextValue\n\n onChange(setArrayItemValue(value, row, nextRowValue))\n },\n [columns, itemSchema, onChange, readOnly, rows, value]\n )\n\n const drawCell = React.useCallback<DrawCellCallback>(\n (args, drawContent) => {\n drawContent()\n\n const selectionRange = mirroredSelectionRanges.find((range) =>\n isCellInRange(args.col, args.row, range)\n )\n\n if (!selectionRange) {\n return\n }\n\n const { ctx, rect } = args\n const edges = getRangeEdges(args.col, args.row, selectionRange)\n\n ctx.save()\n ctx.strokeStyle = mirroredCellBorder\n ctx.lineWidth = 1.5\n ctx.setLineDash([4, 3])\n\n if (edges.top) {\n ctx.beginPath()\n ctx.moveTo(rect.x + 1.5, rect.y + 1.5)\n ctx.lineTo(rect.x + rect.width - 1.5, rect.y + 1.5)\n ctx.stroke()\n }\n\n if (edges.right) {\n ctx.beginPath()\n ctx.moveTo(rect.x + rect.width - 1.5, rect.y + 1.5)\n ctx.lineTo(rect.x + rect.width - 1.5, rect.y + rect.height - 1.5)\n ctx.stroke()\n }\n\n if (edges.bottom) {\n ctx.beginPath()\n ctx.moveTo(rect.x + 1.5, rect.y + rect.height - 1.5)\n ctx.lineTo(rect.x + rect.width - 1.5, rect.y + rect.height - 1.5)\n ctx.stroke()\n }\n\n if (edges.left) {\n ctx.beginPath()\n ctx.moveTo(rect.x + 1.5, rect.y + 1.5)\n ctx.lineTo(rect.x + 1.5, rect.y + rect.height - 1.5)\n ctx.stroke()\n }\n\n ctx.restore()\n },\n [mirroredCellBorder, mirroredSelectionRanges]\n )\n\n const openNestedCell = React.useCallback(\n ([col, row]: Item) => {\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n\n if (!isComplexSchema(cellSchema)) return\n\n setNestedStack((current) => {\n const nextView = {\n rowIndex: row,\n columnId,\n title: `${column?.title ?? columnId} / row ${row + 1}`,\n schema: cellSchema,\n value: getCellValueForArrayColumn(rowValue, itemSchema, columnId),\n }\n const currentView = current[nestedStackBaseDepth]\n\n if (\n currentView?.rowIndex === nextView.rowIndex &&\n currentView.columnId === nextView.columnId\n ) {\n return current\n }\n\n return [...current.slice(0, nestedStackBaseDepth), nextView]\n })\n },\n [columns, itemSchema, nestedStackBaseDepth, rows, setNestedStack]\n )\n\n const updateNestedValue = React.useCallback(\n (nextNestedValue: JsonValue) => {\n if (!activeNestedView || readOnly || !onChange) return\n\n onChange(\n setNestedArrayValue({\n value,\n schema,\n nestedStack: visibleNestedStack.slice(0, 1),\n nextNestedValue,\n })\n )\n setNestedStack((current) =>\n current.map((view, index) =>\n index === nestedStackBaseDepth\n ? { ...view, value: nextNestedValue }\n : view\n )\n )\n },\n [\n activeNestedView,\n nestedStackBaseDepth,\n onChange,\n readOnly,\n schema,\n setNestedStack,\n value,\n visibleNestedStack,\n ]\n )\n\n return (\n <div\n className={cn(\n "relative overflow-hidden rounded-md border bg-background transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:shadow-[0_0_0_1px_rgb(59_130_246_/_8%)] hover:border-blue-500/50",\n isActiveNestedSource &&\n "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_10%)]"\n )}\n >\n <div>\n <div className="flex h-8 items-center justify-between gap-2 border-b px-2 text-[11px] font-medium text-muted-foreground">\n <span>{label}</span>\n <span>{rows.length} rows</span>\n </div>\n <div className="h-[220px]">\n <DataEditor\n columns={columns}\n rows={rows.length}\n getCellContent={getCellContent}\n cellActivationBehavior="double-click"\n drawCell={drawCell}\n gridSelection={gridSelection}\n onCellEdited={updateCellValue}\n onCellActivated={openNestedCell}\n onGridSelectionChange={handleGridSelectionChange}\n rowMarkers="number"\n smoothScrollX\n smoothScrollY\n theme={gridTheme}\n width="100%"\n height="100%"\n rowHeight={32}\n headerHeight={34}\n />\n </div>\n </div>\n {activeNestedView ? (\n <div className="absolute inset-0 z-10 flex flex-col bg-background">\n <div className="flex h-8 items-center gap-2 border-b px-2">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="size-6 text-muted-foreground"\n onClick={() =>\n setNestedStack((current) =>\n current.slice(\n 0,\n Math.max(nestedStackBaseDepth, current.length - 1)\n )\n )\n }\n aria-label="Back to parent array"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />\n </Button>\n <div className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">\n {activeNestedView.title}\n </div>\n </div>\n <div className="min-h-0 flex-1 overflow-auto p-2">\n {activeNestedView.schema.type === "array" ? (\n <HumanReviewArrayValueGrid\n label={\n activeNestedView.schema.title ?? activeNestedView.columnId\n }\n nestedStackBaseDepth={nestedStackBaseDepth + 1}\n readOnly={readOnly}\n schema={activeNestedView.schema}\n sharedGridSelection={sharedGridSelection}\n sharedNestedStack={sharedNestedStack}\n value={activeNestedValue}\n viewSide={viewSide}\n activeNestedSide={activeNestedSide}\n activeSelectionSide={activeSelectionSide}\n selectionDepth={selectionDepth}\n onChange={updateNestedValue}\n onGridSelectionChange={onGridSelectionChange}\n onNestedStackChange={onNestedStackChange}\n />\n ) : (\n <HumanReviewObjectValueEditor\n schema={activeNestedView.schema}\n value={activeNestedValue}\n originalValue={activeNestedValue}\n readOnly={readOnly}\n onChange={updateNestedValue}\n />\n )}\n </div>\n </div>\n ) : null}\n </div>\n )\n}\n\nfunction HumanReviewObjectValueEditor({\n schema,\n value,\n originalValue,\n readOnly = false,\n onChange,\n}: {\n schema: ReviewFieldSchema\n value: JsonValue\n originalValue: JsonValue\n readOnly?: boolean\n onChange: (value: JsonValue) => void\n}) {\n const propertyEntries = Object.entries(schema.properties ?? {})\n\n if (!propertyEntries.length) {\n return (\n <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n No properties\n </div>\n )\n }\n\n return (\n <div className="space-y-2">\n {propertyEntries.map(([propertyKey, propertySchema]) => (\n <HumanReviewFieldCard\n key={propertyKey}\n field={{\n key: propertyKey,\n schema: propertySchema,\n actual: getObjectValue(originalValue, propertyKey),\n expected: getObjectValue(originalValue, propertyKey),\n }}\n value={getObjectValue(value, propertyKey)}\n originalValue={getObjectValue(originalValue, propertyKey)}\n readOnly={readOnly}\n onChange={(childValue) =>\n !readOnly &&\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onUndo={() =>\n !readOnly &&\n onChange(\n setObjectValue(\n value,\n propertyKey,\n getObjectValue(originalValue, propertyKey)\n )\n )\n }\n onSetNull={() =>\n !readOnly && onChange(setObjectValue(value, propertyKey, null))\n }\n />\n ))}\n </div>\n )\n}\n\ntype HumanReviewFieldCardProps = {\n field: ReviewField\n value: JsonValue\n originalValue: JsonValue\n active?: boolean\n activeFieldKey?: string\n readOnly?: boolean\n onChange: (value: JsonValue) => void\n onFieldFocus?: (field: ReviewField) => void\n onUndo: () => void\n onSetNull: () => void\n}\n\nfunction areHumanReviewFieldCardPropsEqual(\n previous: HumanReviewFieldCardProps,\n next: HumanReviewFieldCardProps\n) {\n return (\n previous.field === next.field &&\n Object.is(previous.value, next.value) &&\n Object.is(previous.originalValue, next.originalValue) &&\n previous.active === next.active &&\n previous.activeFieldKey === next.activeFieldKey &&\n previous.readOnly === next.readOnly &&\n previous.onFieldFocus === next.onFieldFocus\n )\n}\n\nconst HumanReviewFieldCard = React.memo(\n HumanReviewFieldCardBase,\n areHumanReviewFieldCardPropsEqual\n)\n\nfunction HumanReviewFieldCardBase({\n field,\n value,\n originalValue,\n active,\n activeFieldKey,\n readOnly = false,\n onChange,\n onFieldFocus,\n onUndo,\n onSetNull,\n}: HumanReviewFieldCardProps) {\n const modified = !jsonValuesEqual(value, originalValue)\n const Icon = getFieldIcon(field.schema.type)\n const propertyEntries = Object.entries(field.schema.properties ?? {})\n const [syncedArrayNestedView, setSyncedArrayNestedView] =\n React.useState<SyncedArrayNestedView>(EMPTY_SYNCED_ARRAY_NESTED_VIEW)\n const [syncedArraySelection, setSyncedArraySelection] =\n React.useState<SyncedArraySelection>(EMPTY_SYNCED_ARRAY_SELECTION)\n const updateSyncedArrayNestedView = React.useCallback(\n (stack: ArrayNestedView[], side: ArrayReviewSide) => {\n setSyncedArrayNestedView({\n activeSide: stack.length ? side : null,\n stack,\n })\n },\n []\n )\n const updateSyncedArraySelection = React.useCallback(\n (gridSelection: GridSelection, side: ArrayReviewSide, depth: number) => {\n setSyncedArraySelection({\n activeSide: gridSelection.current ? side : null,\n depth,\n gridSelection,\n })\n },\n []\n )\n\n return (\n <div\n tabIndex={0}\n onFocusCapture={() => onFieldFocus?.(field)}\n onMouseEnter={() => onFieldFocus?.(field)}\n className={cn(\n "rounded-lg border bg-background p-3 transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:bg-blue-500/5 hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",\n active &&\n "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_8%)]"\n )}\n >\n <div className="mb-3 flex min-h-8 items-start justify-between gap-3">\n <div className="min-w-0">\n <div className="flex min-w-0 items-center gap-2">\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">\n {field.schema.title ?? field.key}\n </div>\n </div>\n <span\n className={cn(\n "size-2 shrink-0 rounded-full bg-amber-400 transition-opacity",\n !modified && "opacity-0"\n )}\n />\n </div>\n <div className="truncate text-xs text-muted-foreground">\n {field.key}\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-1">\n {!readOnly && modified ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="text-muted-foreground"\n onClick={onUndo}\n aria-label={`Undo ${field.key}`}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Revert changes</TooltipContent>\n </Tooltip>\n ) : null}\n {!readOnly ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="text-muted-foreground"\n onClick={onSetNull}\n aria-label={`Set ${field.key} to null`}\n >\n <HugeiconsIcon icon={CancelCircleIcon} className="size-4" />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Set to NULL</TooltipContent>\n </Tooltip>\n ) : null}\n <div className="flex h-6 items-center gap-1 rounded-md border bg-muted/50 px-1.5 text-xs text-muted-foreground">\n <HugeiconsIcon icon={Icon} className="size-3.5" />\n {field.schema.type}\n </div>\n </div>\n </div>\n {field.schema.type === "object" ? (\n <div className="rounded-md border bg-muted/25 p-2">\n <div className="mb-2 flex items-center justify-between gap-3 text-[11px] font-medium text-muted-foreground">\n <span>Properties</span>\n <span>{propertyEntries.length} fields</span>\n </div>\n <div className="space-y-2">\n {propertyEntries.length ? (\n propertyEntries.map(([propertyKey, schema]) => {\n const childField: ReviewField = {\n key: `${field.key}.${propertyKey}`,\n schema,\n actual: getObjectValue(field.actual, propertyKey),\n expected: getObjectValue(originalValue, propertyKey),\n }\n\n return (\n <HumanReviewFieldCard\n key={childField.key}\n field={childField}\n value={getObjectValue(value, propertyKey)}\n originalValue={childField.expected}\n active={childField.key === activeFieldKey}\n activeFieldKey={activeFieldKey}\n readOnly={readOnly}\n onChange={(childValue) =>\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onFieldFocus={onFieldFocus}\n onUndo={() =>\n onChange(\n setObjectValue(value, propertyKey, childField.expected)\n )\n }\n onSetNull={() =>\n onChange(setObjectValue(value, propertyKey, null))\n }\n />\n )\n })\n ) : (\n <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n No properties\n </div>\n )}\n </div>\n </div>\n ) : field.schema.type === "array" ? (\n <div className="grid gap-2">\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Actual"\n readOnly\n schema={field.schema}\n selectionDepth={syncedArraySelection.depth}\n sharedGridSelection={syncedArraySelection.gridSelection}\n sharedNestedStack={syncedArrayNestedView.stack}\n value={field.actual}\n viewSide="actual"\n onGridSelectionChange={updateSyncedArraySelection}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Expected"\n readOnly={readOnly}\n schema={field.schema}\n selectionDepth={syncedArraySelection.depth}\n sharedGridSelection={syncedArraySelection.gridSelection}\n sharedNestedStack={syncedArrayNestedView.stack}\n value={value}\n viewSide="expected"\n onChange={onChange}\n onGridSelectionChange={updateSyncedArraySelection}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n </div>\n ) : (\n <div className="grid gap-2 sm:grid-cols-2">\n <div className="rounded-md border bg-muted/30 p-2">\n {field.schema.description ? (\n <p className="mb-2 text-xs text-muted-foreground">\n {field.schema.description}\n </p>\n ) : null}\n <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n Actual\n </div>\n <div className="min-h-7 rounded-md bg-background px-2 py-1.5 text-sm">\n {formatValue(field.actual)}\n </div>\n </div>\n <div className="rounded-md border bg-muted/30 p-2">\n <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n Expected\n </div>\n <HumanReviewValueInput\n readOnly={readOnly}\n schema={field.schema}\n value={getPrimitiveValue(value)}\n onChange={onChange}\n />\n </div>\n </div>\n )}\n </div>\n )\n}\n\nfunction HumanReviewHighlight({ field }: { field: ReviewField }) {\n const area = field.location?.area\n\n if (!area) return null\n\n return (\n <div\n className={cn(\n "pointer-events-none absolute z-10 rounded-[3px] border",\n REVIEW_HIGHLIGHT_STYLE\n )}\n style={{\n left: `${area.left}%`,\n top: `${area.top}%`,\n width: `${area.width}%`,\n height: `${area.height}%`,\n }}\n />\n )\n}\n\nexport function JsonDiffView({\n actual,\n expected,\n}: {\n actual: JsonObject\n expected: JsonObject\n}) {\n return (\n <Virtualizer\n className="h-full overflow-auto rounded-b-xl bg-surface/60"\n contentClassName="min-w-full"\n >\n <div className="human-review-diff h-full text-xs">\n <MultiFileDiff\n className="block min-w-full"\n style={DIFF_VIEWER_THEME}\n oldFile={{\n name: "actual.json",\n contents: formatJson(actual),\n lang: "json",\n }}\n newFile={{\n name: "expected.json",\n contents: formatJson(expected),\n lang: "json",\n }}\n disableWorkerPool\n options={{\n diffStyle: "split",\n diffIndicators: "bars",\n hunkSeparators: "line-info-basic",\n overflow: "wrap",\n theme: {\n light: "pierre-light",\n dark: "pierre-dark",\n },\n }}\n />\n </div>\n </Virtualizer>\n )\n}\n\nexport function HumanReviewPanel({\n fields = REVIEW_FIELDS,\n activeFieldKey,\n className,\n onFieldFocus,\n}: {\n fields?: ReviewField[]\n activeFieldKey?: string\n className?: string\n onFieldFocus?: (field: ReviewField) => void\n} = {}) {\n const [activeTab, setActiveTab] = React.useState("form")\n const actualValues = React.useMemo(\n () => valuesFromFields(fields, "actual"),\n [fields]\n )\n const initialExpectedValues = React.useMemo(\n () => valuesFromFields(fields, "expected"),\n [fields]\n )\n const [expected, setExpected] = React.useState<JsonObject>(\n initialExpectedValues\n )\n\n React.useEffect(() => {\n setExpected(initialExpectedValues)\n }, [initialExpectedValues])\n\n const updateValue = React.useCallback((key: string, value: JsonValue) => {\n setExpected((current) =>\n Object.is(current[key], value) ? current : { ...current, [key]: value }\n )\n }, [])\n const fieldCount = React.useMemo(() => countReviewFields(fields), [fields])\n\n return (\n <TooltipProvider delay={200}>\n <Tabs\n value={activeTab}\n onValueChange={setActiveTab}\n className={cn("flex h-[560px] flex-col gap-0 bg-background", className)}\n >\n <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">\n <TabsList className="h-8 sm:h-7">\n <TabsTrigger value="form" className="h-7 sm:h-6">\n <HugeiconsIcon icon={TextCheckIcon} className="size-4" />\n Form\n </TabsTrigger>\n <TabsTrigger value="json" className="h-7 sm:h-6">\n <HugeiconsIcon icon={SourceCodeSquareIcon} className="size-4" />\n JSON\n </TabsTrigger>\n </TabsList>\n <div className="flex h-8 items-center gap-1 rounded-md border bg-muted/40 px-2 text-xs text-muted-foreground sm:h-7">\n <HugeiconsIcon icon={FileDiffIcon} className="size-3.5" />\n {fieldCount} fields\n </div>\n </div>\n <TabsContent value="form" className="min-h-0 flex-1">\n <ScrollArea className="h-full" scrollFade>\n <div className="space-y-3 p-3">\n {fields.map((field) => (\n <HumanReviewFieldCard\n key={field.key}\n field={field}\n value={expected[field.key] ?? null}\n originalValue={field.expected}\n active={\n field.key === activeFieldKey ||\n activeFieldKey?.startsWith(`${field.key}.`)\n }\n activeFieldKey={activeFieldKey}\n onChange={(value) => updateValue(field.key, value)}\n onFieldFocus={onFieldFocus}\n onUndo={() => updateValue(field.key, field.expected)}\n onSetNull={() => updateValue(field.key, null)}\n />\n ))}\n </div>\n </ScrollArea>\n </TabsContent>\n <TabsContent value="json" className="min-h-0 flex-1">\n {activeTab === "json" ? (\n <JsonDiffView actual={actualValues} expected={expected} />\n ) : null}\n </TabsContent>\n </Tabs>\n </TooltipProvider>\n )\n}\n\nexport function HumanReviewBlock({\n file,\n fields = REVIEW_FIELDS,\n className,\n}: {\n file?: string\n fields?: ReviewField[]\n className?: string\n}) {\n const [activeFieldKey, setActiveFieldKey] = React.useState(fields[0]?.key)\n const viewerRef = React.useRef<PDFViewerHandle>(null)\n const activeField = findReviewField(fields, activeFieldKey) ?? fields[0]\n\n React.useEffect(() => {\n if (activeFieldKey || !fields[0]) return\n setActiveFieldKey(fields[0].key)\n }, [activeFieldKey, fields])\n\n const focusField = React.useCallback((field: ReviewField) => {\n setActiveFieldKey(field.key)\n\n if (field.location) {\n viewerRef.current?.scrollToPageArea(\n field.location.page,\n field.location.area\n )\n }\n }, [])\n\n return (\n <PdfBlockResizableShell\n autoSaveId="pdf-block-human-review"\n className={className}\n rightDefaultSize={42}\n rightMaxSize={60}\n rightMinSize={30}\n left={\n <PDFViewer\n ref={viewerRef}\n file={file}\n defaultZoom={DEFAULT_ZOOM}\n renderPageOverlay={({ pageNumber }) =>\n activeField?.location?.page === pageNumber ? (\n <HumanReviewHighlight field={activeField} />\n ) : null\n }\n />\n }\n right={\n <aside className="min-h-0 bg-background">\n <HumanReviewPanel\n fields={fields}\n activeFieldKey={activeField?.key}\n className="h-full min-h-0"\n onFieldFocus={focusField}\n />\n </aside>\n }\n />\n )\n}\n'
export function HumanReviewSource() {
return <HighlightedCodeBlock code={humanReviewSourceCode} />
diff --git a/apps/v4/components/ocr-blocks-docs.tsx b/apps/v4/components/ocr-blocks-docs.tsx
index 5f8348e..f628571 100644
--- a/apps/v4/components/ocr-blocks-docs.tsx
+++ b/apps/v4/components/ocr-blocks-docs.tsx
@@ -113,7 +113,7 @@ const OCR_BLOCKS: OcrBlock[] = [
{
id: "title",
type: "heading",
- text: "**Attention Is All You Need**",
+ text: "# Attention Is All You Need",
page: 1,
confidence: 0.99,
polygon: [
@@ -262,40 +262,61 @@ function BlockOverlay({
function OcrBlockMarkdown({ text }: { text: string }) {
return (
- <ReactMarkdown
- components={{
- h2: ({ node: _node, ...props }) => (
- <div className="text-sm font-semibold text-foreground" {...props} />
- ),
- p: ({ node: _node, ...props }) => <p className="my-0" {...props} />,
- strong: ({ node: _node, ...props }) => (
- <strong className="font-semibold text-foreground" {...props} />
- ),
- em: ({ node: _node, ...props }) => (
- <em className="text-foreground" {...props} />
- ),
- ul: ({ node: _node, ...props }) => (
- <ul className="my-0 list-disc space-y-0.5 pl-4" {...props} />
- ),
- li: ({ node: _node, ...props }) => <li className="pl-0.5" {...props} />,
- table: ({ node: _node, ...props }) => (
- <div className="overflow-hidden rounded-md border bg-background">
- <table className="w-full border-collapse text-xs" {...props} />
- </div>
- ),
- th: ({ node: _node, ...props }) => (
- <th
- className="border-b bg-muted px-2 py-1 text-left font-medium"
- {...props}
- />
- ),
- td: ({ node: _node, ...props }) => (
- <td className="border-t px-2 py-1" {...props} />
- ),
- }}
- >
- {text}
- </ReactMarkdown>
+ <div className="space-y-1 text-sm leading-5 text-foreground/90">
+ <ReactMarkdown
+ components={{
+ h1: ({ node: _node, ...props }) => (
+ <h1
+ className="my-0 text-base leading-5 font-semibold text-foreground"
+ {...props}
+ />
+ ),
+ h2: ({ node: _node, ...props }) => (
+ <h2
+ className="my-0 text-[15px] leading-5 font-semibold text-foreground"
+ {...props}
+ />
+ ),
+ h3: ({ node: _node, ...props }) => (
+ <h3
+ className="my-0 text-sm leading-5 font-semibold text-foreground"
+ {...props}
+ />
+ ),
+ p: ({ node: _node, ...props }) => (
+ <p className="my-0 text-[13px] leading-5" {...props} />
+ ),
+ strong: ({ node: _node, ...props }) => (
+ <strong className="font-semibold text-foreground" {...props} />
+ ),
+ em: ({ node: _node, ...props }) => (
+ <em className="text-foreground" {...props} />
+ ),
+ ul: ({ node: _node, ...props }) => (
+ <ul className="my-0 list-disc space-y-0.5 pl-4" {...props} />
+ ),
+ li: ({ node: _node, ...props }) => (
+ <li className="pl-0.5 text-[13px] leading-5" {...props} />
+ ),
+ table: ({ node: _node, ...props }) => (
+ <div className="overflow-hidden rounded-md border bg-background">
+ <table className="w-full border-collapse text-xs" {...props} />
+ </div>
+ ),
+ th: ({ node: _node, ...props }) => (
+ <th
+ className="border-b bg-muted px-2 py-1 text-left font-medium"
+ {...props}
+ />
+ ),
+ td: ({ node: _node, ...props }) => (
+ <td className="border-t px-2 py-1" {...props} />
+ ),
+ }}
+ >
+ {text}
+ </ReactMarkdown>
+ </div>
)
}
@@ -496,7 +517,7 @@ function OcrBlocksExample() {
kind="Heading"
pageLabel="p. 1"
confidence={0.99}
- text="**Attention Is All You Need**"
+ text="# Attention Is All You Need"
iconClassName="bg-violet-500/10 text-violet-600 dark:text-violet-300"
activeClassName="border-violet-500/60 bg-violet-500/5"
/>
@@ -588,7 +609,7 @@ export function OcrBlocksExample() {
kind="Heading"
pageLabel="p. 1"
confidence={0.99}
- text="**Attention Is All You Need**"
+ text="# Attention Is All You Need"
iconClassName="bg-violet-500/10 text-violet-600 dark:text-violet-300"
activeClassName="border-violet-500/60 bg-violet-500/5"
/>
@@ -633,34 +654,61 @@ type OcrBlockCardProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
function OcrBlockMarkdown({ text }: { text: string }) {
return (
- <ReactMarkdown
- components={{
- p: ({ node: _node, ...props }) => <p className="my-0" {...props} />,
- strong: ({ node: _node, ...props }) => (
- <strong className="font-semibold text-foreground" {...props} />
- ),
- ul: ({ node: _node, ...props }) => (
- <ul className="my-0 list-disc space-y-0.5 pl-4" {...props} />
- ),
- li: ({ node: _node, ...props }) => <li className="pl-0.5" {...props} />,
- table: ({ node: _node, ...props }) => (
- <div className="overflow-hidden rounded-md border bg-background">
- <table className="w-full border-collapse text-xs" {...props} />
- </div>
- ),
- th: ({ node: _node, ...props }) => (
- <th
- className="border-b bg-muted px-2 py-1 text-left font-medium"
- {...props}
- />
- ),
- td: ({ node: _node, ...props }) => (
- <td className="border-t px-2 py-1" {...props} />
- ),
- }}
- >
- {text}
- </ReactMarkdown>
+ <div className="space-y-1 text-sm leading-5 text-foreground/90">
+ <ReactMarkdown
+ components={{
+ h1: ({ node: _node, ...props }) => (
+ <h1
+ className="my-0 text-base leading-5 font-semibold text-foreground"
+ {...props}
+ />
+ ),
+ h2: ({ node: _node, ...props }) => (
+ <h2
+ className="my-0 text-[15px] leading-5 font-semibold text-foreground"
+ {...props}
+ />
+ ),
+ h3: ({ node: _node, ...props }) => (
+ <h3
+ className="my-0 text-sm leading-5 font-semibold text-foreground"
+ {...props}
+ />
+ ),
+ p: ({ node: _node, ...props }) => (
+ <p className="my-0 text-[13px] leading-5" {...props} />
+ ),
+ strong: ({ node: _node, ...props }) => (
+ <strong className="font-semibold text-foreground" {...props} />
+ ),
+ em: ({ node: _node, ...props }) => (
+ <em className="text-foreground" {...props} />
+ ),
+ ul: ({ node: _node, ...props }) => (
+ <ul className="my-0 list-disc space-y-0.5 pl-4" {...props} />
+ ),
+ li: ({ node: _node, ...props }) => (
+ <li className="pl-0.5 text-[13px] leading-5" {...props} />
+ ),
+ table: ({ node: _node, ...props }) => (
+ <div className="overflow-hidden rounded-md border bg-background">
+ <table className="w-full border-collapse text-xs" {...props} />
+ </div>
+ ),
+ th: ({ node: _node, ...props }) => (
+ <th
+ className="border-b bg-muted px-2 py-1 text-left font-medium"
+ {...props}
+ />
+ ),
+ td: ({ node: _node, ...props }) => (
+ <td className="border-t px-2 py-1" {...props} />
+ ),
+ }}
+ >
+ {text}
+ </ReactMarkdown>
+ </div>
);
}
diff --git a/apps/v4/components/pdf-viewer-blocks.tsx b/apps/v4/components/pdf-viewer-blocks.tsx
index 63241fa..89962f1 100644
--- a/apps/v4/components/pdf-viewer-blocks.tsx
+++ b/apps/v4/components/pdf-viewer-blocks.tsx
@@ -28,7 +28,6 @@ import {
ResizablePanelGroup,
} from "@/components/ui/resizable"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
-import { CitationsBlock } from "@/components/citations-docs"
import { copyToClipboardWithMeta } from "@/components/copy-button"
import {
DocumentSplitsBlock,
@@ -140,15 +139,6 @@ const pdfViewerBlocks = [
docsHref: "/docs/components/file-upload",
component: PdfDropzoneBlock,
},
- {
- id: "citations",
- title: "Citations",
- description:
- "Evidence cards that scroll the PDF viewer to source bounding boxes.",
- command: getRegistryAddCommand("citations"),
- docsHref: "/docs/components/citations",
- component: CitationsBlock,
- },
{
id: "ocr-blocks",
title: "OCR Blocks",
diff --git a/apps/v4/components/ui/csv-viewer.tsx b/apps/v4/components/ui/csv-viewer.tsx
index 8f8b364..1608912 100644
--- a/apps/v4/components/ui/csv-viewer.tsx
+++ b/apps/v4/components/ui/csv-viewer.tsx
@@ -158,9 +158,40 @@ function ToolbarTooltip({
)
}
+function readIsDarkTheme() {
+ return (
+ typeof document !== "undefined" &&
+ document.documentElement.classList.contains("dark")
+ )
+}
+
+function useIsDarkTheme() {
+ const [isDark, setIsDark] = React.useState(readIsDarkTheme)
+
+ React.useEffect(() => {
+ if (typeof document === "undefined") return
+
+ const updateTheme = () => setIsDark(readIsDarkTheme())
+
+ updateTheme()
+
+ if (typeof MutationObserver === "undefined") return
+
+ const observer = new MutationObserver(updateTheme)
+ observer.observe(document.documentElement, {
+ attributes: true,
+ attributeFilter: ["class"],
+ })
+
+ return () => observer.disconnect()
+ }, [])
+
+ return isDark
+}
+
export function CsvViewer({ className, data }: CsvViewerProps) {
const inputRef = React.useRef<HTMLInputElement | null>(null)
- const isDark = false
+ const isDark = useIsDarkTheme()
const [glide, setGlide] = React.useState<GlideDataGridModule | null>(null)
const [zoom, setZoom] = React.useState<(typeof ZOOM_OPTIONS)[number]>(1)
const [parsed, setParsed] = React.useState(() =>
diff --git a/apps/v4/components/ui/docx-editor.tsx b/apps/v4/components/ui/docx-editor.tsx
index bf3fcdc..399c14d 100644
--- a/apps/v4/components/ui/docx-editor.tsx
+++ b/apps/v4/components/ui/docx-editor.tsx
@@ -74,7 +74,6 @@ import {
} from "@/components/ui/document-viewer-sidebar"
import { FileThumbnail } from "@/components/ui/file-thumbnail"
import { Input } from "@/components/ui/input"
-import { ScrollArea } from "@/components/ui/scroll-area"
import {
Select,
SelectContent,
@@ -1891,7 +1890,7 @@ function DocxEditorContent({
inline={sidebarInline}
open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}
>
- <ScrollArea className="h-full" scrollFade>
+ <div className="h-full overflow-auto">
<div className="p-4">
{isLoadingDocument ? (
<>
@@ -1937,7 +1936,7 @@ function DocxEditorContent({
</div>
)}
</div>
- </ScrollArea>
+ </div>
</DocumentViewerThumbnailSidebar>
<div
ref={viewportRef}
diff --git a/apps/v4/components/ui/docx-viewer.tsx b/apps/v4/components/ui/docx-viewer.tsx
index 95c0479..f8fa01b 100644
--- a/apps/v4/components/ui/docx-viewer.tsx
+++ b/apps/v4/components/ui/docx-viewer.tsx
@@ -26,7 +26,6 @@ import {
useInlineThumbnailSidebar,
} from "@/components/ui/document-viewer-sidebar"
import { FileThumbnail } from "@/components/ui/file-thumbnail"
-import { ScrollArea } from "@/components/ui/scroll-area"
import {
Select,
SelectContent,
@@ -777,7 +776,7 @@ function DocxViewerContent({
inline={sidebarInline}
open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}
>
- <ScrollArea className="h-full" scrollFade>
+ <div className="h-full overflow-auto">
<div className="p-4">
{isLoadingDocument ? (
<>
@@ -823,7 +822,7 @@ function DocxViewerContent({
</div>
)}
</div>
- </ScrollArea>
+ </div>
</DocumentViewerThumbnailSidebar>
<div
ref={viewportRef}
diff --git a/apps/v4/components/ui/file-thumbnail.tsx b/apps/v4/components/ui/file-thumbnail.tsx
index 222c0bd..12b64ea 100644
--- a/apps/v4/components/ui/file-thumbnail.tsx
+++ b/apps/v4/components/ui/file-thumbnail.tsx
@@ -906,13 +906,17 @@ function XlsxThumbnailGeneratorContent({
thumbnailWidth: number
}) {
const controller = useXlsxViewer()
- const { thumbnails } = useXlsxViewerThumbnails({
- includeHeaders: true,
- resolution: {
- maxHeight: thumbnailWidth,
- maxWidth: thumbnailWidth,
- },
- })
+ const thumbnailOptions = React.useMemo(
+ () => ({
+ includeHeaders: true,
+ resolution: {
+ maxHeight: thumbnailWidth,
+ maxWidth: thumbnailWidth,
+ },
+ }),
+ [thumbnailWidth]
+ )
+ const { thumbnails } = useXlsxViewerThumbnails(thumbnailOptions)
const firstThumbnail = thumbnails[0]
React.useEffect(() => {
diff --git a/apps/v4/components/ui/xlsx-editor.tsx b/apps/v4/components/ui/xlsx-editor.tsx
index 1912255..4eb777c 100644
--- a/apps/v4/components/ui/xlsx-editor.tsx
+++ b/apps/v4/components/ui/xlsx-editor.tsx
@@ -30,7 +30,6 @@ import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Group, GroupText } from "@/components/ui/group"
import { Input } from "@/components/ui/input"
-import { ScrollArea } from "@/components/ui/scroll-area"
import {
Select,
SelectContent,
@@ -485,11 +484,7 @@ export function XlsxEditorSurface({
showNightRenderToggle={showNightRenderToggle}
/>
<div className="flex min-h-0 flex-1 flex-col">
- <ScrollArea
- orientation="both"
- className="min-h-0 flex-1 bg-muted/20"
- viewportClassName="min-h-0"
- >
+ <div className="min-h-0 flex-1 bg-muted/20">
<XlsxViewer
experimentalCanvas
allowResizeInReadOnly
@@ -519,7 +514,7 @@ export function XlsxEditorSurface({
}
renderTableHeaderMenu={renderTableHeaderMenu}
/>
- </ScrollArea>
+ </div>
<WorkbookSheetTabs workbookIdentity={workbookIdentity} />
</div>
</div>
diff --git a/apps/v4/components/ui/xlsx-viewer.tsx b/apps/v4/components/ui/xlsx-viewer.tsx
index e7e4b30..ce2eb67 100644
--- a/apps/v4/components/ui/xlsx-viewer.tsx
+++ b/apps/v4/components/ui/xlsx-viewer.tsx
@@ -55,6 +55,15 @@ const XLSX_LOADING_INDICATOR_DELAY_MS = 300
const XLSX_DROPDOWN_Z_INDEX_CLASS = "z-[100010]"
const ZOOM_OPTIONS = [10, 25, 50, 75, 100, 125, 150, 175, 200, 400] as const
+// Stable reference so the thumbnails memo isn't invalidated on every render
+// (e.g. by selection changes), which would recompute every sheet thumbnail.
+const XLSX_SHEET_TAB_THUMBNAIL_OPTIONS = {
+ resolution: {
+ maxHeight: 360,
+ maxWidth: 560,
+ },
+} as const
+
const xlsxWorkbookBufferCache = new Map<string, ArrayBuffer>()
const xlsxWorkbookBufferPromiseCache = new Map<string, Promise<ArrayBuffer>>()
@@ -375,18 +384,46 @@ function WorkbookToolbar({
)
}
+type WorkbookSheetTab = {
+ name: string
+ workbookSheetIndex: number
+}
+
+type WorkbookSheetTabsInnerProps = {
+ activeSheetIndex: number
+ onActiveSheetIndexChange: (index: number) => void
+ sheets: WorkbookSheetTab[]
+ workbookIdentity: string
+}
+
export function WorkbookSheetTabs({
workbookIdentity,
}: {
workbookIdentity: string
}) {
const { activeSheetIndex, setActiveSheetIndex, sheets } = useXlsxViewer()
- const { thumbnails } = useXlsxViewerThumbnails({
- resolution: {
- maxHeight: 360,
- maxWidth: 560,
- },
- })
+
+ const handleActiveSheetIndexChange = React.useCallback(
+ (index: number) => setActiveSheetIndex(index),
+ [setActiveSheetIndex]
+ )
+
+ return (
+ <WorkbookSheetTabsInner
+ activeSheetIndex={activeSheetIndex}
+ onActiveSheetIndexChange={handleActiveSheetIndexChange}
+ sheets={sheets}
+ workbookIdentity={workbookIdentity}
+ />
+ )
+}
+
+const WorkbookSheetTabsInner = React.memo(function WorkbookSheetTabsInner({
+ activeSheetIndex,
+ onActiveSheetIndexChange,
+ sheets,
+ workbookIdentity,
+}: WorkbookSheetTabsInnerProps) {
const [visiblePreviewIndex, setVisiblePreviewIndex] = React.useState<
number | null
>(null)
@@ -394,9 +431,6 @@ export function WorkbookSheetTabs({
left: 0,
top: 0,
})
- const [thumbnailUrls, setThumbnailUrls] = React.useState<
- Record<number, string>
- >({})
const scrollRef = React.useRef<HTMLDivElement | null>(null)
const itemRefs = React.useRef<Record<number, HTMLButtonElement | null>>({})
const openTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(
@@ -496,31 +530,8 @@ export function WorkbookSheetTabs({
clearCloseTimeout()
setVisiblePreviewIndex(null)
setPreviewPosition({ left: 0, top: 0 })
- setThumbnailUrls({})
}, [clearCloseTimeout, clearOpenTimeout, workbookIdentity])
- React.useEffect(() => {
- thumbnails.forEach((thumbnail) => {
- if (thumbnailUrls[thumbnail.sheetIndex]) return
-
- const canvas = document.createElement("canvas")
- canvas.width = thumbnail.width
- canvas.height = thumbnail.height
-
- if (!thumbnail.paint(canvas)) return
-
- const nextUrl = canvas.toDataURL("image/png")
- setThumbnailUrls((current) => {
- if (current[thumbnail.sheetIndex]) return current
-
- return {
- ...current,
- [thumbnail.sheetIndex]: nextUrl,
- }
- })
- })
- }, [thumbnailUrls, thumbnails])
-
React.useEffect(() => {
if (visiblePreviewIndex === null) return
@@ -541,8 +552,6 @@ export function WorkbookSheetTabs({
if (sheets.length <= 1) return null
- const previewUrl =
- visiblePreviewIndex === null ? null : thumbnailUrls[visiblePreviewIndex]
const previewSheet =
visiblePreviewIndex === null ? null : sheets[visiblePreviewIndex]
@@ -553,7 +562,7 @@ export function WorkbookSheetTabs({
>
<Tabs
value={String(activeSheetIndex)}
- onValueChange={(value) => setActiveSheetIndex(Number(value))}
+ onValueChange={(value) => onActiveSheetIndexChange(Number(value))}
className="gap-0"
>
<ScrollArea
@@ -582,15 +591,12 @@ export function WorkbookSheetTabs({
</div>
</ScrollArea>
</Tabs>
- {typeof document !== "undefined" && previewSheet
+ {typeof document !== "undefined" &&
+ previewSheet &&
+ visiblePreviewIndex !== null
? createPortal(
<div
- className={cn(
- "pointer-events-none fixed z-[2147483647] overflow-hidden rounded-lg border bg-background/95 shadow-xl backdrop-blur-md transition-[opacity,transform] duration-100",
- previewUrl
- ? "translate-y-0 opacity-100"
- : "translate-y-1 opacity-0"
- )}
+ className="pointer-events-none fixed z-[2147483647] translate-y-0 overflow-hidden rounded-lg border bg-background/95 opacity-100 shadow-xl backdrop-blur-md transition-[opacity,transform] duration-100"
style={{
left: previewPosition.left,
top: previewPosition.top,
@@ -598,18 +604,10 @@ export function WorkbookSheetTabs({
}}
>
<div className="relative aspect-[11/7] w-full overflow-hidden bg-muted/60">
- {previewUrl ? (
- <img
- src={previewUrl}
- alt={`${previewSheet.name} preview`}
- className="absolute inset-0 size-full object-cover object-left-top"
- draggable={false}
- />
- ) : (
- <div className="grid size-full place-items-center">
- <Spinner className="size-4 text-muted-foreground" />
- </div>
- )}
+ <WorkbookSheetTabPreview
+ key={`${workbookIdentity}-${visiblePreviewIndex}`}
+ sheetIndex={visiblePreviewIndex}
+ />
</div>
</div>,
document.body
@@ -617,6 +615,46 @@ export function WorkbookSheetTabs({
: null}
</div>
)
+})
+
+function WorkbookSheetTabPreview({ sheetIndex }: { sheetIndex: number }) {
+ const { thumbnails } = useXlsxViewerThumbnails(
+ XLSX_SHEET_TAB_THUMBNAIL_OPTIONS
+ )
+ const canvasRef = React.useRef<HTMLCanvasElement | null>(null)
+ const [isPainted, setIsPainted] = React.useState(false)
+ const thumbnail = thumbnails.find(
+ (candidate) => candidate.sheetIndex === sheetIndex
+ )
+
+ React.useEffect(() => {
+ setIsPainted(false)
+
+ if (!thumbnail || !canvasRef.current) return
+
+ canvasRef.current.width = thumbnail.width
+ canvasRef.current.height = thumbnail.height
+ setIsPainted(thumbnail.paint(canvasRef.current))
+ }, [thumbnail])
+
+ return (
+ <>
+ {thumbnail ? (
+ <canvas
+ ref={canvasRef}
+ className={cn(
+ "absolute inset-0 size-full object-cover object-left-top transition-opacity duration-100",
+ isPainted ? "opacity-100" : "opacity-0"
+ )}
+ />
+ ) : null}
+ {!isPainted ? (
+ <div className="absolute inset-0 grid place-items-center">
+ <Spinner className="size-4 text-muted-foreground" />
+ </div>
+ ) : null}
+ </>
+ )
}
export function XlsxWorkbookSurface({
@@ -661,11 +699,7 @@ export function XlsxWorkbookSurface({
workbookIdentity={workbookIdentity}
/>
<div className="flex min-h-0 flex-1 flex-col">
- <ScrollArea
- orientation="both"
- className="min-h-0 flex-1 bg-muted/20"
- viewportClassName="min-h-0"
- >
+ <div className="min-h-0 flex-1 bg-muted/20">
<XlsxViewer
experimentalCanvas
allowResizeInReadOnly
@@ -695,7 +729,7 @@ export function XlsxWorkbookSurface({
}
renderTableHeaderMenu={renderTableHeaderMenu}
/>
- </ScrollArea>
+ </div>
<WorkbookSheetTabs workbookIdentity={workbookIdentity} />
</div>
</div>
diff --git a/apps/v4/components/xlsx-editor-docs.tsx b/apps/v4/components/xlsx-editor-docs.tsx
index 0aea1d4..92b73fb 100644
--- a/apps/v4/components/xlsx-editor-docs.tsx
+++ b/apps/v4/components/xlsx-editor-docs.tsx
@@ -117,7 +117,6 @@ import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Group, GroupText } from "@/components/ui/group"
import { Input } from "@/components/ui/input"
-import { ScrollArea } from "@/components/ui/scroll-area"
import {
Select,
SelectContent,
@@ -456,6 +455,7 @@ function EditorToolbar({
value={currentZoom.toString()}
onValueChange={(value) => setZoomScale(Number(value))}
disabled={!hasWorkbook}
+ modal={false}
>
<SelectTrigger
size="sm"
@@ -469,6 +469,7 @@ function EditorToolbar({
</SelectTrigger>
<SelectContent
align="end"
+ alignItemWithTrigger={false}
className={XLSX_DROPDOWN_Z_INDEX_CLASS}
>
{ZOOM_OPTIONS.map((value) => (
@@ -570,11 +571,7 @@ export function XlsxEditorSurface({
showNightRenderToggle={showNightRenderToggle}
/>
<div className="flex min-h-0 flex-1 flex-col">
- <ScrollArea
- orientation="both"
- className="min-h-0 flex-1 bg-muted/20"
- viewportClassName="min-h-0"
- >
+ <div className="min-h-0 flex-1 bg-muted/20">
<XlsxViewer
experimentalCanvas
allowResizeInReadOnly
@@ -604,7 +601,7 @@ export function XlsxEditorSurface({
}
renderTableHeaderMenu={renderTableHeaderMenu}
/>
- </ScrollArea>
+ </div>
<WorkbookSheetTabs workbookIdentity={workbookIdentity} />
</div>
</div>
diff --git a/apps/v4/components/xlsx-viewer-docs.tsx b/apps/v4/components/xlsx-viewer-docs.tsx
index 7cf8d54..8a39f91 100644
--- a/apps/v4/components/xlsx-viewer-docs.tsx
+++ b/apps/v4/components/xlsx-viewer-docs.tsx
@@ -404,6 +404,7 @@ function WorkbookToolbar({
<Select
value={currentZoom.toString()}
onValueChange={(value) => setZoomScale(Number(value))}
+ modal={false}
>
<SelectTrigger
size="sm"
@@ -412,7 +413,11 @@ function WorkbookToolbar({
>
<SelectValue>{currentZoom}%</SelectValue>
</SelectTrigger>
- <SelectContent align="end" className={XLSX_DROPDOWN_Z_INDEX_CLASS}>
+ <SelectContent
+ align="end"
+ alignItemWithTrigger={false}
+ className={XLSX_DROPDOWN_Z_INDEX_CLASS}
+ >
{ZOOM_OPTIONS.map((value) => (
<SelectItem key={value} value={value.toString()}>
{value}%
@@ -457,18 +462,46 @@ function WorkbookToolbar({
)
}
+type WorkbookSheetTab = {
+ name: string
+ workbookSheetIndex: number
+}
+
+type WorkbookSheetTabsInnerProps = {
+ activeSheetIndex: number
+ onActiveSheetIndexChange: (index: number) => void
+ sheets: WorkbookSheetTab[]
+ workbookIdentity: string
+}
+
export function WorkbookSheetTabs({
workbookIdentity,
}: {
workbookIdentity: string
}) {
const { activeSheetIndex, setActiveSheetIndex, sheets } = useXlsxViewer()
- const { thumbnails } = useXlsxViewerThumbnails({
- resolution: {
- maxHeight: 360,
- maxWidth: 560,
- },
- })
+
+ const handleActiveSheetIndexChange = React.useCallback(
+ (index: number) => setActiveSheetIndex(index),
+ [setActiveSheetIndex]
+ )
+
+ return (
+ <WorkbookSheetTabsInner
+ activeSheetIndex={activeSheetIndex}
+ onActiveSheetIndexChange={handleActiveSheetIndexChange}
+ sheets={sheets}
+ workbookIdentity={workbookIdentity}
+ />
+ )
+}
+
+const WorkbookSheetTabsInner = React.memo(function WorkbookSheetTabsInner({
+ activeSheetIndex,
+ onActiveSheetIndexChange,
+ sheets,
+ workbookIdentity,
+}: WorkbookSheetTabsInnerProps) {
const [visiblePreviewIndex, setVisiblePreviewIndex] = React.useState<
number | null
>(null)
@@ -476,9 +509,6 @@ export function WorkbookSheetTabs({
left: 0,
top: 0,
})
- const [thumbnailUrls, setThumbnailUrls] = React.useState<
- Record<number, string>
- >({})
const scrollRef = React.useRef<HTMLDivElement | null>(null)
const itemRefs = React.useRef<Record<number, HTMLButtonElement | null>>({})
const openTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(
@@ -578,31 +608,8 @@ export function WorkbookSheetTabs({
clearCloseTimeout()
setVisiblePreviewIndex(null)
setPreviewPosition({ left: 0, top: 0 })
- setThumbnailUrls({})
}, [clearCloseTimeout, clearOpenTimeout, workbookIdentity])
- React.useEffect(() => {
- thumbnails.forEach((thumbnail) => {
- if (thumbnailUrls[thumbnail.sheetIndex]) return
-
- const canvas = document.createElement("canvas")
- canvas.width = thumbnail.width
- canvas.height = thumbnail.height
-
- if (!thumbnail.paint(canvas)) return
-
- const nextUrl = canvas.toDataURL("image/png")
- setThumbnailUrls((current) => {
- if (current[thumbnail.sheetIndex]) return current
-
- return {
- ...current,
- [thumbnail.sheetIndex]: nextUrl,
- }
- })
- })
- }, [thumbnailUrls, thumbnails])
-
React.useEffect(() => {
if (visiblePreviewIndex === null) return
@@ -623,8 +630,6 @@ export function WorkbookSheetTabs({
if (sheets.length <= 1) return null
- const previewUrl =
- visiblePreviewIndex === null ? null : thumbnailUrls[visiblePreviewIndex]
const previewSheet =
visiblePreviewIndex === null ? null : sheets[visiblePreviewIndex]
@@ -635,7 +640,7 @@ export function WorkbookSheetTabs({
>
<Tabs
value={String(activeSheetIndex)}
- onValueChange={(value) => setActiveSheetIndex(Number(value))}
+ onValueChange={(value) => onActiveSheetIndexChange(Number(value))}
className="gap-0"
>
<ScrollArea
@@ -664,15 +669,12 @@ export function WorkbookSheetTabs({
</div>
</ScrollArea>
</Tabs>
- {typeof document !== "undefined" && previewSheet
+ {typeof document !== "undefined" &&
+ previewSheet &&
+ visiblePreviewIndex !== null
? createPortal(
<div
- className={cn(
- "pointer-events-none fixed z-[2147483647] overflow-hidden rounded-lg border bg-background/95 shadow-xl backdrop-blur-md transition-[opacity,transform] duration-100",
- previewUrl
- ? "translate-y-0 opacity-100"
- : "translate-y-1 opacity-0"
- )}
+ className="pointer-events-none fixed z-[2147483647] translate-y-0 overflow-hidden rounded-lg border bg-background/95 opacity-100 shadow-xl backdrop-blur-md transition-[opacity,transform] duration-100"
style={{
left: previewPosition.left,
top: previewPosition.top,
@@ -680,18 +682,10 @@ export function WorkbookSheetTabs({
}}
>
<div className="relative aspect-[11/7] w-full overflow-hidden bg-muted/60">
- {previewUrl ? (
- <img
- src={previewUrl}
- alt={\`\${previewSheet.name} preview\`}
- className="absolute inset-0 size-full object-cover object-left-top"
- draggable={false}
- />
- ) : (
- <div className="grid size-full place-items-center">
- <Spinner className="size-4 text-muted-foreground" />
- </div>
- )}
+ <WorkbookSheetTabPreview
+ key={\`\${workbookIdentity}-\${visiblePreviewIndex}\`}
+ sheetIndex={visiblePreviewIndex}
+ />
</div>
</div>,
document.body
@@ -699,6 +693,46 @@ export function WorkbookSheetTabs({
: null}
</div>
)
+})
+
+function WorkbookSheetTabPreview({ sheetIndex }: { sheetIndex: number }) {
+ const { thumbnails } = useXlsxViewerThumbnails(
+ XLSX_SHEET_TAB_THUMBNAIL_OPTIONS
+ )
+ const canvasRef = React.useRef<HTMLCanvasElement | null>(null)
+ const [isPainted, setIsPainted] = React.useState(false)
+ const thumbnail = thumbnails.find(
+ (candidate) => candidate.sheetIndex === sheetIndex
+ )
+
+ React.useEffect(() => {
+ setIsPainted(false)
+
+ if (!thumbnail || !canvasRef.current) return
+
+ canvasRef.current.width = thumbnail.width
+ canvasRef.current.height = thumbnail.height
+ setIsPainted(thumbnail.paint(canvasRef.current))
+ }, [thumbnail])
+
+ return (
+ <>
+ {thumbnail ? (
+ <canvas
+ ref={canvasRef}
+ className={cn(
+ "absolute inset-0 size-full object-cover object-left-top transition-opacity duration-100",
+ isPainted ? "opacity-100" : "opacity-0"
+ )}
+ />
+ ) : null}
+ {!isPainted ? (
+ <div className="absolute inset-0 grid place-items-center">
+ <Spinner className="size-4 text-muted-foreground" />
+ </div>
+ ) : null}
+ </>
+ )
}
export function XlsxWorkbookSurface({
@@ -743,11 +777,7 @@ export function XlsxWorkbookSurface({
workbookIdentity={workbookIdentity}
/>
<div className="flex min-h-0 flex-1 flex-col">
- <ScrollArea
- orientation="both"
- className="min-h-0 flex-1 bg-muted/20"
- viewportClassName="min-h-0"
- >
+ <div className="min-h-0 flex-1 bg-muted/20">
<XlsxViewer
experimentalCanvas
allowResizeInReadOnly
@@ -777,7 +807,7 @@ export function XlsxWorkbookSurface({
}
renderTableHeaderMenu={renderTableHeaderMenu}
/>
- </ScrollArea>
+ </div>
<WorkbookSheetTabs workbookIdentity={workbookIdentity} />
</div>
</div>
diff --git a/apps/v4/content/docs/(root)/index.mdx b/apps/v4/content/docs/(root)/index.mdx
index 6d0c088..3c9e65b 100644
--- a/apps/v4/content/docs/(root)/index.mdx
+++ b/apps/v4/content/docs/(root)/index.mdx
@@ -11,7 +11,7 @@ Extend is built around the work of turning raw PDFs, spreadsheets, scans, and te
- Viewers for the file types document-heavy products need every day.
- Navigation primitives for pages, sheets, sections, images, and extracted text.
-- Review surfaces for annotations, citations, e-signature, and human-in-the-loop checks.
+- Review surfaces for annotations, e-signature, and human-in-the-loop checks.
- Utility panels for OCR blocks, extraction status, and validation context.
## Component set
diff --git a/apps/v4/content/docs/components/citations.mdx b/apps/v4/content/docs/components/citations.mdx
deleted file mode 100644
index 3d68831..0000000
--- a/apps/v4/content/docs/components/citations.mdx
+++ /dev/null
@@ -1,67 +0,0 @@
----
-title: Citations
-description: Link extracted answers, review notes, and model outputs back to exact PDF pages and regions.
-component: true
----
-
-Citations connect document answers to their source evidence. They should make it easy to jump from an extracted value, comment, or answer back to the PDF page that supports it.
-
-See it composed with the PDF Viewer in the [Citations block](/blocks#citations).
-
-<CitationsDemo />
-
-## Installation
-
-<CodeTabs>
-
-<TabsList>
- <TabsTrigger value="cli">Command</TabsTrigger>
- <TabsTrigger value="manual">Manual</TabsTrigger>
-</TabsList>
-<TabsContent value="cli">
-
-```bash
-npx shadcn@latest add http://localhost:4000/r/citations.json
-```
-
-</TabsContent>
-
-<TabsContent value="manual">
-
-<Steps className="mb-0 pt-2">
-
-<Step>Copy and paste the following code into your project.</Step>
-
-<CitationsSource />
-
-<Step>Update the import paths to match your project setup.</Step>
-
-</Steps>
-
-</TabsContent>
-
-</CodeTabs>
-
-## Useful behaviors
-
-- Page and bounding-box anchors for source evidence.
-- Highlighted citation regions that can be focused from outside the viewer.
-- Citation lists grouped by answer, field, or reviewer note.
-- Empty and unresolved states when the cited page or region is unavailable.
-
-## API Reference
-
-### CitationCard
-
-The CitationCard component renders a clickable citation result that can focus a related PDF page or region.
-
-| Prop | Type | Default | Required |
-| ----------------- | ----------------------------------------------- | ------------------------- | -------- |
-| `fieldKey` | `string` | `-` | Yes |
-| `value` | `string` | `-` | Yes |
-| `description` | `string` | `-` | No |
-| `pageLabel` | `string` | `-` | No |
-| `active` | `boolean` | `false` | No |
-| `accentClassName` | `string` | blue active field styling | No |
-| `className` | `string` | `-` | No |
-| `...props` | `React.ButtonHTMLAttributes<HTMLButtonElement>` | `-` | No |
diff --git a/apps/v4/content/docs/components/human-review.mdx b/apps/v4/content/docs/components/human-review.mdx
index 5231000..64cb14a 100644
--- a/apps/v4/content/docs/components/human-review.mdx
+++ b/apps/v4/content/docs/components/human-review.mdx
@@ -33,7 +33,7 @@ npx shadcn@latest add http://localhost:4000/r/human-review.json
<Step>Install the following dependencies:</Step>
```bash
-npm install @hugeicons/core-free-icons @hugeicons/react @pierre/diffs
+npm install @glideapps/glide-data-grid @hugeicons/core-free-icons @hugeicons/react @pierre/diffs
```
<Step>Copy and paste the following code into your project.</Step>
@@ -51,6 +51,7 @@ npm install @hugeicons/core-free-icons @hugeicons/react @pierre/diffs
## Useful behaviors
- Actual and expected values displayed side by side for each schema field.
+- Array values rendered with Glide Data Grid, including drill-down for nested arrays and objects.
- Input controls selected from the JSON schema property type.
- Object schema properties rendered as nested cards in the scrollable form.
- Per-field undo and Set to NULL actions.
@@ -62,19 +63,19 @@ npm install @hugeicons/core-free-icons @hugeicons/react @pierre/diffs
The HumanReviewPanel component renders editable review fields and a JSON diff for the same extraction output.
-| Prop | Type | Default | Required |
-| ---------------- | ----------------------------- | --------------- | -------- |
-| `fields` | `ReviewField[]` | sample fields | No |
-| `activeFieldKey` | `string` | `-` | No |
-| `className` | `string` | `-` | No |
-| `onFieldFocus` | `(field: ReviewField) => void` | `-` | No |
+| Prop | Type | Default | Required |
+| ---------------- | ------------------------------ | ------------- | -------- |
+| `fields` | `ReviewField[]` | sample fields | No |
+| `activeFieldKey` | `string` | `-` | No |
+| `className` | `string` | `-` | No |
+| `onFieldFocus` | `(field: ReviewField) => void` | `-` | No |
### ReviewField
-| Prop | Type | Default | Required |
-| ---------- | ------------------- | ------- | -------- |
-| `key` | `string` | `-` | Yes |
-| `schema` | `ReviewFieldSchema` | `-` | Yes |
-| `actual` | `JsonValue` | `-` | Yes |
-| `expected` | `JsonValue` | `-` | Yes |
-| `location` | `{ page: number; area: HighlightArea }` | `-` | No |
+| Prop | Type | Default | Required |
+| ---------- | --------------------------------------- | ------- | -------- |
+| `key` | `string` | `-` | Yes |
+| `schema` | `ReviewFieldSchema` | `-` | Yes |
+| `actual` | `JsonValue` | `-` | Yes |
+| `expected` | `JsonValue` | `-` | Yes |
+| `location` | `{ page: number; area: HighlightArea }` | `-` | No |
diff --git a/apps/v4/content/docs/components/meta.json b/apps/v4/content/docs/components/meta.json
index 8cf351a..f382044 100644
--- a/apps/v4/content/docs/components/meta.json
+++ b/apps/v4/content/docs/components/meta.json
@@ -8,12 +8,11 @@
"xlsx-viewer",
"xlsx-editor",
"csv-tsv-viewer",
- "file-thumbnail",
"file-upload",
- "citations",
+ "human-review",
+ "file-thumbnail",
"ocr-blocks",
"e-signature",
- "human-review",
"document-splits"
]
}
diff --git a/apps/v4/content/docs/components/pdf-viewer.mdx b/apps/v4/content/docs/components/pdf-viewer.mdx
index f87aa4d..6ffddac 100644
--- a/apps/v4/content/docs/components/pdf-viewer.mdx
+++ b/apps/v4/content/docs/components/pdf-viewer.mdx
@@ -57,7 +57,7 @@ import "react-pdf/dist/Page/TextLayer.css"
- Zoom, fit width, fit page, rotate, and print/download actions.
- Virtualized page rendering for long PDFs.
-- Optional citation anchors, OCR block overlays, e-signature fields, search highlights, and annotation layer.
+- Optional OCR block overlays, e-signature fields, search highlights, and annotation layer.
- Text layer support for selection, copy, search, and accessibility.
## API Reference
diff --git a/apps/v4/mdx-components.tsx b/apps/v4/mdx-components.tsx
index 9bec764..c2431e3 100644
--- a/apps/v4/mdx-components.tsx
+++ b/apps/v4/mdx-components.tsx
@@ -6,7 +6,6 @@ import { type PageTreeFolder } from "@/lib/page-tree"
import { source } from "@/lib/source"
import { cn } from "@/lib/utils"
import { Callout } from "@/components/callout"
-import { CitationsDemo, CitationsSource } from "@/components/citations-docs"
import { CodeBlockCommand } from "@/components/code-block-command"
import { CodeCollapsibleWrapper } from "@/components/code-collapsible-wrapper"
import { CodeTabs } from "@/components/code-tabs"
@@ -373,8 +372,6 @@ export const mdxComponents = {
CodeTabs,
CodeCollapsibleWrapper,
ComponentsList: ComponentsListWrapper,
- CitationsDemo,
- CitationsSource,
CsvViewerDemo,
CsvViewerSource,
DocumentSplitsDemo,
diff --git a/apps/v4/registry.json b/apps/v4/registry.json
index b57c849..14076c7 100644
--- a/apps/v4/registry.json
+++ b/apps/v4/registry.json
@@ -779,26 +779,6 @@
}
]
},
- {
- "name": "citations",
- "type": "registry:block",
- "title": "Citations",
- "description": "A PDF evidence review block with citation cards that focus page regions.",
- "registryDependencies": [
- "pdf-block-resizable-shell",
- "pdf-viewer",
- "scroll-area",
- "utils"
- ],
- "categories": ["documents", "blocks"],
- "files": [
- {
- "path": "registry/new-york-v4/blocks/citations.tsx",
- "type": "registry:component",
- "target": "@components/blocks/citations.tsx"
- }
- ]
- },
{
"name": "ocr-blocks",
"type": "registry:block",
@@ -858,6 +838,7 @@
"title": "Human Review",
"description": "A human-in-the-loop extraction review block linked to source PDF evidence.",
"dependencies": [
+ "@glideapps/[email protected]",
"@hugeicons/core-free-icons@^4.1.1",
"@hugeicons/react@^1.1.6",
"@pierre/diffs@^1.1.22"
diff --git a/apps/v4/registry/new-york-v4/blocks/citations.tsx b/apps/v4/registry/new-york-v4/blocks/citations.tsx
deleted file mode 100644
index 8a8840c..0000000
--- a/apps/v4/registry/new-york-v4/blocks/citations.tsx
+++ /dev/null
@@ -1,180 +0,0 @@
-"use client"
-
-import * as React from "react"
-
-import { cn } from "@/lib/utils"
-import { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"
-import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"
-import { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"
-
-type Point = { x: number; y: number }
-type Citation = {
- id: string
- description: string
- value: string
- page: number
- polygon: Point[]
-}
-type HighlightArea = {
- left: number
- top: number
- width: number
- height: number
-}
-
-const ANNOTATION_PAGE_WIDTH = 792
-const ANNOTATION_PAGE_HEIGHT = 612
-const CITATIONS: Citation[] = [
- {
- id: "title",
- description: "Paper title extracted from the first page heading.",
- value: "Attention Is All You Need",
- page: 1,
- polygon: [
- { x: 246, y: 188 },
- { x: 566, y: 188 },
- { x: 566, y: 222 },
- { x: 246, y: 222 },
- ],
- },
- {
- id: "authors",
- description: "Authors listed beneath the paper title.",
- value: "Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser",
- page: 1,
- polygon: [
- { x: 92, y: 206 },
- { x: 698, y: 206 },
- { x: 698, y: 270 },
- { x: 92, y: 270 },
- ],
- },
- {
- id: "abstract",
- description: "Central model claim from the abstract.",
- value: "The Transformer avoids recurrence and convolutions.",
- page: 1,
- polygon: [
- { x: 108, y: 346 },
- { x: 692, y: 346 },
- { x: 692, y: 414 },
- { x: 108, y: 414 },
- ],
- },
-]
-
-function convertPolygonToHighlightArea(polygon: Point[]): HighlightArea {
- const xValues = polygon.map((point) => point.x)
- const yValues = polygon.map((point) => point.y)
- const left = Math.min(...xValues)
- const right = Math.max(...xValues)
- const top = Math.min(...yValues)
- const bottom = Math.max(...yValues)
-
- return {
- left: (left / ANNOTATION_PAGE_WIDTH) * 100,
- top: (top / ANNOTATION_PAGE_HEIGHT) * 100,
- width: ((right - left) / ANNOTATION_PAGE_WIDTH) * 100,
- height: ((bottom - top) / ANNOTATION_PAGE_HEIGHT) * 100,
- }
-}
-
-function CitationHighlight({ citation }: { citation: Citation }) {
- const highlight = convertPolygonToHighlightArea(citation.polygon)
-
- return (
- <div
- className="pointer-events-none absolute z-10 rounded-[3px] border border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_12%)]"
- style={{
- left: `${highlight.left}%`,
- top: `${highlight.top}%`,
- width: `${highlight.width}%`,
- height: `${highlight.height}%`,
- }}
- />
- )
-}
-
-export function CitationsBlock({ file }: { file?: string }) {
- const [activeCitationId, setActiveCitationId] = React.useState(
- CITATIONS[0].id
- )
- const viewerRef = React.useRef<PDFViewerHandle>(null)
- const activeCitation =
- CITATIONS.find((citation) => citation.id === activeCitationId) ??
- CITATIONS[0]
-
- const focusCitation = React.useCallback((citation: Citation) => {
- setActiveCitationId(citation.id)
- viewerRef.current?.scrollToPageArea(
- citation.page,
- convertPolygonToHighlightArea(citation.polygon)
- )
- }, [])
-
- return (
- <PdfBlockResizableShell
- autoSaveId="pdf-block-citations"
- left={
- <PDFViewer
- ref={viewerRef}
- file={file}
- defaultZoom={0.75}
- renderPageOverlay={({ pageNumber }) =>
- activeCitation.page === pageNumber ? (
- <CitationHighlight citation={activeCitation} />
- ) : null
- }
- />
- }
- right={
- <aside className="min-h-0 bg-background">
- <ScrollArea className="h-full" scrollFade>
- <div className="space-y-2 p-3">
- {CITATIONS.map((citation) => {
- const isActive = citation.id === activeCitation.id
-
- return (
- <button
- key={citation.id}
- type="button"
- onClick={() => focusCitation(citation)}
- onFocus={() => focusCitation(citation)}
- onMouseEnter={() => focusCitation(citation)}
- className={cn(
- "w-full rounded-lg border bg-background p-3 text-left transition-[border-color,background-color,box-shadow] hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:border-blue-500/60 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",
- isActive &&
- "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_8%)]"
- )}
- >
- <div className="mb-3 flex min-h-8 items-start justify-between gap-3">
- <div className="min-w-0">
- <div className="truncate text-sm font-medium">
- {citation.id}
- </div>
- <div className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">
- {citation.description}
- </div>
- </div>
- <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">
- p. {citation.page}
- </div>
- </div>
- <div className="rounded-md border bg-muted/30 p-2">
- <div className="mb-1 text-[11px] font-medium text-muted-foreground">
- Actual output
- </div>
- <div className="min-h-7 rounded-md bg-background px-2 py-1.5 text-sm">
- {citation.value}
- </div>
- </div>
- </button>
- )
- })}
- </div>
- </ScrollArea>
- </aside>
- }
- />
- )
-}
diff --git a/apps/v4/registry/new-york-v4/blocks/human-review.tsx b/apps/v4/registry/new-york-v4/blocks/human-review.tsx
index e490306..e51b740 100644
--- a/apps/v4/registry/new-york-v4/blocks/human-review.tsx
+++ b/apps/v4/registry/new-york-v4/blocks/human-review.tsx
@@ -2,10 +2,25 @@
import * as React from "react"
import {
+ DataEditor,
+ emptyGridSelection,
+ GridCellKind,
+ type DrawCellCallback,
+ type EditableGridCell,
+ type GridCell,
+ type GridColumn,
+ type GridSelection,
+ type Item,
+ type Rectangle,
+ type Theme,
+} from "@glideapps/glide-data-grid"
+import {
+ ArrowLeft01Icon,
CancelCircleIcon,
FileDiffIcon,
InputNumericIcon,
InputTextIcon,
+ SecondBracketIcon,
SourceCodeSquareIcon,
TextCheckIcon,
Undo02Icon,
@@ -32,15 +47,19 @@ import {
TooltipTrigger,
} from "@/registry/new-york-v4/ui/tooltip"
+import "@glideapps/glide-data-grid/dist/index.css"
+
export type JsonPrimitive = string | number | boolean | null
-export type JsonValue = JsonPrimitive | JsonObject
+export type JsonValue = JsonPrimitive | JsonObject | JsonArray
export type JsonObject = { [key: string]: JsonValue }
+export type JsonArray = JsonValue[]
export type SchemaPropertyType =
| "string"
| "number"
| "integer"
| "boolean"
| "object"
+ | "array"
export type ReviewFieldSchema = {
type: SchemaPropertyType
@@ -48,6 +67,7 @@ export type ReviewFieldSchema = {
description?: string
enum?: Array<string | number>
properties?: Record<string, ReviewFieldSchema>
+ items?: ReviewFieldSchema
}
export type HighlightArea = {
@@ -102,6 +122,97 @@ const DIFF_VIEWER_THEME = {
"--diffs-line-height": "20px",
} as React.CSSProperties
+function readIsDarkTheme() {
+ return (
+ typeof document !== "undefined" &&
+ document.documentElement.classList.contains("dark")
+ )
+}
+
+// A single shared MutationObserver backs every consumer. Each grid previously
+// created its own observer (two, via useHumanReviewGridTheme), so opening a
+// nested array view spun up and tore down several observers at once.
+const darkThemeListeners = new Set<(isDark: boolean) => void>()
+let darkThemeObserver: MutationObserver | null = null
+let sharedIsDarkTheme = false
+
+function ensureDarkThemeObserver() {
+ if (
+ darkThemeObserver ||
+ typeof document === "undefined" ||
+ typeof MutationObserver === "undefined"
+ ) {
+ return
+ }
+
+ sharedIsDarkTheme = readIsDarkTheme()
+ darkThemeObserver = new MutationObserver(() => {
+ const nextIsDark = readIsDarkTheme()
+ if (nextIsDark === sharedIsDarkTheme) return
+
+ sharedIsDarkTheme = nextIsDark
+ darkThemeListeners.forEach((listener) => listener(nextIsDark))
+ })
+ darkThemeObserver.observe(document.documentElement, {
+ attributes: true,
+ attributeFilter: ["class"],
+ })
+}
+
+function useIsDarkTheme() {
+ const [isDark, setIsDark] = React.useState(readIsDarkTheme)
+
+ React.useEffect(() => {
+ ensureDarkThemeObserver()
+ setIsDark(sharedIsDarkTheme)
+ darkThemeListeners.add(setIsDark)
+
+ return () => {
+ darkThemeListeners.delete(setIsDark)
+ if (darkThemeListeners.size === 0 && darkThemeObserver) {
+ darkThemeObserver.disconnect()
+ darkThemeObserver = null
+ }
+ }
+ }, [])
+
+ return isDark
+}
+
+function useHumanReviewGridTheme() {
+ const isDark = useIsDarkTheme()
+
+ return React.useMemo<Partial<Theme>>(
+ () => ({
+ accentColor: isDark ? "rgb(96, 165, 250)" : "rgb(37, 99, 235)",
+ accentLight: isDark ? "rgba(29, 78, 216, 0.15)" : "rgb(219, 234, 254)",
+ accentFg: "rgb(255, 255, 255)",
+ textDark: isDark ? "rgb(229, 229, 229)" : "rgb(23, 23, 23)",
+ textMedium: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",
+ textLight: isDark ? "rgb(115, 115, 115)" : "rgb(163, 163, 163)",
+ textBubble: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",
+ textHeader: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",
+ textGroupHeader: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",
+ bgCell: isDark ? "rgb(10, 10, 10)" : "rgb(255, 255, 255)",
+ bgCellMedium: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",
+ bgHeader: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",
+ bgHeaderHasFocus: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",
+ bgHeaderHovered: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",
+ borderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",
+ horizontalBorderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",
+ cellHorizontalPadding: 8,
+ cellVerticalPadding: 3,
+ headerIconSize: 18,
+ baseFontStyle: "13px",
+ headerFontStyle: "600 13px",
+ markerFontStyle: "11px",
+ fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
+ editorFontSize: "13px",
+ }),
+ [isDark]
+ )
+}
+
const REVIEW_FIELDS: ReviewField[] = [
{
key: "vendor_name",
@@ -145,6 +256,104 @@ const REVIEW_FIELDS: ReviewField[] = [
area: { left: 13.5, top: 55.5, width: 73.5, height: 7.5 },
},
},
+ {
+ key: "line_items",
+ schema: {
+ type: "array",
+ title: "Line items",
+ description: "Invoice rows with nested allocation details.",
+ items: {
+ type: "object",
+ properties: {
+ description: {
+ type: "string",
+ title: "Description",
+ },
+ quantity: {
+ type: "number",
+ title: "Qty",
+ },
+ unit_price: {
+ type: "number",
+ title: "Unit price",
+ },
+ tax_detail: {
+ type: "object",
+ title: "Tax detail",
+ properties: {
+ code: {
+ type: "string",
+ title: "Code",
+ },
+ jurisdiction: {
+ type: "string",
+ title: "Jurisdiction",
+ },
+ },
+ },
+ allocations: {
+ type: "array",
+ title: "Allocations",
+ items: {
+ type: "object",
+ properties: {
+ department: {
+ type: "string",
+ title: "Department",
+ },
+ percent: {
+ type: "number",
+ title: "Percent",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ actual: [
+ {
+ description: "Transformer implementation support",
+ quantity: 2,
+ unit_price: 4200,
+ tax_detail: { code: "TX-CA", jurisdiction: "CA" },
+ allocations: [
+ { department: "Research", percent: 70 },
+ { department: "Platform", percent: 20 },
+ ],
+ },
+ {
+ description: "Attention model review",
+ quantity: 1,
+ unit_price: 4080,
+ tax_detail: { code: "TX-NY", jurisdiction: "NY" },
+ allocations: [{ department: "Research", percent: 100 }],
+ },
+ ],
+ expected: [
+ {
+ description: "Transformer implementation support",
+ quantity: 2,
+ unit_price: 4200,
+ tax_detail: { code: "TX-CA", jurisdiction: "CA" },
+ allocations: [
+ { department: "Research", percent: 70 },
+ { department: "Platform", percent: 30 },
+ ],
+ },
+ {
+ description: "Attention model review",
+ quantity: 1,
+ unit_price: 4080.75,
+ tax_detail: { code: "TX-NY", jurisdiction: "NY" },
+ allocations: [{ department: "Research", percent: 100 }],
+ },
+ ],
+ location: {
+ page: 1,
+ area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },
+ },
+ },
{
key: "requires_review",
schema: {
@@ -211,6 +420,10 @@ function isJsonObject(value: JsonValue): value is JsonObject {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
+function isJsonArray(value: JsonValue): value is JsonArray {
+ return Array.isArray(value)
+}
+
function getObjectValue(value: JsonValue, key: string): JsonValue {
if (!isJsonObject(value)) return null
return value[key] ?? null
@@ -227,8 +440,22 @@ function setObjectValue(
}
}
+function getArrayValue(value: JsonValue): JsonArray {
+ return isJsonArray(value) ? value : []
+}
+
+function setArrayItemValue(
+ value: JsonValue,
+ index: number,
+ childValue: JsonValue
+): JsonArray {
+ const nextValue = getArrayValue(value).slice()
+ nextValue[index] = childValue
+ return nextValue
+}
+
function getPrimitiveValue(value: JsonValue): JsonPrimitive {
- return isJsonObject(value) ? null : value
+ return isJsonObject(value) || isJsonArray(value) ? null : value
}
function jsonValuesEqual(left: JsonValue, right: JsonValue) {
@@ -281,7 +508,7 @@ function findReviewField(
function formatValue(value: JsonValue) {
if (value === null) return "NULL"
- if (isJsonObject(value)) return formatJson(value)
+ if (isJsonObject(value) || isJsonArray(value)) return formatJson(value)
if (typeof value === "boolean") return value ? "true" : "false"
return String(value)
}
@@ -289,15 +516,18 @@ function formatValue(value: JsonValue) {
function getFieldIcon(type: SchemaPropertyType) {
if (type === "number" || type === "integer") return InputNumericIcon
if (type === "boolean") return TextCheckIcon
+ if (type === "array") return SecondBracketIcon
if (type === "object") return SourceCodeSquareIcon
return InputTextIcon
}
function HumanReviewValueInput({
+ readOnly = false,
schema,
value,
onChange,
}: {
+ readOnly?: boolean
schema: ReviewFieldSchema
value: JsonPrimitive
onChange: (value: JsonPrimitive) => void
@@ -306,6 +536,7 @@ function HumanReviewValueInput({
return (
<span className="relative inline-flex w-full rounded-lg border border-input bg-background text-sm text-foreground shadow-xs/5 dark:bg-input/32">
<select
+ disabled={readOnly}
value={value === null ? "" : String(value)}
onChange={(event) => onChange(event.target.value)}
className="h-8.5 w-full appearance-none rounded-[inherit] bg-transparent px-3 text-sm outline-none sm:h-7.5"
@@ -324,6 +555,7 @@ function HumanReviewValueInput({
return (
<Input
nativeInput
+ readOnly={readOnly}
type="number"
value={value === null ? "" : String(value)}
onChange={(event) => {
@@ -347,6 +579,7 @@ function HumanReviewValueInput({
"h-7 shadow-none",
value === option && "bg-background dark:bg-input"
)}
+ disabled={readOnly}
onClick={() => onChange(option)}
>
{option ? "True" : "False"}
@@ -359,36 +592,826 @@ function HumanReviewValueInput({
return (
<Input
nativeInput
+ readOnly={readOnly}
value={value === null ? "" : String(value)}
onChange={(event) => onChange(event.currentTarget.value)}
/>
)
}
-function HumanReviewFieldCard({
- field,
+function getArrayItemSchema(schema: ReviewFieldSchema): ReviewFieldSchema {
+ return schema.items ?? { type: "string" }
+}
+
+function isComplexSchema(schema: ReviewFieldSchema) {
+ return schema.type === "object" || schema.type === "array"
+}
+
+function summarizeComplexValue(value: JsonValue) {
+ if (isJsonArray(value)) return `${value.length} items`
+ if (isJsonObject(value)) return `${Object.keys(value).length} fields`
+ return formatValue(value)
+}
+
+function getCellValueForArrayColumn(
+ rowValue: JsonValue,
+ itemSchema: ReviewFieldSchema,
+ columnId: string
+) {
+ if (itemSchema.type === "object") {
+ return getObjectValue(rowValue, columnId)
+ }
+
+ return rowValue
+}
+
+function getCellSchemaForArrayColumn(
+ itemSchema: ReviewFieldSchema,
+ columnId: string
+) {
+ if (itemSchema.type === "object") {
+ return itemSchema.properties?.[columnId] ?? { type: "string" }
+ }
+
+ return itemSchema
+}
+
+function applyPrimitiveEdit(
+ schema: ReviewFieldSchema,
+ value: EditableGridCell
+): JsonValue | undefined {
+ if (schema.type === "boolean" && value.kind === GridCellKind.Boolean) {
+ return value.data
+ }
+
+ if (
+ (schema.type === "number" || schema.type === "integer") &&
+ value.kind === GridCellKind.Number
+ ) {
+ return value.data ?? null
+ }
+
+ if (value.kind === GridCellKind.Text) {
+ if (schema.type === "number" || schema.type === "integer") {
+ return value.data.trim() === "" ? null : Number(value.data)
+ }
+
+ return value.data
+ }
+
+ return undefined
+}
+
+type ArrayNestedView = {
+ rowIndex: number
+ columnId: string
+ title: string
+ schema: ReviewFieldSchema
+ value: JsonValue
+}
+
+type ArrayReviewSide = "actual" | "expected"
+
+type SyncedArrayNestedView = {
+ activeSide: ArrayReviewSide | null
+ stack: ArrayNestedView[]
+}
+
+type SyncedArraySelection = {
+ activeSide: ArrayReviewSide | null
+ depth: number
+ gridSelection: GridSelection
+}
+
+const EMPTY_SYNCED_ARRAY_NESTED_VIEW: SyncedArrayNestedView = {
+ activeSide: null,
+ stack: [],
+}
+
+const EMPTY_SYNCED_ARRAY_SELECTION: SyncedArraySelection = {
+ activeSide: null,
+ depth: 0,
+ gridSelection: emptyGridSelection,
+}
+
+function setNestedArrayValue({
+ value,
+ schema,
+ nestedStack,
+ nextNestedValue,
+}: {
+ value: JsonValue
+ schema: ReviewFieldSchema
+ nestedStack: ArrayNestedView[]
+ nextNestedValue: JsonValue
+}): JsonValue {
+ const [currentView, ...remainingViews] = nestedStack
+
+ if (!currentView) return nextNestedValue
+
+ const itemSchema = getArrayItemSchema(schema)
+ const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null
+ const cellSchema = getCellSchemaForArrayColumn(
+ itemSchema,
+ currentView.columnId
+ )
+ const currentCellValue = getCellValueForArrayColumn(
+ rowValue,
+ itemSchema,
+ currentView.columnId
+ )
+ const nextCellValue: JsonValue = remainingViews.length
+ ? setNestedArrayValue({
+ value: currentCellValue,
+ schema: cellSchema,
+ nestedStack: remainingViews,
+ nextNestedValue,
+ })
+ : nextNestedValue
+ const nextRowValue: JsonValue =
+ itemSchema.type === "object"
+ ? setObjectValue(rowValue, currentView.columnId, nextCellValue)
+ : nextCellValue
+
+ return setArrayItemValue(value, currentView.rowIndex, nextRowValue)
+}
+
+function getNestedArrayValue({
+ value,
+ schema,
+ nestedStack,
+}: {
+ value: JsonValue
+ schema: ReviewFieldSchema
+ nestedStack: ArrayNestedView[]
+}): JsonValue {
+ const [currentView, ...remainingViews] = nestedStack
+
+ if (!currentView) return value
+
+ const itemSchema = getArrayItemSchema(schema)
+ const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null
+ const cellSchema = getCellSchemaForArrayColumn(
+ itemSchema,
+ currentView.columnId
+ )
+ const cellValue = getCellValueForArrayColumn(
+ rowValue,
+ itemSchema,
+ currentView.columnId
+ )
+
+ if (!remainingViews.length) return cellValue
+
+ return getNestedArrayValue({
+ value: cellValue,
+ schema: cellSchema,
+ nestedStack: remainingViews,
+ })
+}
+
+function isCellInRange(col: number, row: number, range: Rectangle) {
+ return (
+ col >= range.x &&
+ col < range.x + range.width &&
+ row >= range.y &&
+ row < range.y + range.height
+ )
+}
+
+function getRangeEdges(col: number, row: number, range: Rectangle) {
+ return {
+ bottom: row === range.y + range.height - 1,
+ left: col === range.x,
+ right: col === range.x + range.width - 1,
+ top: row === range.y,
+ }
+}
+
+function HumanReviewArrayValueGrid({
+ activeNestedSide = null,
+ activeSelectionSide = null,
+ label,
+ nestedStackBaseDepth = 0,
+ readOnly = false,
+ schema,
+ selectionDepth = 0,
+ sharedGridSelection,
+ sharedNestedStack,
+ value,
+ viewSide = "expected",
+ onChange,
+ onGridSelectionChange,
+ onNestedStackChange,
+}: {
+ activeNestedSide?: ArrayReviewSide | null
+ activeSelectionSide?: ArrayReviewSide | null
+ label: string
+ nestedStackBaseDepth?: number
+ readOnly?: boolean
+ schema: ReviewFieldSchema
+ selectionDepth?: number
+ sharedGridSelection?: GridSelection
+ sharedNestedStack?: ArrayNestedView[]
+ value: JsonValue
+ viewSide?: ArrayReviewSide
+ onChange?: (value: JsonValue) => void
+ onGridSelectionChange?: (
+ selection: GridSelection,
+ side: ArrayReviewSide,
+ depth: number
+ ) => void
+ onNestedStackChange?: (
+ stack: ArrayNestedView[],
+ side: ArrayReviewSide
+ ) => void
+}) {
+ const rows = getArrayValue(value)
+ const itemSchema = getArrayItemSchema(schema)
+ const gridTheme = useHumanReviewGridTheme()
+ const isDark = useIsDarkTheme()
+ const [localNestedStack, setLocalNestedStack] = React.useState<
+ ArrayNestedView[]
+ >([])
+ const [localGridSelection, setLocalGridSelection] =
+ React.useState<GridSelection>(emptyGridSelection)
+ const nestedStack = sharedNestedStack ?? localNestedStack
+ const syncedGridSelection = sharedGridSelection ?? localGridSelection
+ const gridSelection =
+ sharedGridSelection &&
+ (activeSelectionSide !== viewSide ||
+ selectionDepth !== nestedStackBaseDepth)
+ ? emptyGridSelection
+ : syncedGridSelection
+ const sharedSelectionRange = sharedGridSelection?.current?.range
+ const sharedSelectionRangeStack = sharedGridSelection?.current?.rangeStack
+ const mirroredSelectionRanges = React.useMemo<readonly Rectangle[]>(() => {
+ if (
+ !activeSelectionSide ||
+ activeSelectionSide === viewSide ||
+ selectionDepth !== nestedStackBaseDepth ||
+ !sharedSelectionRange ||
+ !sharedSelectionRangeStack
+ ) {
+ return []
+ }
+
+ return [...sharedSelectionRangeStack, sharedSelectionRange]
+ }, [
+ activeSelectionSide,
+ nestedStackBaseDepth,
+ selectionDepth,
+ sharedSelectionRange,
+ sharedSelectionRangeStack,
+ viewSide,
+ ])
+ const visibleNestedStack = nestedStack.slice(nestedStackBaseDepth)
+ const activeNestedView = visibleNestedStack[0] ?? null
+ const activeNestedValue = activeNestedView
+ ? getNestedArrayValue({
+ value,
+ schema,
+ nestedStack: [activeNestedView],
+ })
+ : null
+ const isActiveNestedSource =
+ Boolean(activeNestedView) && activeNestedSide === viewSide
+ const isMirroredNestedTarget =
+ Boolean(activeNestedView) &&
+ activeNestedSide !== null &&
+ activeNestedSide !== viewSide
+ const blueCellText = isDark ? "rgb(147, 197, 253)" : "rgb(37, 99, 235)"
+ const selectedCellBackground = isDark
+ ? "rgba(37, 99, 235, 0.2)"
+ : "rgba(219, 234, 254, 0.85)"
+ const mirroredCellBackground = isDark
+ ? "rgba(167, 139, 250, 0.18)"
+ : "rgba(237, 233, 254, 0.9)"
+ const mirroredCellBorder = isDark ? "rgb(196, 181, 253)" : "rgb(124, 58, 237)"
+
+ const setNestedStack = React.useCallback(
+ (
+ updater:
+ | ArrayNestedView[]
+ | ((current: ArrayNestedView[]) => ArrayNestedView[])
+ ) => {
+ if (onNestedStackChange) {
+ const nextStack =
+ typeof updater === "function" ? updater(nestedStack) : updater
+
+ onNestedStackChange(nextStack, viewSide)
+ return
+ }
+
+ setLocalNestedStack(updater)
+ },
+ [nestedStack, onNestedStackChange, viewSide]
+ )
+
+ const handleGridSelectionChange = React.useCallback(
+ (selection: GridSelection) => {
+ if (onGridSelectionChange) {
+ onGridSelectionChange(selection, viewSide, nestedStackBaseDepth)
+ return
+ }
+
+ setLocalGridSelection(selection)
+ },
+ [nestedStackBaseDepth, onGridSelectionChange, viewSide]
+ )
+
+ const columns = React.useMemo<GridColumn[]>(() => {
+ if (itemSchema.type === "object") {
+ const propertyEntries = Object.entries(itemSchema.properties ?? {})
+
+ if (propertyEntries.length) {
+ return propertyEntries.map(([key, propertySchema]) => ({
+ id: key,
+ title: propertySchema.title ?? key,
+ width: isComplexSchema(propertySchema) ? 148 : 132,
+ }))
+ }
+ }
+
+ return [
+ {
+ id: "value",
+ title: itemSchema.title ?? "Value",
+ width: isComplexSchema(itemSchema) ? 148 : 180,
+ },
+ ]
+ }, [itemSchema])
+
+ const getCellContent = React.useCallback(
+ ([col, row]: Item): GridCell => {
+ const column = columns[col]
+ const columnId = String(column?.id ?? "value")
+ const rowValue = rows[row] ?? null
+ const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)
+ const cellValue = getCellValueForArrayColumn(
+ rowValue,
+ itemSchema,
+ columnId
+ )
+ const matchedNestedCell =
+ activeNestedView?.rowIndex === row &&
+ activeNestedView.columnId === columnId
+ const matchesMirroredSelection = mirroredSelectionRanges.some((range) =>
+ isCellInRange(col, row, range)
+ )
+ const nestedCellTheme: Partial<Theme> | undefined = matchedNestedCell
+ ? {
+ bgCell: isMirroredNestedTarget
+ ? mirroredCellBackground
+ : selectedCellBackground,
+ textDark: blueCellText,
+ }
+ : undefined
+ const selectionCellTheme: Partial<Theme> | undefined =
+ matchesMirroredSelection
+ ? {
+ bgCell: mirroredCellBackground,
+ textDark: isDark ? "rgb(233, 213, 255)" : "rgb(91, 33, 182)",
+ }
+ : undefined
+
+ if (isComplexSchema(cellSchema)) {
+ return {
+ kind: GridCellKind.Text,
+ data: summarizeComplexValue(cellValue),
+ displayData: summarizeComplexValue(cellValue),
+ allowOverlay: false,
+ readonly: true,
+ cursor: "pointer",
+ activationBehaviorOverride: "double-click",
+ themeOverride: {
+ textDark: blueCellText,
+ ...(selectionCellTheme ?? {}),
+ ...(nestedCellTheme ?? {}),
+ },
+ }
+ }
+
+ if (cellSchema.type === "boolean") {
+ return {
+ kind: GridCellKind.Boolean,
+ data: typeof cellValue === "boolean" ? cellValue : false,
+ allowOverlay: false,
+ readonly: readOnly,
+ ...(selectionCellTheme ? { themeOverride: selectionCellTheme } : {}),
+ }
+ }
+
+ if (cellSchema.type === "number" || cellSchema.type === "integer") {
+ return {
+ kind: GridCellKind.Number,
+ data: typeof cellValue === "number" ? cellValue : undefined,
+ displayData: typeof cellValue === "number" ? String(cellValue) : "",
+ allowOverlay: !readOnly,
+ readonly: readOnly,
+ ...(selectionCellTheme ? { themeOverride: selectionCellTheme } : {}),
+ }
+ }
+
+ return {
+ kind: GridCellKind.Text,
+ data:
+ cellValue === null ||
+ isJsonObject(cellValue) ||
+ isJsonArray(cellValue)
+ ? ""
+ : String(cellValue),
+ displayData:
+ cellValue === null ||
+ isJsonObject(cellValue) ||
+ isJsonArray(cellValue)
+ ? ""
+ : String(cellValue),
+ allowOverlay: !readOnly,
+ readonly: readOnly,
+ ...(selectionCellTheme ? { themeOverride: selectionCellTheme } : {}),
+ }
+ },
+ [
+ activeNestedView,
+ blueCellText,
+ columns,
+ isMirroredNestedTarget,
+ isDark,
+ itemSchema,
+ mirroredCellBackground,
+ mirroredSelectionRanges,
+ readOnly,
+ rows,
+ selectedCellBackground,
+ ]
+ )
+
+ const updateCellValue = React.useCallback(
+ ([col, row]: Item, nextCell: EditableGridCell) => {
+ if (readOnly || !onChange) return
+
+ const column = columns[col]
+ const columnId = String(column?.id ?? "value")
+ const rowValue = rows[row] ?? null
+ const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)
+ const nextValue = applyPrimitiveEdit(cellSchema, nextCell)
+
+ if (nextValue === undefined) return
+
+ const nextRowValue =
+ itemSchema.type === "object"
+ ? setObjectValue(rowValue, columnId, nextValue)
+ : nextValue
+
+ onChange(setArrayItemValue(value, row, nextRowValue))
+ },
+ [columns, itemSchema, onChange, readOnly, rows, value]
+ )
+
+ const drawCell = React.useCallback<DrawCellCallback>(
+ (args, drawContent) => {
+ drawContent()
+
+ const selectionRange = mirroredSelectionRanges.find((range) =>
+ isCellInRange(args.col, args.row, range)
+ )
+
+ if (!selectionRange) {
+ return
+ }
+
+ const { ctx, rect } = args
+ const edges = getRangeEdges(args.col, args.row, selectionRange)
+
+ ctx.save()
+ ctx.strokeStyle = mirroredCellBorder
+ ctx.lineWidth = 1.5
+ ctx.setLineDash([4, 3])
+
+ if (edges.top) {
+ ctx.beginPath()
+ ctx.moveTo(rect.x + 1.5, rect.y + 1.5)
+ ctx.lineTo(rect.x + rect.width - 1.5, rect.y + 1.5)
+ ctx.stroke()
+ }
+
+ if (edges.right) {
+ ctx.beginPath()
+ ctx.moveTo(rect.x + rect.width - 1.5, rect.y + 1.5)
+ ctx.lineTo(rect.x + rect.width - 1.5, rect.y + rect.height - 1.5)
+ ctx.stroke()
+ }
+
+ if (edges.bottom) {
+ ctx.beginPath()
+ ctx.moveTo(rect.x + 1.5, rect.y + rect.height - 1.5)
+ ctx.lineTo(rect.x + rect.width - 1.5, rect.y + rect.height - 1.5)
+ ctx.stroke()
+ }
+
+ if (edges.left) {
+ ctx.beginPath()
+ ctx.moveTo(rect.x + 1.5, rect.y + 1.5)
+ ctx.lineTo(rect.x + 1.5, rect.y + rect.height - 1.5)
+ ctx.stroke()
+ }
+
+ ctx.restore()
+ },
+ [mirroredCellBorder, mirroredSelectionRanges]
+ )
+
+ const openNestedCell = React.useCallback(
+ ([col, row]: Item) => {
+ const column = columns[col]
+ const columnId = String(column?.id ?? "value")
+ const rowValue = rows[row] ?? null
+ const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)
+
+ if (!isComplexSchema(cellSchema)) return
+
+ setNestedStack((current) => {
+ const nextView = {
+ rowIndex: row,
+ columnId,
+ title: `${column?.title ?? columnId} / row ${row + 1}`,
+ schema: cellSchema,
+ value: getCellValueForArrayColumn(rowValue, itemSchema, columnId),
+ }
+ const currentView = current[nestedStackBaseDepth]
+
+ if (
+ currentView?.rowIndex === nextView.rowIndex &&
+ currentView.columnId === nextView.columnId
+ ) {
+ return current
+ }
+
+ return [...current.slice(0, nestedStackBaseDepth), nextView]
+ })
+ },
+ [columns, itemSchema, nestedStackBaseDepth, rows, setNestedStack]
+ )
+
+ const updateNestedValue = React.useCallback(
+ (nextNestedValue: JsonValue) => {
+ if (!activeNestedView || readOnly || !onChange) return
+
+ onChange(
+ setNestedArrayValue({
+ value,
+ schema,
+ nestedStack: visibleNestedStack.slice(0, 1),
+ nextNestedValue,
+ })
+ )
+ setNestedStack((current) =>
+ current.map((view, index) =>
+ index === nestedStackBaseDepth
+ ? { ...view, value: nextNestedValue }
+ : view
+ )
+ )
+ },
+ [
+ activeNestedView,
+ nestedStackBaseDepth,
+ onChange,
+ readOnly,
+ schema,
+ setNestedStack,
+ value,
+ visibleNestedStack,
+ ]
+ )
+
+ return (
+ <div
+ className={cn(
+ "relative overflow-hidden rounded-md border bg-background transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:shadow-[0_0_0_1px_rgb(59_130_246_/_8%)] hover:border-blue-500/50",
+ isActiveNestedSource &&
+ "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_10%)]"
+ )}
+ >
+ <div>
+ <div className="flex h-8 items-center justify-between gap-2 border-b px-2 text-[11px] font-medium text-muted-foreground">
+ <span>{label}</span>
+ <span>{rows.length} rows</span>
+ </div>
+ <div className="h-[220px]">
+ <DataEditor
+ columns={columns}
+ rows={rows.length}
+ getCellContent={getCellContent}
+ cellActivationBehavior="double-click"
+ drawCell={drawCell}
+ gridSelection={gridSelection}
+ onCellEdited={updateCellValue}
+ onCellActivated={openNestedCell}
+ onGridSelectionChange={handleGridSelectionChange}
+ rowMarkers="number"
+ smoothScrollX
+ smoothScrollY
+ theme={gridTheme}
+ width="100%"
+ height="100%"
+ rowHeight={32}
+ headerHeight={34}
+ />
+ </div>
+ </div>
+ {activeNestedView ? (
+ <div className="absolute inset-0 z-10 flex flex-col bg-background">
+ <div className="flex h-8 items-center gap-2 border-b px-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="size-6 text-muted-foreground"
+ onClick={() =>
+ setNestedStack((current) =>
+ current.slice(
+ 0,
+ Math.max(nestedStackBaseDepth, current.length - 1)
+ )
+ )
+ }
+ aria-label="Back to parent array"
+ >
+ <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />
+ </Button>
+ <div className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">
+ {activeNestedView.title}
+ </div>
+ </div>
+ <div className="min-h-0 flex-1 overflow-auto p-2">
+ {activeNestedView.schema.type === "array" ? (
+ <HumanReviewArrayValueGrid
+ label={
+ activeNestedView.schema.title ?? activeNestedView.columnId
+ }
+ nestedStackBaseDepth={nestedStackBaseDepth + 1}
+ readOnly={readOnly}
+ schema={activeNestedView.schema}
+ sharedGridSelection={sharedGridSelection}
+ sharedNestedStack={sharedNestedStack}
+ value={activeNestedValue}
+ viewSide={viewSide}
+ activeNestedSide={activeNestedSide}
+ activeSelectionSide={activeSelectionSide}
+ selectionDepth={selectionDepth}
+ onChange={updateNestedValue}
+ onGridSelectionChange={onGridSelectionChange}
+ onNestedStackChange={onNestedStackChange}
+ />
+ ) : (
+ <HumanReviewObjectValueEditor
+ schema={activeNestedView.schema}
+ value={activeNestedValue}
+ originalValue={activeNestedValue}
+ readOnly={readOnly}
+ onChange={updateNestedValue}
+ />
+ )}
+ </div>
+ </div>
+ ) : null}
+ </div>
+ )
+}
+
+function HumanReviewObjectValueEditor({
+ schema,
value,
originalValue,
- active,
- activeFieldKey,
+ readOnly = false,
onChange,
- onFieldFocus,
- onUndo,
- onSetNull,
}: {
+ schema: ReviewFieldSchema
+ value: JsonValue
+ originalValue: JsonValue
+ readOnly?: boolean
+ onChange: (value: JsonValue) => void
+}) {
+ const propertyEntries = Object.entries(schema.properties ?? {})
+
+ if (!propertyEntries.length) {
+ return (
+ <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">
+ No properties
+ </div>
+ )
+ }
+
+ return (
+ <div className="space-y-2">
+ {propertyEntries.map(([propertyKey, propertySchema]) => (
+ <HumanReviewFieldCard
+ key={propertyKey}
+ field={{
+ key: propertyKey,
+ schema: propertySchema,
+ actual: getObjectValue(originalValue, propertyKey),
+ expected: getObjectValue(originalValue, propertyKey),
+ }}
+ value={getObjectValue(value, propertyKey)}
+ originalValue={getObjectValue(originalValue, propertyKey)}
+ readOnly={readOnly}
+ onChange={(childValue) =>
+ !readOnly &&
+ onChange(setObjectValue(value, propertyKey, childValue))
+ }
+ onUndo={() =>
+ !readOnly &&
+ onChange(
+ setObjectValue(
+ value,
+ propertyKey,
+ getObjectValue(originalValue, propertyKey)
+ )
+ )
+ }
+ onSetNull={() =>
+ !readOnly && onChange(setObjectValue(value, propertyKey, null))
+ }
+ />
+ ))}
+ </div>
+ )
+}
+
+type HumanReviewFieldCardProps = {
field: ReviewField
value: JsonValue
originalValue: JsonValue
active?: boolean
activeFieldKey?: string
+ readOnly?: boolean
onChange: (value: JsonValue) => void
onFieldFocus?: (field: ReviewField) => void
onUndo: () => void
onSetNull: () => void
-}) {
+}
+
+function areHumanReviewFieldCardPropsEqual(
+ previous: HumanReviewFieldCardProps,
+ next: HumanReviewFieldCardProps
+) {
+ return (
+ previous.field === next.field &&
+ Object.is(previous.value, next.value) &&
+ Object.is(previous.originalValue, next.originalValue) &&
+ previous.active === next.active &&
+ previous.activeFieldKey === next.activeFieldKey &&
+ previous.readOnly === next.readOnly &&
+ previous.onFieldFocus === next.onFieldFocus
+ )
+}
+
+const HumanReviewFieldCard = React.memo(
+ HumanReviewFieldCardBase,
+ areHumanReviewFieldCardPropsEqual
+)
+
+function HumanReviewFieldCardBase({
+ field,
+ value,
+ originalValue,
+ active,
+ activeFieldKey,
+ readOnly = false,
+ onChange,
+ onFieldFocus,
+ onUndo,
+ onSetNull,
+}: HumanReviewFieldCardProps) {
const modified = !jsonValuesEqual(value, originalValue)
const Icon = getFieldIcon(field.schema.type)
const propertyEntries = Object.entries(field.schema.properties ?? {})
+ const [syncedArrayNestedView, setSyncedArrayNestedView] =
+ React.useState<SyncedArrayNestedView>(EMPTY_SYNCED_ARRAY_NESTED_VIEW)
+ const [syncedArraySelection, setSyncedArraySelection] =
+ React.useState<SyncedArraySelection>(EMPTY_SYNCED_ARRAY_SELECTION)
+ const updateSyncedArrayNestedView = React.useCallback(
+ (stack: ArrayNestedView[], side: ArrayReviewSide) => {
+ setSyncedArrayNestedView({
+ activeSide: stack.length ? side : null,
+ stack,
+ })
+ },
+ []
+ )
+ const updateSyncedArraySelection = React.useCallback(
+ (gridSelection: GridSelection, side: ArrayReviewSide, depth: number) => {
+ setSyncedArraySelection({
+ activeSide: gridSelection.current ? side : null,
+ depth,
+ gridSelection,
+ })
+ },
+ []
+ )
return (
<div
@@ -421,7 +1444,7 @@ function HumanReviewFieldCard({
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
- {modified ? (
+ {!readOnly && modified ? (
<Tooltip>
<TooltipTrigger asChild>
<Button
@@ -438,21 +1461,23 @@ function HumanReviewFieldCard({
<TooltipContent>Revert changes</TooltipContent>
</Tooltip>
) : null}
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- className="text-muted-foreground"
- onClick={onSetNull}
- aria-label={`Set ${field.key} to null`}
- >
- <HugeiconsIcon icon={CancelCircleIcon} className="size-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>Set to NULL</TooltipContent>
- </Tooltip>
+ {!readOnly ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="text-muted-foreground"
+ onClick={onSetNull}
+ aria-label={`Set ${field.key} to null`}
+ >
+ <HugeiconsIcon icon={CancelCircleIcon} className="size-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Set to NULL</TooltipContent>
+ </Tooltip>
+ ) : null}
<div className="flex h-6 items-center gap-1 rounded-md border bg-muted/50 px-1.5 text-xs text-muted-foreground">
<HugeiconsIcon icon={Icon} className="size-3.5" />
{field.schema.type}
@@ -483,6 +1508,7 @@ function HumanReviewFieldCard({
originalValue={childField.expected}
active={childField.key === activeFieldKey}
activeFieldKey={activeFieldKey}
+ readOnly={readOnly}
onChange={(childValue) =>
onChange(setObjectValue(value, propertyKey, childValue))
}
@@ -505,6 +1531,38 @@ function HumanReviewFieldCard({
)}
</div>
</div>
+ ) : field.schema.type === "array" ? (
+ <div className="grid gap-2">
+ <HumanReviewArrayValueGrid
+ activeNestedSide={syncedArrayNestedView.activeSide}
+ activeSelectionSide={syncedArraySelection.activeSide}
+ label="Actual"
+ readOnly
+ schema={field.schema}
+ selectionDepth={syncedArraySelection.depth}
+ sharedGridSelection={syncedArraySelection.gridSelection}
+ sharedNestedStack={syncedArrayNestedView.stack}
+ value={field.actual}
+ viewSide="actual"
+ onGridSelectionChange={updateSyncedArraySelection}
+ onNestedStackChange={updateSyncedArrayNestedView}
+ />
+ <HumanReviewArrayValueGrid
+ activeNestedSide={syncedArrayNestedView.activeSide}
+ activeSelectionSide={syncedArraySelection.activeSide}
+ label="Expected"
+ readOnly={readOnly}
+ schema={field.schema}
+ selectionDepth={syncedArraySelection.depth}
+ sharedGridSelection={syncedArraySelection.gridSelection}
+ sharedNestedStack={syncedArrayNestedView.stack}
+ value={value}
+ viewSide="expected"
+ onChange={onChange}
+ onGridSelectionChange={updateSyncedArraySelection}
+ onNestedStackChange={updateSyncedArrayNestedView}
+ />
+ </div>
) : (
<div className="grid gap-2 sm:grid-cols-2">
<div className="rounded-md border bg-muted/30 p-2">
@@ -525,6 +1583,7 @@ function HumanReviewFieldCard({
Expected
</div>
<HumanReviewValueInput
+ readOnly={readOnly}
schema={field.schema}
value={getPrimitiveValue(value)}
onChange={onChange}
@@ -611,6 +1670,7 @@ export function HumanReviewPanel({
className?: string
onFieldFocus?: (field: ReviewField) => void
} = {}) {
+ const [activeTab, setActiveTab] = React.useState("form")
const actualValues = React.useMemo(
() => valuesFromFields(fields, "actual"),
[fields]
@@ -628,14 +1688,17 @@ export function HumanReviewPanel({
}, [initialExpectedValues])
const updateValue = React.useCallback((key: string, value: JsonValue) => {
- setExpected((current) => ({ ...current, [key]: value }))
+ setExpected((current) =>
+ Object.is(current[key], value) ? current : { ...current, [key]: value }
+ )
}, [])
const fieldCount = React.useMemo(() => countReviewFields(fields), [fields])
return (
<TooltipProvider delay={200}>
<Tabs
- defaultValue="form"
+ value={activeTab}
+ onValueChange={setActiveTab}
className={cn("flex h-[560px] flex-col gap-0 bg-background", className)}
>
<div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">
@@ -678,7 +1741,9 @@ export function HumanReviewPanel({
</ScrollArea>
</TabsContent>
<TabsContent value="json" className="min-h-0 flex-1">
- <JsonDiffView actual={actualValues} expected={expected} />
+ {activeTab === "json" ? (
+ <JsonDiffView actual={actualValues} expected={expected} />
+ ) : null}
</TabsContent>
</Tabs>
</TooltipProvider>
diff --git a/apps/v4/registry/new-york-v4/blocks/ocr-blocks.tsx b/apps/v4/registry/new-york-v4/blocks/ocr-blocks.tsx
index 2b7113f..27d650d 100644
--- a/apps/v4/registry/new-york-v4/blocks/ocr-blocks.tsx
+++ b/apps/v4/registry/new-york-v4/blocks/ocr-blocks.tsx
@@ -31,7 +31,7 @@ const OCR_BLOCKS: OcrBlock[] = [
{
id: "title",
kind: "Heading",
- text: "**Attention Is All You Need**",
+ text: "# Attention Is All You Need",
page: 1,
confidence: 0.99,
icon: Heading01Icon,
@@ -93,34 +93,61 @@ function polygonToArea(polygon: OcrBlock["polygon"]) {
function OcrBlockMarkdown({ text }: { text: string }) {
return (
- <ReactMarkdown
- components={{
- p: ({ node: _node, ...props }) => <p className="my-0" {...props} />,
- strong: ({ node: _node, ...props }) => (
- <strong className="font-semibold text-foreground" {...props} />
- ),
- ul: ({ node: _node, ...props }) => (
- <ul className="my-0 list-disc space-y-0.5 pl-4" {...props} />
- ),
- li: ({ node: _node, ...props }) => <li className="pl-0.5" {...props} />,
- table: ({ node: _node, ...props }) => (
- <div className="overflow-hidden rounded-md border bg-background">
- <table className="w-full border-collapse text-xs" {...props} />
- </div>
- ),
- th: ({ node: _node, ...props }) => (
- <th
- className="border-b bg-muted px-2 py-1 text-left font-medium"
- {...props}
- />
- ),
- td: ({ node: _node, ...props }) => (
- <td className="border-t px-2 py-1" {...props} />
- ),
- }}
- >
- {text}
- </ReactMarkdown>
+ <div className="space-y-1 text-sm leading-5 text-foreground/90">
+ <ReactMarkdown
+ components={{
+ h1: ({ node: _node, ...props }) => (
+ <h1
+ className="my-0 text-base leading-5 font-semibold text-foreground"
+ {...props}
+ />
+ ),
+ h2: ({ node: _node, ...props }) => (
+ <h2
+ className="my-0 text-[15px] leading-5 font-semibold text-foreground"
+ {...props}
+ />
+ ),
+ h3: ({ node: _node, ...props }) => (
+ <h3
+ className="my-0 text-sm leading-5 font-semibold text-foreground"
+ {...props}
+ />
+ ),
+ p: ({ node: _node, ...props }) => (
+ <p className="my-0 text-[13px] leading-5" {...props} />
+ ),
+ strong: ({ node: _node, ...props }) => (
+ <strong className="font-semibold text-foreground" {...props} />
+ ),
+ em: ({ node: _node, ...props }) => (
+ <em className="text-foreground" {...props} />
+ ),
+ ul: ({ node: _node, ...props }) => (
+ <ul className="my-0 list-disc space-y-0.5 pl-4" {...props} />
+ ),
+ li: ({ node: _node, ...props }) => (
+ <li className="pl-0.5 text-[13px] leading-5" {...props} />
+ ),
+ table: ({ node: _node, ...props }) => (
+ <div className="overflow-hidden rounded-md border bg-background">
+ <table className="w-full border-collapse text-xs" {...props} />
+ </div>
+ ),
+ th: ({ node: _node, ...props }) => (
+ <th
+ className="border-b bg-muted px-2 py-1 text-left font-medium"
+ {...props}
+ />
+ ),
+ td: ({ node: _node, ...props }) => (
+ <td className="border-t px-2 py-1" {...props} />
+ ),
+ }}
+ >
+ {text}
+ </ReactMarkdown>
+ </div>
)
}