TypeScript
Synchronize v4 component sources and registry
Andrew Luocab4629b2003
diff --git a/apps/v4/components/bounding-box-citations-docs.tsx b/apps/v4/components/bounding-box-citations-docs.tsxindex 875198e..65d514b 100644--- a/apps/v4/components/bounding-box-citations-docs.tsx+++ b/apps/v4/components/bounding-box-citations-docs.tsx@@ -3024,7 +3024,7 @@ export function HumanReviewExample() {}`const humanReviewSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n DataEditor,\n emptyGridSelection,\n GridCellKind,\n TextCellEntry,\n type EditableGridCell,\n type GridCell,\n type GridColumn,\n type GridMouseEventArgs,\n type GridSelection,\n type Item,\n type NumberCell,\n type ProvideEditorComponent,\n type Rectangle,\n type TextCell,\n type Theme,\n} from "@glideapps/glide-data-grid"\nimport {\n ArrowLeft01Icon,\n CancelCircleIcon,\n InputNumericIcon,\n InputTextIcon,\n SecondBracketIcon,\n SourceCodeSquareIcon,\n TextCheckIcon,\n Undo02Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { Virtualizer as DiffsVirtualizer } from "@pierre/diffs"\nimport {\n File,\n MultiFileDiff,\n VirtualizerContext,\n WorkerPoolContextProvider,\n type VirtualFileMetrics,\n type WorkerInitializationRenderOptions,\n type WorkerPoolOptions,\n} from "@pierre/diffs/react"\nimport { flushSync } from "react-dom"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport { Input } from "@/components/ui/input"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/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?: ReviewLocation\n metadataPath?: string\n}\n\nexport type ReviewLocation = {\n page: number\n area: HighlightArea\n}\n\nexport type ReviewCitation = {\n page: number\n polygon?: Array<{ x: number; y: number }>\n pageWidth: number\n pageHeight: number\n}\n\nexport type ReviewMetadataEntry = {\n citations?: ReviewCitation[]\n}\n\nfunction ScrollAreaVirtualizer({\n children,\n className,\n contentClassName,\n contentStyle,\n scrollFade = true,\n}: {\n children: React.ReactNode\n className?: string\n contentClassName?: string\n contentStyle?: React.CSSProperties\n scrollFade?: boolean\n}) {\n const [virtualizer] = React.useState(() =>\n typeof window !== "undefined" ? new DiffsVirtualizer() : undefined\n )\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const contentRef = React.useRef<HTMLDivElement | null>(null)\n const syncVirtualizer = React.useCallback(() => {\n if (!virtualizer) return\n\n const viewport = viewportRef.current\n const content = contentRef.current\n\n if (viewport && content) {\n virtualizer.setup(viewport, content)\n return\n }\n\n virtualizer.cleanUp()\n }, [virtualizer])\n const setViewportRef = React.useCallback(\n (node: HTMLDivElement | null) => {\n viewportRef.current = node\n syncVirtualizer()\n },\n [syncVirtualizer]\n )\n const setContentRef = React.useCallback(\n (node: HTMLDivElement | null) => {\n contentRef.current = node\n syncVirtualizer()\n },\n [syncVirtualizer]\n )\n\n React.useEffect(() => {\n return () => virtualizer?.cleanUp()\n }, [virtualizer])\n\n return (\n <VirtualizerContext.Provider value={virtualizer}>\n <ScrollArea\n className={className}\n scrollFade={scrollFade}\n scrollbarOverflowOnly\n viewportRef={setViewportRef}\n >\n <div\n ref={setContentRef}\n className={contentClassName}\n style={contentStyle}\n >\n {children}\n </div>\n </ScrollArea>\n </VirtualizerContext.Provider>\n )\n}\n\nconst DEFAULT_ZOOM = 1\nconst REVIEW_HIGHLIGHT_STYLE =\n "border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_10%)]"\n\nconst CODE_FILE_THEME = {\n "--diffs-light-bg": "var(--color-code)",\n "--diffs-dark-bg": "var(--color-code)",\n "--diffs-light": "var(--color-code-foreground)",\n "--diffs-dark": "var(--color-code-foreground)",\n "--diffs-bg-context-override": "var(--color-code)",\n "--diffs-bg-context-gutter-override": "var(--color-code)",\n "--diffs-bg-buffer-override": "var(--color-code)",\n "--diffs-fg-number-override": "var(--color-muted-foreground)",\n "--diffs-font-size": "0.8rem",\n "--diffs-line-height": "1.625",\n} as React.CSSProperties\n\nconst CODE_FONT_SIZE_PX = 12.8\nconst CODE_LINE_HEIGHT_PX = CODE_FONT_SIZE_PX * 1.625\n\nconst CODE_VIRTUAL_FILE_METRICS = {\n hunkLineCount: 50,\n lineHeight: CODE_LINE_HEIGHT_PX,\n diffHeaderHeight: 44,\n spacing: 8,\n paddingTop: 0,\n paddingBottom: 8,\n} satisfies VirtualFileMetrics\n\nconst CODE_HIGHLIGHTER_OPTIONS = {\n theme: {\n light: "pierre-light-soft",\n dark: "pierre-dark-soft",\n },\n langs: ["json"],\n} satisfies WorkerInitializationRenderOptions\n\nconst CODE_WORKER_POOL_OPTIONS = {\n workerFactory: () =>\n new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), {\n type: "module",\n }),\n} satisfies WorkerPoolOptions\n\nfunction readIsDarkTheme() {\n return (\n typeof document !== "undefined" &&\n document.documentElement.classList.contains("dark")\n )\n}\n\n// A single shared MutationObserver backs every consumer. Each grid previously\n// created its own observer (two, via useHumanReviewGridTheme), so opening a\n// nested array view spun up and tore down several observers at once.\nconst darkThemeListeners = new Set<(isDark: boolean) => void>()\nlet darkThemeObserver: MutationObserver | null = null\nlet sharedIsDarkTheme = false\n\nfunction ensureDarkThemeObserver() {\n if (\n darkThemeObserver ||\n typeof document === "undefined" ||\n typeof MutationObserver === "undefined"\n ) {\n return\n }\n\n sharedIsDarkTheme = readIsDarkTheme()\n darkThemeObserver = new MutationObserver(() => {\n const nextIsDark = readIsDarkTheme()\n if (nextIsDark === sharedIsDarkTheme) return\n\n sharedIsDarkTheme = nextIsDark\n darkThemeListeners.forEach((listener) => listener(nextIsDark))\n })\n darkThemeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ["class"],\n })\n}\n\nfunction useIsDarkTheme() {\n const [isDark, setIsDark] = React.useState(readIsDarkTheme)\n\n React.useEffect(() => {\n ensureDarkThemeObserver()\n setIsDark(sharedIsDarkTheme)\n darkThemeListeners.add(setIsDark)\n\n return () => {\n darkThemeListeners.delete(setIsDark)\n if (darkThemeListeners.size === 0 && darkThemeObserver) {\n darkThemeObserver.disconnect()\n darkThemeObserver = null\n }\n }\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\nexport const REVIEW_FIELDS: ReviewField[] = [\n {\n key: "statement_period",\n schema: {\n type: "string",\n title: "Statement period",\n description: "Date range covered by the bank statement.",\n },\n actual: "Jan 1-31, 2026",\n expected: "January 1-31, 2026",\n location: {\n page: 1,\n area: { left: 31, top: 30, width: 40, height: 5.8 },\n },\n },\n {\n key: "transactions",\n schema: {\n type: "array",\n title: "Transactions",\n description: "Posted account activity during the statement period.",\n items: {\n type: "object",\n properties: {\n date: {\n type: "string",\n title: "Date",\n },\n description: {\n type: "string",\n title: "Description",\n },\n amount: {\n type: "number",\n title: "Amount",\n },\n category: {\n type: "string",\n title: "Category",\n },\n merchant: {\n type: "object",\n title: "Merchant",\n properties: {\n name: {\n type: "string",\n title: "Name",\n },\n city: {\n type: "string",\n title: "City",\n },\n risk_level: {\n type: "string",\n title: "Risk level",\n },\n },\n },\n tags: {\n type: "array",\n title: "Tags",\n items: {\n type: "string",\n title: "Tag",\n },\n },\n },\n },\n },\n actual: [\n {\n date: "2026-01-03",\n description: "ACH CREDIT PAYROLL",\n amount: 4250,\n category: "Deposit",\n merchant: {\n name: "Acme Payroll",\n city: "New York",\n risk_level: "low",\n },\n tags: ["payroll", "recurring"],\n },\n {\n date: "2026-01-12",\n description: "POS PURCHASE GROCERY MART",\n amount: -86.42,\n category: "Debit",\n merchant: {\n name: "Grocery Mart",\n city: "Brooklyn",\n risk_level: "medium",\n },\n tags: ["card", "groceries"],\n },\n ],\n expected: [\n {\n date: "2026-01-03",\n description: "ACH CREDIT PAYROLL",\n amount: 4250,\n category: "Deposit",\n merchant: {\n name: "Acme Payroll",\n city: "New York",\n risk_level: "low",\n },\n tags: ["payroll", "recurring"],\n },\n {\n date: "2026-01-12",\n description: "POS PURCHASE GROCERY MART",\n amount: -68.42,\n category: "Debit",\n merchant: {\n name: "Grocery Mart",\n city: "Brooklyn",\n risk_level: "low",\n },\n tags: ["card", "groceries", "needs_review"],\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: "ending_balance",\n schema: {\n type: "number",\n title: "Ending balance",\n description: "Final account balance at the end of the statement period.",\n },\n actual: 12840.18,\n expected: 12858.18,\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "overdraft_protection_enabled",\n schema: {\n type: "boolean",\n title: "Overdraft protection enabled",\n description: "Whether overdraft protection is enabled for the account.",\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: "account_details",\n schema: {\n type: "object",\n title: "Account details",\n description: "Account owner and identifying details from the statement.",\n properties: {\n holder_name: {\n type: "string",\n title: "Holder name",\n },\n account_last_four: {\n type: "string",\n title: "Account last four",\n },\n account_type: {\n type: "string",\n title: "Account type",\n },\n mailing_address: {\n type: "object",\n title: "Mailing address",\n properties: {\n line_1: {\n type: "string",\n title: "Line 1",\n },\n city: {\n type: "string",\n title: "City",\n },\n state: {\n type: "string",\n title: "State",\n },\n },\n },\n linked_accounts: {\n type: "array",\n title: "Linked accounts",\n items: {\n type: "object",\n properties: {\n nickname: {\n type: "string",\n title: "Nickname",\n },\n last_four: {\n type: "string",\n title: "Last four",\n },\n },\n },\n },\n },\n },\n actual: {\n holder_name: "Jordan Lee",\n account_last_four: "4821",\n account_type: "Checking",\n mailing_address: {\n line_1: "42 Market Street",\n city: "Brooklyn",\n state: "NY",\n },\n linked_accounts: [\n {\n nickname: "Operations reserve",\n last_four: "1842",\n },\n ],\n },\n expected: {\n holder_name: "Jordan Lee",\n account_last_four: "4821",\n account_type: "Premier Checking",\n mailing_address: {\n line_1: "42 Market Street",\n city: "New York",\n state: "NY",\n },\n linked_accounts: [\n {\n nickname: "Operations reserve",\n last_four: "1842",\n },\n {\n nickname: "Payroll sweep",\n last_four: "9174",\n },\n ],\n },\n },\n]\n\nfunction getCitationLocation(\n citation: ReviewCitation\n): ReviewLocation | undefined {\n const polygon = citation.polygon\n if (!polygon?.length || !citation.pageWidth || !citation.pageHeight) {\n return undefined\n }\n\n const xs = polygon.map((point) => point.x)\n const ys = polygon.map((point) => point.y)\n const left = Math.min(...xs)\n const top = Math.min(...ys)\n const right = Math.max(...xs)\n const bottom = Math.max(...ys)\n\n return {\n page: citation.page,\n area: {\n left: (left / citation.pageWidth) * 100,\n top: (top / citation.pageHeight) * 100,\n width: ((right - left) / citation.pageWidth) * 100,\n height: ((bottom - top) / citation.pageHeight) * 100,\n },\n }\n}\n\nexport function getMetadataLocation(\n metadata: Record<string, ReviewMetadataEntry> | undefined,\n metadataPath: string | undefined\n) {\n if (!metadata || !metadataPath) return undefined\n\n const citation = metadata[metadataPath]?.citations?.find(\n (candidate) => candidate.polygon?.length\n )\n\n return citation ? getCitationLocation(citation) : undefined\n}\n\nexport function getReviewFieldLocation(\n field: ReviewField | undefined,\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n) {\n if (!field) return undefined\n\n return (\n field.location ??\n resolveLocation?.(field.metadataPath ?? field.key) ??\n undefined\n )\n}\n\nexport function getReviewLocationKey(location: ReviewLocation | undefined) {\n if (!location) return null\n\n const { area } = location\n return [location.page, area.left, area.top, area.width, area.height].join(":")\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\nexport function 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 metadataPath: `${field.metadataPath ?? field.key}.${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 areGridRangesEqual(\n left: Readonly<Rectangle> | undefined,\n right: Readonly<Rectangle> | undefined\n) {\n return (\n left === right ||\n (left !== undefined &&\n right !== undefined &&\n left.x === right.x &&\n left.y === right.y &&\n left.width === right.width &&\n left.height === right.height)\n )\n}\n\nfunction areGridRangeStacksEqual(\n left: readonly Readonly<Rectangle>[] | undefined,\n right: readonly Readonly<Rectangle>[] | undefined\n) {\n if (left === right) return true\n if (!left || !right || left.length !== right.length) return false\n\n return left.every((range, index) => areGridRangesEqual(range, right[index]))\n}\n\nfunction areGridSelectionsEqual(left: GridSelection, right: GridSelection) {\n const leftCurrent = left.current\n const rightCurrent = right.current\n\n return (\n leftCurrent?.cell[0] === rightCurrent?.cell[0] &&\n leftCurrent?.cell[1] === rightCurrent?.cell[1] &&\n areGridRangesEqual(leftCurrent?.range, rightCurrent?.range) &&\n areGridRangeStacksEqual(\n leftCurrent?.rangeStack,\n rightCurrent?.rangeStack\n ) &&\n left.columns.equals(right.columns) &&\n left.rows.equals(right.rows)\n )\n}\n\nfunction getGridSelectionRanges(selection: GridSelection | undefined) {\n const current = selection?.current\n if (!current) return []\n\n return [...(current.rangeStack ?? []), current.range]\n}\n\nfunction areArrayNestedViewsEqual(\n left: ArrayNestedView[],\n right: ArrayNestedView[]\n) {\n if (left === right) return true\n if (left.length !== right.length) return false\n\n return left.every((view, index) => {\n const other = right[index]\n\n return (\n view.rowIndex === other?.rowIndex &&\n view.columnId === other.columnId &&\n view.title === other.title &&\n view.schema === other.schema &&\n Object.is(view.value, other.value)\n )\n })\n}\n\ntype HumanReviewOverlayCell = TextCell | NumberCell\n\ntype HumanReviewTextOverlayEditorProps = React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n> & {\n overlayOpenRef: React.RefObject<boolean>\n readOnly?: boolean\n}\n\nfunction HumanReviewTextOverlayEditor({\n isHighlighted,\n onFinishedEditing,\n overlayOpenRef,\n readOnly = false,\n validatedSelection,\n value,\n}: HumanReviewTextOverlayEditorProps) {\n const initialValue =\n value.kind === GridCellKind.Number ? value.displayData : value.data\n const [entryValue, setEntryValue] = React.useState(initialValue)\n const latestValueRef = React.useRef(initialValue)\n const finishedRef = React.useRef(false)\n\n const finishEditing = React.useCallback(\n (\n shouldSave: boolean,\n movement: readonly [-1 | 0 | 1, -1 | 0 | 1] = [0, 0]\n ) => {\n if (finishedRef.current) return\n\n finishedRef.current = true\n overlayOpenRef.current = false\n\n if (!shouldSave || readOnly) {\n onFinishedEditing(undefined, movement)\n return\n }\n\n if (value.kind === GridCellKind.Number) {\n const numericValue = Number(latestValueRef.current)\n\n onFinishedEditing(\n {\n ...value,\n data: Number.isFinite(numericValue) ? numericValue : value.data,\n displayData: latestValueRef.current,\n },\n movement\n )\n return\n }\n\n onFinishedEditing(\n {\n ...value,\n data: latestValueRef.current,\n displayData: latestValueRef.current,\n },\n movement\n )\n },\n [onFinishedEditing, overlayOpenRef, readOnly, value]\n )\n\n const handleEntryChange = React.useCallback(\n (event: React.ChangeEvent<HTMLTextAreaElement>) => {\n event.stopPropagation()\n latestValueRef.current = event.target.value\n setEntryValue(event.target.value)\n },\n []\n )\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n event.stopPropagation()\n\n if (event.key === "Escape") {\n event.preventDefault()\n finishEditing(false)\n return\n }\n\n if (event.key === "Tab") {\n event.preventDefault()\n finishEditing(true, [event.shiftKey ? -1 : 1, 0])\n return\n }\n\n if (event.key === "Enter" && !event.shiftKey) {\n event.preventDefault()\n finishEditing(true, [0, 1])\n }\n },\n [finishEditing]\n )\n\n React.useEffect(() => {\n overlayOpenRef.current = true\n\n return () => {\n overlayOpenRef.current = false\n }\n }, [overlayOpenRef])\n\n React.useEffect(() => {\n const handlePointerOutside = (event: PointerEvent | MouseEvent) => {\n const input = document.querySelector<HTMLTextAreaElement>(".gdg-input")\n const overlayRoot = input?.closest(".gdg-clip-region")\n\n if (!overlayRoot || overlayRoot.contains(event.target as Node | null)) {\n return\n }\n\n finishEditing(true)\n }\n\n document.addEventListener("pointerdown", handlePointerOutside, true)\n document.addEventListener("contextmenu", handlePointerOutside, true)\n\n return () => {\n document.removeEventListener("pointerdown", handlePointerOutside, true)\n document.removeEventListener("contextmenu", handlePointerOutside, true)\n }\n }, [finishEditing])\n\n return (\n <TextCellEntry\n autoFocus={!readOnly}\n disabled={readOnly}\n highlight={isHighlighted}\n value={entryValue}\n validatedSelection={validatedSelection}\n altNewline\n onChange={handleEntryChange}\n onKeyDown={handleKeyDown}\n />\n )\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\nexport type HumanReviewTheme = "light" | "dark"\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 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 metadataPath,\n onChange,\n onGridSelectionChange,\n onLocationHover,\n onNestedStackChange,\n resolveArrayItemMetadataPath,\n resolveLocation,\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 metadataPath?: string\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 onLocationHover?: (location?: ReviewLocation) => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\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 fastTextOverlayOpenRef = React.useRef(false)\n const nestedStack = sharedNestedStack ?? localNestedStack\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 mirroredHighlightRegions = React.useMemo<\n React.ComponentProps<typeof DataEditor>["highlightRegions"]\n >(() => {\n if (\n !activeSelectionSide ||\n activeSelectionSide === viewSide ||\n selectionDepth !== nestedStackBaseDepth\n ) {\n return undefined\n }\n\n const ranges = getGridSelectionRanges(sharedGridSelection)\n if (!ranges.length) return undefined\n\n return ranges.map((range) => ({\n color: mirroredCellBackground,\n range,\n style: "dashed" as const,\n }))\n }, [\n activeSelectionSide,\n mirroredCellBackground,\n nestedStackBaseDepth,\n selectionDepth,\n sharedGridSelection,\n viewSide,\n ])\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 flushSync(() => {\n setLocalGridSelection((current) =>\n areGridSelectionsEqual(current, selection) ? current : selection\n )\n })\n\n if (onGridSelectionChange) {\n if (\n activeSelectionSide === viewSide &&\n sharedGridSelection &&\n areGridSelectionsEqual(sharedGridSelection, selection)\n ) {\n return\n }\n\n React.startTransition(() => {\n onGridSelectionChange(selection, viewSide, nestedStackBaseDepth)\n })\n return\n }\n },\n [\n activeSelectionSide,\n nestedStackBaseDepth,\n onGridSelectionChange,\n sharedGridSelection,\n viewSide,\n ]\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 nestedCellTheme: Partial<Theme> | undefined = matchedNestedCell\n ? {\n bgCell: isMirroredNestedTarget\n ? mirroredCellBackground\n : selectedCellBackground,\n textDark: blueCellText,\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 ...(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 }\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: true,\n readonly: false,\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: true,\n readonly: false,\n }\n },\n [\n activeNestedView,\n blueCellText,\n columns,\n isMirroredNestedTarget,\n itemSchema,\n mirroredCellBackground,\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 const provideEditor = React.useCallback<\n NonNullable<React.ComponentProps<typeof DataEditor>["provideEditor"]>\n >(\n (cell) => {\n if (\n cell.kind !== GridCellKind.Text &&\n cell.kind !== GridCellKind.Number\n ) {\n return undefined\n }\n\n return {\n editor: (props) => {\n if (\n props.value.kind !== GridCellKind.Text &&\n props.value.kind !== GridCellKind.Number\n ) {\n return null\n }\n\n return (\n <HumanReviewTextOverlayEditor\n {...(props as React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n >)}\n overlayOpenRef={fastTextOverlayOpenRef}\n readOnly={readOnly}\n />\n )\n },\n }\n },\n [readOnly]\n )\n const handleOutsideClick = React.useCallback(\n () => !fastTextOverlayOpenRef.current,\n []\n )\n const handleItemHovered = React.useCallback(\n (args: GridMouseEventArgs) => {\n if (!onLocationHover || !resolveLocation || !metadataPath) return\n\n if (args.kind !== "cell") {\n onLocationHover(undefined)\n return\n }\n\n const [col, row] = args.location\n const column = columns[col]\n const rowValue = rows[row]\n if (!column || rowValue === undefined) {\n onLocationHover(undefined)\n return\n }\n\n const columnId = String(column.id ?? "value")\n const rowMetadataPath = resolveArrayItemMetadataPath\n ? resolveArrayItemMetadataPath(metadataPath, row, rowValue)\n : `${metadataPath}[${row}]`\n if (!rowMetadataPath) {\n onLocationHover(undefined)\n return\n }\n\n const propertyMetadataPath =\n itemSchema.type === "object"\n ? `${rowMetadataPath}.${columnId}`\n : rowMetadataPath\n\n onLocationHover(\n resolveLocation(propertyMetadataPath) ??\n resolveLocation(rowMetadataPath)\n )\n },\n [\n columns,\n itemSchema.type,\n metadataPath,\n onLocationHover,\n resolveArrayItemMetadataPath,\n resolveLocation,\n rows,\n ]\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 onMouseLeave={() => onLocationHover?.(undefined)}\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 gridSelection={localGridSelection}\n highlightRegions={mirroredHighlightRegions}\n onCellEdited={updateCellValue}\n onCellActivated={openNestedCell}\n onGridSelectionChange={handleGridSelectionChange}\n onItemHovered={handleItemHovered}\n provideEditor={provideEditor}\n isOutsideClick={handleOutsideClick}\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 resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\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 showExpected?: boolean\n onChange: (value: JsonValue) => void\n onFieldFocus?: (field: ReviewField) => void\n onLocationHover?: (location?: ReviewLocation) => void\n onUndo: () => void\n onSetNull: () => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\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.showExpected === next.showExpected &&\n previous.onFieldFocus === next.onFieldFocus &&\n previous.onLocationHover === next.onLocationHover &&\n previous.resolveArrayItemMetadataPath ===\n next.resolveArrayItemMetadataPath &&\n previous.resolveLocation === next.resolveLocation\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 showExpected = true,\n onChange,\n onFieldFocus,\n onLocationHover,\n onUndo,\n onSetNull,\n resolveArrayItemMetadataPath,\n resolveLocation,\n}: HumanReviewFieldCardProps) {\n const isExpectedEditable = showExpected && !readOnly\n const modified = showExpected && !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 const activeSide = stack.length ? side : null\n\n setSyncedArrayNestedView((current) =>\n current.activeSide === activeSide &&\n areArrayNestedViewsEqual(current.stack, stack)\n ? current\n : {\n activeSide,\n stack,\n }\n )\n },\n []\n )\n const updateSyncedArraySelection = React.useCallback(\n (gridSelection: GridSelection, side: ArrayReviewSide, depth: number) => {\n const activeSide = gridSelection.current ? side : null\n\n setSyncedArraySelection((current) =>\n current.activeSide === activeSide &&\n current.depth === depth &&\n areGridSelectionsEqual(current.gridSelection, gridSelection)\n ? current\n : {\n activeSide,\n depth,\n gridSelection,\n }\n )\n },\n []\n )\n const focusAndHoverField = React.useCallback(() => {\n onFieldFocus?.(field)\n onLocationHover?.(getReviewFieldLocation(field, resolveLocation))\n }, [field, onFieldFocus, onLocationHover, resolveLocation])\n\n return (\n <div\n tabIndex={0}\n onFocusCapture={focusAndHoverField}\n onMouseEnter={focusAndHoverField}\n onMouseLeave={() => onLocationHover?.(undefined)}\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",\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 {isExpectedEditable && 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 {isExpectedEditable ? (\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 metadataPath: `${field.metadataPath ?? field.key}.${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 showExpected={showExpected}\n onChange={(childValue) =>\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onFieldFocus={onFieldFocus}\n onLocationHover={onLocationHover}\n onUndo={() =>\n onChange(\n setObjectValue(value, propertyKey, childField.expected)\n )\n }\n onSetNull={() =>\n onChange(setObjectValue(value, propertyKey, null))\n }\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\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 metadataPath={field.metadataPath ?? field.key}\n readOnly\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\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 onLocationHover={onLocationHover}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n {showExpected ? (\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Expected"\n metadataPath={field.metadataPath ?? field.key}\n readOnly={readOnly}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\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 onLocationHover={onLocationHover}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n ) : null}\n </div>\n ) : (\n <div className={cn("grid gap-2", showExpected && "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 {showExpected ? (\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 ) : null}\n </div>\n )}\n </div>\n )\n}\n\nexport function HumanReviewHighlight({\n location,\n}: {\n location: ReviewLocation\n}) {\n const area = location.area\n\n return (\n <div\n className={cn(\n "pointer-events-none absolute z-10 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 theme = "light",\n}: {\n actual: JsonObject\n expected: JsonObject\n theme?: HumanReviewTheme\n}) {\n const oldFile = React.useMemo(\n () => ({\n name: "actual.json",\n contents: formatJson(actual),\n lang: "json",\n }),\n [actual]\n )\n const newFile = React.useMemo(\n () => ({\n name: "expected.json",\n contents: formatJson(expected),\n lang: "json",\n }),\n [expected]\n )\n\n return (\n <ScrollAreaVirtualizer\n className="h-full bg-surface/60"\n contentClassName="min-w-full"\n >\n <div className="bounding-box-citations-diff h-full text-xs">\n <MultiFileDiff\n className="block min-w-full"\n oldFile={oldFile}\n newFile={newFile}\n options={{\n diffStyle: "split",\n disableFileHeader: true,\n diffIndicators: "bars",\n hunkSeparators: "line-info-basic",\n overflow: "wrap",\n themeType: theme,\n theme: {\n light: "pierre-light-soft",\n dark: "pierre-dark-soft",\n },\n }}\n />\n </div>\n </ScrollAreaVirtualizer>\n )\n}\n\nexport function JsonCodeView({\n name = "actual.json",\n theme = "light",\n value,\n}: {\n name?: string\n theme?: HumanReviewTheme\n value: JsonValue\n}) {\n const file = React.useMemo(() => {\n const contents = formatJson(value)\n\n return {\n name,\n contents,\n lang: "json" as const,\n cacheKey: contents,\n }\n }, [name, value])\n\n return (\n <div\n data-rehype-pretty-code-figure\n className="relative m-0! h-full overflow-hidden rounded-none! bg-code text-code-foreground"\n >\n <WorkerPoolContextProvider\n poolOptions={CODE_WORKER_POOL_OPTIONS}\n highlighterOptions={CODE_HIGHLIGHTER_OPTIONS}\n >\n <ScrollAreaVirtualizer\n key={`${file.cacheKey}:${theme}`}\n className="h-full min-w-0"\n contentClassName="min-w-full"\n >\n <File\n key={`${file.cacheKey}:${theme}`}\n className="block min-w-full"\n file={file}\n metrics={CODE_VIRTUAL_FILE_METRICS}\n style={CODE_FILE_THEME}\n options={{\n disableFileHeader: true,\n overflow: "scroll",\n themeType: theme,\n theme: {\n light: "pierre-light-soft",\n dark: "pierre-dark-soft",\n },\n }}\n />\n </ScrollAreaVirtualizer>\n </WorkerPoolContextProvider>\n </div>\n )\n}\n\nexport function HumanReviewPanel({\n fields = REVIEW_FIELDS,\n activeFieldKey,\n className,\n onFieldFocus,\n onLocationHover,\n resolveArrayItemMetadataPath,\n resolveLocation,\n showExpected = true,\n theme = "light",\n}: {\n fields?: ReviewField[]\n activeFieldKey?: string\n className?: string\n onFieldFocus?: (field: ReviewField) => void\n onLocationHover?: (location?: ReviewLocation) => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n showExpected?: boolean\n theme?: HumanReviewTheme\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\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>\n <TabsContent value="form" keepMounted 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={\n showExpected ? (expected[field.key] ?? null) : field.actual\n }\n originalValue={showExpected ? field.expected : field.actual}\n active={\n field.key === activeFieldKey ||\n activeFieldKey?.startsWith(`${field.key}.`)\n }\n activeFieldKey={activeFieldKey}\n showExpected={showExpected}\n onChange={(value) => updateValue(field.key, value)}\n onFieldFocus={onFieldFocus}\n onLocationHover={onLocationHover}\n onUndo={() => updateValue(field.key, field.expected)}\n onSetNull={() => updateValue(field.key, null)}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n ))}\n </div>\n </ScrollArea>\n </TabsContent>\n <TabsContent value="json" keepMounted className="min-h-0 flex-1">\n {showExpected ? (\n <JsonDiffView\n actual={actualValues}\n expected={expected}\n theme={theme}\n />\n ) : (\n <JsonCodeView value={actualValues} theme={theme} />\n )}\n </TabsContent>\n </Tabs>\n </TooltipProvider>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n DataEditor,\n emptyGridSelection,\n GridCellKind,\n TextCellEntry,\n type EditableGridCell,\n type GridCell,\n type GridColumn,\n type GridMouseEventArgs,\n type GridSelection,\n type Item,\n type NumberCell,\n type ProvideEditorComponent,\n type Rectangle,\n type TextCell,\n type Theme,\n} from "@glideapps/glide-data-grid"\nimport { Virtualizer as DiffsVirtualizer } from "@pierre/diffs"\nimport {\n File,\n MultiFileDiff,\n VirtualizerContext,\n WorkerPoolContextProvider,\n type VirtualFileMetrics,\n type WorkerInitializationRenderOptions,\n type WorkerPoolOptions,\n} from "@pierre/diffs/react"\nimport { flushSync } from "react-dom"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport { Input } from "@/components/ui/input"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nimport "@glideapps/glide-data-grid/dist/index.css"\n\nfunction InputNumericGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Hash"\n tabler="IconNumber123"\n hugeicons="InputNumericIcon"\n phosphor="NumpadIcon"\n remixicon="RiHashtag"\n {...props}\n />\n )\n}\n\nfunction InputTextGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="TextCursorInput"\n tabler="IconForms"\n hugeicons="InputTextIcon"\n phosphor="TextboxIcon"\n remixicon="RiInputField"\n {...props}\n />\n )\n}\n\nfunction SecondBracketGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Brackets"\n tabler="IconBrackets"\n hugeicons="SecondBracketIcon"\n phosphor="BracketsSquareIcon"\n remixicon="RiBracketsLine"\n {...props}\n />\n )\n}\n\nfunction SourceCodeSquareGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="SquareCode"\n tabler="IconSourceCode"\n hugeicons="SourceCodeSquareIcon"\n phosphor="CodeIcon"\n remixicon="RiCodeBlock"\n {...props}\n />\n )\n}\n\nfunction TextCheckGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="CaptionsIcon"\n tabler="IconTextCaption"\n hugeicons="TextCheckIcon"\n phosphor="TextTIcon"\n remixicon="RiTextWrap"\n {...props}\n />\n )\n}\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?: ReviewLocation\n metadataPath?: string\n}\n\nexport type ReviewLocation = {\n page: number\n area: HighlightArea\n}\n\nexport type ReviewCitation = {\n page: number\n polygon?: Array<{ x: number; y: number }>\n pageWidth: number\n pageHeight: number\n}\n\nexport type ReviewMetadataEntry = {\n citations?: ReviewCitation[]\n}\n\nfunction ScrollAreaVirtualizer({\n children,\n className,\n contentClassName,\n contentStyle,\n scrollFade = true,\n}: {\n children: React.ReactNode\n className?: string\n contentClassName?: string\n contentStyle?: React.CSSProperties\n scrollFade?: boolean\n}) {\n const [virtualizer] = React.useState(() =>\n typeof window !== "undefined" ? new DiffsVirtualizer() : undefined\n )\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const contentRef = React.useRef<HTMLDivElement | null>(null)\n const syncVirtualizer = React.useCallback(() => {\n if (!virtualizer) return\n\n const viewport = viewportRef.current\n const content = contentRef.current\n\n if (viewport && content) {\n virtualizer.setup(viewport, content)\n return\n }\n\n virtualizer.cleanUp()\n }, [virtualizer])\n const setViewportRef = React.useCallback(\n (node: HTMLDivElement | null) => {\n viewportRef.current = node\n syncVirtualizer()\n },\n [syncVirtualizer]\n )\n const setContentRef = React.useCallback(\n (node: HTMLDivElement | null) => {\n contentRef.current = node\n syncVirtualizer()\n },\n [syncVirtualizer]\n )\n\n React.useEffect(() => {\n return () => virtualizer?.cleanUp()\n }, [virtualizer])\n\n return (\n <VirtualizerContext.Provider value={virtualizer}>\n <ScrollArea\n className={className}\n scrollFade={scrollFade}\n scrollbarOverflowOnly\n viewportRef={setViewportRef}\n >\n <div\n ref={setContentRef}\n className={contentClassName}\n style={contentStyle}\n >\n {children}\n </div>\n </ScrollArea>\n </VirtualizerContext.Provider>\n )\n}\n\nconst DEFAULT_ZOOM = 1\nconst REVIEW_HIGHLIGHT_STYLE =\n "border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_10%)]"\n\nconst CODE_FILE_THEME = {\n "--diffs-light-bg": "var(--color-code)",\n "--diffs-dark-bg": "var(--color-code)",\n "--diffs-light": "var(--color-code-foreground)",\n "--diffs-dark": "var(--color-code-foreground)",\n "--diffs-bg-context-override": "var(--color-code)",\n "--diffs-bg-context-gutter-override": "var(--color-code)",\n "--diffs-bg-buffer-override": "var(--color-code)",\n "--diffs-fg-number-override": "var(--color-muted-foreground)",\n "--diffs-font-size": "0.8rem",\n "--diffs-line-height": "1.625",\n} as React.CSSProperties\n\nconst CODE_FONT_SIZE_PX = 12.8\nconst CODE_LINE_HEIGHT_PX = CODE_FONT_SIZE_PX * 1.625\n\nconst CODE_VIRTUAL_FILE_METRICS = {\n hunkLineCount: 50,\n lineHeight: CODE_LINE_HEIGHT_PX,\n diffHeaderHeight: 44,\n spacing: 8,\n paddingTop: 0,\n paddingBottom: 8,\n} satisfies VirtualFileMetrics\n\nconst CODE_HIGHLIGHTER_OPTIONS = {\n theme: {\n light: "pierre-light-soft",\n dark: "pierre-dark-soft",\n },\n langs: ["json"],\n} satisfies WorkerInitializationRenderOptions\n\nconst CODE_WORKER_POOL_OPTIONS = {\n workerFactory: () =>\n new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), {\n type: "module",\n }),\n} satisfies WorkerPoolOptions\n\nfunction readIsDarkTheme() {\n return (\n typeof document !== "undefined" &&\n document.documentElement.classList.contains("dark")\n )\n}\n\n// A single shared MutationObserver backs every consumer. Each grid previously\n// created its own observer (two, via useHumanReviewGridTheme), so opening a\n// nested array view spun up and tore down several observers at once.\nconst darkThemeListeners = new Set<(isDark: boolean) => void>()\nlet darkThemeObserver: MutationObserver | null = null\nlet sharedIsDarkTheme = false\n\nfunction ensureDarkThemeObserver() {\n if (\n darkThemeObserver ||\n typeof document === "undefined" ||\n typeof MutationObserver === "undefined"\n ) {\n return\n }\n\n sharedIsDarkTheme = readIsDarkTheme()\n darkThemeObserver = new MutationObserver(() => {\n const nextIsDark = readIsDarkTheme()\n if (nextIsDark === sharedIsDarkTheme) return\n\n sharedIsDarkTheme = nextIsDark\n darkThemeListeners.forEach((listener) => listener(nextIsDark))\n })\n darkThemeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ["class"],\n })\n}\n\nfunction useIsDarkTheme() {\n const [isDark, setIsDark] = React.useState(readIsDarkTheme)\n\n React.useEffect(() => {\n ensureDarkThemeObserver()\n setIsDark(sharedIsDarkTheme)\n darkThemeListeners.add(setIsDark)\n\n return () => {\n darkThemeListeners.delete(setIsDark)\n if (darkThemeListeners.size === 0 && darkThemeObserver) {\n darkThemeObserver.disconnect()\n darkThemeObserver = null\n }\n }\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\nexport const REVIEW_FIELDS: ReviewField[] = [\n {\n key: "statement_period",\n schema: {\n type: "string",\n title: "Statement period",\n description: "Date range covered by the bank statement.",\n },\n actual: "Jan 1-31, 2026",\n expected: "January 1-31, 2026",\n location: {\n page: 1,\n area: { left: 31, top: 30, width: 40, height: 5.8 },\n },\n },\n {\n key: "transactions",\n schema: {\n type: "array",\n title: "Transactions",\n description: "Posted account activity during the statement period.",\n items: {\n type: "object",\n properties: {\n date: {\n type: "string",\n title: "Date",\n },\n description: {\n type: "string",\n title: "Description",\n },\n amount: {\n type: "number",\n title: "Amount",\n },\n category: {\n type: "string",\n title: "Category",\n },\n merchant: {\n type: "object",\n title: "Merchant",\n properties: {\n name: {\n type: "string",\n title: "Name",\n },\n city: {\n type: "string",\n title: "City",\n },\n risk_level: {\n type: "string",\n title: "Risk level",\n },\n },\n },\n tags: {\n type: "array",\n title: "Tags",\n items: {\n type: "string",\n title: "Tag",\n },\n },\n },\n },\n },\n actual: [\n {\n date: "2026-01-03",\n description: "ACH CREDIT PAYROLL",\n amount: 4250,\n category: "Deposit",\n merchant: {\n name: "Acme Payroll",\n city: "New York",\n risk_level: "low",\n },\n tags: ["payroll", "recurring"],\n },\n {\n date: "2026-01-12",\n description: "POS PURCHASE GROCERY MART",\n amount: -86.42,\n category: "Debit",\n merchant: {\n name: "Grocery Mart",\n city: "Brooklyn",\n risk_level: "medium",\n },\n tags: ["card", "groceries"],\n },\n ],\n expected: [\n {\n date: "2026-01-03",\n description: "ACH CREDIT PAYROLL",\n amount: 4250,\n category: "Deposit",\n merchant: {\n name: "Acme Payroll",\n city: "New York",\n risk_level: "low",\n },\n tags: ["payroll", "recurring"],\n },\n {\n date: "2026-01-12",\n description: "POS PURCHASE GROCERY MART",\n amount: -68.42,\n category: "Debit",\n merchant: {\n name: "Grocery Mart",\n city: "Brooklyn",\n risk_level: "low",\n },\n tags: ["card", "groceries", "needs_review"],\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: "ending_balance",\n schema: {\n type: "number",\n title: "Ending balance",\n description: "Final account balance at the end of the statement period.",\n },\n actual: 12840.18,\n expected: 12858.18,\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "overdraft_protection_enabled",\n schema: {\n type: "boolean",\n title: "Overdraft protection enabled",\n description: "Whether overdraft protection is enabled for the account.",\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: "account_details",\n schema: {\n type: "object",\n title: "Account details",\n description: "Account owner and identifying details from the statement.",\n properties: {\n holder_name: {\n type: "string",\n title: "Holder name",\n },\n account_last_four: {\n type: "string",\n title: "Account last four",\n },\n account_type: {\n type: "string",\n title: "Account type",\n },\n mailing_address: {\n type: "object",\n title: "Mailing address",\n properties: {\n line_1: {\n type: "string",\n title: "Line 1",\n },\n city: {\n type: "string",\n title: "City",\n },\n state: {\n type: "string",\n title: "State",\n },\n },\n },\n linked_accounts: {\n type: "array",\n title: "Linked accounts",\n items: {\n type: "object",\n properties: {\n nickname: {\n type: "string",\n title: "Nickname",\n },\n last_four: {\n type: "string",\n title: "Last four",\n },\n },\n },\n },\n },\n },\n actual: {\n holder_name: "Jordan Lee",\n account_last_four: "4821",\n account_type: "Checking",\n mailing_address: {\n line_1: "42 Market Street",\n city: "Brooklyn",\n state: "NY",\n },\n linked_accounts: [\n {\n nickname: "Operations reserve",\n last_four: "1842",\n },\n ],\n },\n expected: {\n holder_name: "Jordan Lee",\n account_last_four: "4821",\n account_type: "Premier Checking",\n mailing_address: {\n line_1: "42 Market Street",\n city: "New York",\n state: "NY",\n },\n linked_accounts: [\n {\n nickname: "Operations reserve",\n last_four: "1842",\n },\n {\n nickname: "Payroll sweep",\n last_four: "9174",\n },\n ],\n },\n },\n]\n\nfunction getCitationLocation(\n citation: ReviewCitation\n): ReviewLocation | undefined {\n const polygon = citation.polygon\n if (!polygon?.length || !citation.pageWidth || !citation.pageHeight) {\n return undefined\n }\n\n const xs = polygon.map((point) => point.x)\n const ys = polygon.map((point) => point.y)\n const left = Math.min(...xs)\n const top = Math.min(...ys)\n const right = Math.max(...xs)\n const bottom = Math.max(...ys)\n\n return {\n page: citation.page,\n area: {\n left: (left / citation.pageWidth) * 100,\n top: (top / citation.pageHeight) * 100,\n width: ((right - left) / citation.pageWidth) * 100,\n height: ((bottom - top) / citation.pageHeight) * 100,\n },\n }\n}\n\nexport function getMetadataLocation(\n metadata: Record<string, ReviewMetadataEntry> | undefined,\n metadataPath: string | undefined\n) {\n if (!metadata || !metadataPath) return undefined\n\n const citation = metadata[metadataPath]?.citations?.find(\n (candidate) => candidate.polygon?.length\n )\n\n return citation ? getCitationLocation(citation) : undefined\n}\n\nexport function getReviewFieldLocation(\n field: ReviewField | undefined,\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n) {\n if (!field) return undefined\n\n return (\n field.location ??\n resolveLocation?.(field.metadataPath ?? field.key) ??\n undefined\n )\n}\n\nexport function getReviewLocationKey(location: ReviewLocation | undefined) {\n if (!location) return null\n\n const { area } = location\n return [location.page, area.left, area.top, area.width, area.height].join(":")\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\nexport function 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 metadataPath: `${field.metadataPath ?? field.key}.${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 areGridRangesEqual(\n left: Readonly<Rectangle> | undefined,\n right: Readonly<Rectangle> | undefined\n) {\n return (\n left === right ||\n (left !== undefined &&\n right !== undefined &&\n left.x === right.x &&\n left.y === right.y &&\n left.width === right.width &&\n left.height === right.height)\n )\n}\n\nfunction areGridRangeStacksEqual(\n left: readonly Readonly<Rectangle>[] | undefined,\n right: readonly Readonly<Rectangle>[] | undefined\n) {\n if (left === right) return true\n if (!left || !right || left.length !== right.length) return false\n\n return left.every((range, index) => areGridRangesEqual(range, right[index]))\n}\n\nfunction areGridSelectionsEqual(left: GridSelection, right: GridSelection) {\n const leftCurrent = left.current\n const rightCurrent = right.current\n\n return (\n leftCurrent?.cell[0] === rightCurrent?.cell[0] &&\n leftCurrent?.cell[1] === rightCurrent?.cell[1] &&\n areGridRangesEqual(leftCurrent?.range, rightCurrent?.range) &&\n areGridRangeStacksEqual(\n leftCurrent?.rangeStack,\n rightCurrent?.rangeStack\n ) &&\n left.columns.equals(right.columns) &&\n left.rows.equals(right.rows)\n )\n}\n\nfunction getGridSelectionRanges(selection: GridSelection | undefined) {\n const current = selection?.current\n if (!current) return []\n\n return [...(current.rangeStack ?? []), current.range]\n}\n\nfunction areArrayNestedViewsEqual(\n left: ArrayNestedView[],\n right: ArrayNestedView[]\n) {\n if (left === right) return true\n if (left.length !== right.length) return false\n\n return left.every((view, index) => {\n const other = right[index]\n\n return (\n view.rowIndex === other?.rowIndex &&\n view.columnId === other.columnId &&\n view.title === other.title &&\n view.schema === other.schema &&\n Object.is(view.value, other.value)\n )\n })\n}\n\ntype HumanReviewOverlayCell = TextCell | NumberCell\n\ntype HumanReviewTextOverlayEditorProps = React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n> & {\n overlayOpenRef: React.RefObject<boolean>\n readOnly?: boolean\n}\n\nfunction HumanReviewTextOverlayEditor({\n isHighlighted,\n onFinishedEditing,\n overlayOpenRef,\n readOnly = false,\n validatedSelection,\n value,\n}: HumanReviewTextOverlayEditorProps) {\n const initialValue =\n value.kind === GridCellKind.Number ? value.displayData : value.data\n const [entryValue, setEntryValue] = React.useState(initialValue)\n const latestValueRef = React.useRef(initialValue)\n const finishedRef = React.useRef(false)\n\n const finishEditing = React.useCallback(\n (\n shouldSave: boolean,\n movement: readonly [-1 | 0 | 1, -1 | 0 | 1] = [0, 0]\n ) => {\n if (finishedRef.current) return\n\n finishedRef.current = true\n overlayOpenRef.current = false\n\n if (!shouldSave || readOnly) {\n onFinishedEditing(undefined, movement)\n return\n }\n\n if (value.kind === GridCellKind.Number) {\n const numericValue = Number(latestValueRef.current)\n\n onFinishedEditing(\n {\n ...value,\n data: Number.isFinite(numericValue) ? numericValue : value.data,\n displayData: latestValueRef.current,\n },\n movement\n )\n return\n }\n\n onFinishedEditing(\n {\n ...value,\n data: latestValueRef.current,\n displayData: latestValueRef.current,\n },\n movement\n )\n },\n [onFinishedEditing, overlayOpenRef, readOnly, value]\n )\n\n const handleEntryChange = React.useCallback(\n (event: React.ChangeEvent<HTMLTextAreaElement>) => {\n event.stopPropagation()\n latestValueRef.current = event.target.value\n setEntryValue(event.target.value)\n },\n []\n )\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n event.stopPropagation()\n\n if (event.key === "Escape") {\n event.preventDefault()\n finishEditing(false)\n return\n }\n\n if (event.key === "Tab") {\n event.preventDefault()\n finishEditing(true, [event.shiftKey ? -1 : 1, 0])\n return\n }\n\n if (event.key === "Enter" && !event.shiftKey) {\n event.preventDefault()\n finishEditing(true, [0, 1])\n }\n },\n [finishEditing]\n )\n\n React.useEffect(() => {\n overlayOpenRef.current = true\n\n return () => {\n overlayOpenRef.current = false\n }\n }, [overlayOpenRef])\n\n React.useEffect(() => {\n const handlePointerOutside = (event: PointerEvent | MouseEvent) => {\n const input = document.querySelector<HTMLTextAreaElement>(".gdg-input")\n const overlayRoot = input?.closest(".gdg-clip-region")\n\n if (!overlayRoot || overlayRoot.contains(event.target as Node | null)) {\n return\n }\n\n finishEditing(true)\n }\n\n document.addEventListener("pointerdown", handlePointerOutside, true)\n document.addEventListener("contextmenu", handlePointerOutside, true)\n\n return () => {\n document.removeEventListener("pointerdown", handlePointerOutside, true)\n document.removeEventListener("contextmenu", handlePointerOutside, true)\n }\n }, [finishEditing])\n\n return (\n <TextCellEntry\n autoFocus={!readOnly}\n disabled={readOnly}\n highlight={isHighlighted}\n value={entryValue}\n validatedSelection={validatedSelection}\n altNewline\n onChange={handleEntryChange}\n onKeyDown={handleKeyDown}\n />\n )\n}\n\nfunction getFieldIcon(type: SchemaPropertyType) {\n if (type === "number" || type === "integer") return InputNumericGlyph\n if (type === "boolean") return TextCheckGlyph\n if (type === "array") return SecondBracketGlyph\n if (type === "object") return SourceCodeSquareGlyph\n return InputTextGlyph\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\nexport type HumanReviewTheme = "light" | "dark"\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 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 metadataPath,\n onChange,\n onGridSelectionChange,\n onLocationHover,\n onNestedStackChange,\n resolveArrayItemMetadataPath,\n resolveLocation,\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 metadataPath?: string\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 onLocationHover?: (location?: ReviewLocation) => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\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 fastTextOverlayOpenRef = React.useRef(false)\n const nestedStack = sharedNestedStack ?? localNestedStack\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 mirroredHighlightRegions = React.useMemo<\n React.ComponentProps<typeof DataEditor>["highlightRegions"]\n >(() => {\n if (\n !activeSelectionSide ||\n activeSelectionSide === viewSide ||\n selectionDepth !== nestedStackBaseDepth\n ) {\n return undefined\n }\n\n const ranges = getGridSelectionRanges(sharedGridSelection)\n if (!ranges.length) return undefined\n\n return ranges.map((range) => ({\n color: mirroredCellBackground,\n range,\n style: "dashed" as const,\n }))\n }, [\n activeSelectionSide,\n mirroredCellBackground,\n nestedStackBaseDepth,\n selectionDepth,\n sharedGridSelection,\n viewSide,\n ])\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 flushSync(() => {\n setLocalGridSelection((current) =>\n areGridSelectionsEqual(current, selection) ? current : selection\n )\n })\n\n if (onGridSelectionChange) {\n if (\n activeSelectionSide === viewSide &&\n sharedGridSelection &&\n areGridSelectionsEqual(sharedGridSelection, selection)\n ) {\n return\n }\n\n React.startTransition(() => {\n onGridSelectionChange(selection, viewSide, nestedStackBaseDepth)\n })\n return\n }\n },\n [\n activeSelectionSide,\n nestedStackBaseDepth,\n onGridSelectionChange,\n sharedGridSelection,\n viewSide,\n ]\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 nestedCellTheme: Partial<Theme> | undefined = matchedNestedCell\n ? {\n bgCell: isMirroredNestedTarget\n ? mirroredCellBackground\n : selectedCellBackground,\n textDark: blueCellText,\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 ...(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 }\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: true,\n readonly: false,\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: true,\n readonly: false,\n }\n },\n [\n activeNestedView,\n blueCellText,\n columns,\n isMirroredNestedTarget,\n itemSchema,\n mirroredCellBackground,\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 const provideEditor = React.useCallback<\n NonNullable<React.ComponentProps<typeof DataEditor>["provideEditor"]>\n >(\n (cell) => {\n if (\n cell.kind !== GridCellKind.Text &&\n cell.kind !== GridCellKind.Number\n ) {\n return undefined\n }\n\n return {\n editor: (props) => {\n if (\n props.value.kind !== GridCellKind.Text &&\n props.value.kind !== GridCellKind.Number\n ) {\n return null\n }\n\n return (\n <HumanReviewTextOverlayEditor\n {...(props as React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n >)}\n overlayOpenRef={fastTextOverlayOpenRef}\n readOnly={readOnly}\n />\n )\n },\n }\n },\n [readOnly]\n )\n const handleOutsideClick = React.useCallback(\n () => !fastTextOverlayOpenRef.current,\n []\n )\n const handleItemHovered = React.useCallback(\n (args: GridMouseEventArgs) => {\n if (!onLocationHover || !resolveLocation || !metadataPath) return\n\n if (args.kind !== "cell") {\n onLocationHover(undefined)\n return\n }\n\n const [col, row] = args.location\n const column = columns[col]\n const rowValue = rows[row]\n if (!column || rowValue === undefined) {\n onLocationHover(undefined)\n return\n }\n\n const columnId = String(column.id ?? "value")\n const rowMetadataPath = resolveArrayItemMetadataPath\n ? resolveArrayItemMetadataPath(metadataPath, row, rowValue)\n : `${metadataPath}[${row}]`\n if (!rowMetadataPath) {\n onLocationHover(undefined)\n return\n }\n\n const propertyMetadataPath =\n itemSchema.type === "object"\n ? `${rowMetadataPath}.${columnId}`\n : rowMetadataPath\n\n onLocationHover(\n resolveLocation(propertyMetadataPath) ??\n resolveLocation(rowMetadataPath)\n )\n },\n [\n columns,\n itemSchema.type,\n metadataPath,\n onLocationHover,\n resolveArrayItemMetadataPath,\n resolveLocation,\n rows,\n ]\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 onMouseLeave={() => onLocationHover?.(undefined)}\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 gridSelection={localGridSelection}\n highlightRegions={mirroredHighlightRegions}\n onCellEdited={updateCellValue}\n onCellActivated={openNestedCell}\n onGridSelectionChange={handleGridSelectionChange}\n onItemHovered={handleItemHovered}\n provideEditor={provideEditor}\n isOutsideClick={handleOutsideClick}\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 <IconPlaceholder\n lucide="ChevronLeft"\n tabler="IconChevronLeft"\n hugeicons="ArrowLeft01Icon"\n phosphor="CaretLeftIcon"\n remixicon="RiArrowLeftSLine"\n className="size-3.5"\n />\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 resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\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 showExpected?: boolean\n onChange: (value: JsonValue) => void\n onFieldFocus?: (field: ReviewField) => void\n onLocationHover?: (location?: ReviewLocation) => void\n onUndo: () => void\n onSetNull: () => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\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.showExpected === next.showExpected &&\n previous.onFieldFocus === next.onFieldFocus &&\n previous.onLocationHover === next.onLocationHover &&\n previous.resolveArrayItemMetadataPath ===\n next.resolveArrayItemMetadataPath &&\n previous.resolveLocation === next.resolveLocation\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 showExpected = true,\n onChange,\n onFieldFocus,\n onLocationHover,\n onUndo,\n onSetNull,\n resolveArrayItemMetadataPath,\n resolveLocation,\n}: HumanReviewFieldCardProps) {\n const isExpectedEditable = showExpected && !readOnly\n const modified = showExpected && !jsonValuesEqual(value, originalValue)\n const fieldTypeIcon = React.createElement(getFieldIcon(field.schema.type), {\n className: "size-3.5",\n })\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 const activeSide = stack.length ? side : null\n\n setSyncedArrayNestedView((current) =>\n current.activeSide === activeSide &&\n areArrayNestedViewsEqual(current.stack, stack)\n ? current\n : {\n activeSide,\n stack,\n }\n )\n },\n []\n )\n const updateSyncedArraySelection = React.useCallback(\n (gridSelection: GridSelection, side: ArrayReviewSide, depth: number) => {\n const activeSide = gridSelection.current ? side : null\n\n setSyncedArraySelection((current) =>\n current.activeSide === activeSide &&\n current.depth === depth &&\n areGridSelectionsEqual(current.gridSelection, gridSelection)\n ? current\n : {\n activeSide,\n depth,\n gridSelection,\n }\n )\n },\n []\n )\n const focusAndHoverField = React.useCallback(() => {\n onFieldFocus?.(field)\n onLocationHover?.(getReviewFieldLocation(field, resolveLocation))\n }, [field, onFieldFocus, onLocationHover, resolveLocation])\n\n return (\n <div\n tabIndex={0}\n onFocusCapture={focusAndHoverField}\n onMouseEnter={focusAndHoverField}\n onMouseLeave={() => onLocationHover?.(undefined)}\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",\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 {isExpectedEditable && 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 <IconPlaceholder\n lucide="Undo2"\n tabler="IconArrowBackUp"\n hugeicons="Undo02Icon"\n phosphor="ArrowUUpLeftIcon"\n remixicon="RiArrowGoBackLine"\n className="size-4"\n />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Revert changes</TooltipContent>\n </Tooltip>\n ) : null}\n {isExpectedEditable ? (\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 <IconPlaceholder\n lucide="CircleX"\n tabler="IconCircleX"\n hugeicons="CancelCircleIcon"\n phosphor="XCircleIcon"\n remixicon="RiCloseCircleLine"\n className="size-4"\n />\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 {fieldTypeIcon}\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 metadataPath: `${field.metadataPath ?? field.key}.${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 showExpected={showExpected}\n onChange={(childValue) =>\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onFieldFocus={onFieldFocus}\n onLocationHover={onLocationHover}\n onUndo={() =>\n onChange(\n setObjectValue(value, propertyKey, childField.expected)\n )\n }\n onSetNull={() =>\n onChange(setObjectValue(value, propertyKey, null))\n }\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\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 metadataPath={field.metadataPath ?? field.key}\n readOnly\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\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 onLocationHover={onLocationHover}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n {showExpected ? (\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Expected"\n metadataPath={field.metadataPath ?? field.key}\n readOnly={readOnly}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\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 onLocationHover={onLocationHover}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n ) : null}\n </div>\n ) : (\n <div className={cn("grid gap-2", showExpected && "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 {showExpected ? (\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 ) : null}\n </div>\n )}\n </div>\n )\n}\n\nexport function HumanReviewHighlight({\n location,\n}: {\n location: ReviewLocation\n}) {\n const area = location.area\n\n return (\n <div\n className={cn(\n "pointer-events-none absolute z-10 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 theme = "light",\n}: {\n actual: JsonObject\n expected: JsonObject\n theme?: HumanReviewTheme\n}) {\n const oldFile = React.useMemo(\n () => ({\n name: "actual.json",\n contents: formatJson(actual),\n lang: "json",\n }),\n [actual]\n )\n const newFile = React.useMemo(\n () => ({\n name: "expected.json",\n contents: formatJson(expected),\n lang: "json",\n }),\n [expected]\n )\n\n return (\n <ScrollAreaVirtualizer\n className="h-full bg-surface/60"\n contentClassName="min-w-full"\n >\n <div className="bounding-box-citations-diff h-full text-xs">\n <MultiFileDiff\n className="block min-w-full"\n oldFile={oldFile}\n newFile={newFile}\n options={{\n diffStyle: "split",\n disableFileHeader: true,\n diffIndicators: "bars",\n hunkSeparators: "line-info-basic",\n overflow: "wrap",\n themeType: theme,\n theme: {\n light: "pierre-light-soft",\n dark: "pierre-dark-soft",\n },\n }}\n />\n </div>\n </ScrollAreaVirtualizer>\n )\n}\n\nexport function JsonCodeView({\n name = "actual.json",\n theme = "light",\n value,\n}: {\n name?: string\n theme?: HumanReviewTheme\n value: JsonValue\n}) {\n const file = React.useMemo(() => {\n const contents = formatJson(value)\n\n return {\n name,\n contents,\n lang: "json" as const,\n cacheKey: contents,\n }\n }, [name, value])\n\n return (\n <div\n data-rehype-pretty-code-figure\n className="relative m-0! h-full overflow-hidden rounded-none! bg-code text-code-foreground"\n >\n <WorkerPoolContextProvider\n poolOptions={CODE_WORKER_POOL_OPTIONS}\n highlighterOptions={CODE_HIGHLIGHTER_OPTIONS}\n >\n <ScrollAreaVirtualizer\n key={`${file.cacheKey}:${theme}`}\n className="h-full min-w-0"\n contentClassName="min-w-full"\n >\n <File\n key={`${file.cacheKey}:${theme}`}\n className="block min-w-full"\n file={file}\n metrics={CODE_VIRTUAL_FILE_METRICS}\n style={CODE_FILE_THEME}\n options={{\n disableFileHeader: true,\n overflow: "scroll",\n themeType: theme,\n theme: {\n light: "pierre-light-soft",\n dark: "pierre-dark-soft",\n },\n }}\n />\n </ScrollAreaVirtualizer>\n </WorkerPoolContextProvider>\n </div>\n )\n}\n\nexport function HumanReviewPanel({\n fields = REVIEW_FIELDS,\n activeFieldKey,\n className,\n onFieldFocus,\n onLocationHover,\n resolveArrayItemMetadataPath,\n resolveLocation,\n showExpected = true,\n theme = "light",\n}: {\n fields?: ReviewField[]\n activeFieldKey?: string\n className?: string\n onFieldFocus?: (field: ReviewField) => void\n onLocationHover?: (location?: ReviewLocation) => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n showExpected?: boolean\n theme?: HumanReviewTheme\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\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 <IconPlaceholder\n lucide="CaptionsIcon"\n tabler="IconTextCaption"\n hugeicons="TextCheckIcon"\n phosphor="TextTIcon"\n remixicon="RiTextWrap"\n className="size-4"\n />\n Form\n </TabsTrigger>\n <TabsTrigger value="json" className="h-7 sm:h-6">\n <IconPlaceholder\n lucide="SquareCode"\n tabler="IconSourceCode"\n hugeicons="SourceCodeSquareIcon"\n phosphor="CodeIcon"\n remixicon="RiCodeBlock"\n className="size-4"\n />\n JSON\n </TabsTrigger>\n </TabsList>\n </div>\n <TabsContent value="form" keepMounted 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={\n showExpected ? (expected[field.key] ?? null) : field.actual\n }\n originalValue={showExpected ? field.expected : field.actual}\n active={\n field.key === activeFieldKey ||\n activeFieldKey?.startsWith(`${field.key}.`)\n }\n activeFieldKey={activeFieldKey}\n showExpected={showExpected}\n onChange={(value) => updateValue(field.key, value)}\n onFieldFocus={onFieldFocus}\n onLocationHover={onLocationHover}\n onUndo={() => updateValue(field.key, field.expected)}\n onSetNull={() => updateValue(field.key, null)}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n ))}\n </div>\n </ScrollArea>\n </TabsContent>\n <TabsContent value="json" keepMounted className="min-h-0 flex-1">\n {showExpected ? (\n <JsonDiffView\n actual={actualValues}\n expected={expected}\n theme={theme}\n />\n ) : (\n <JsonCodeView value={actualValues} theme={theme} />\n )}\n </TabsContent>\n </Tabs>\n </TooltipProvider>\n )\n}\n'export function HumanReviewSource() {return (diff --git a/apps/v4/components/csv-viewer-docs.tsx b/apps/v4/components/csv-viewer-docs.tsxindex 897ed47..5ff8be0 100644--- a/apps/v4/components/csv-viewer-docs.tsx+++ b/apps/v4/components/csv-viewer-docs.tsx@@ -66,7 +66,7 @@ export function CsvViewerExample() {}`const csvViewerSourceCode =- '"use client"\n\nimport * as React from "react"\nimport type * as GlideDataGrid from "@glideapps/glide-data-grid"\nimport type {\n DataEditorRef,\n GridCell,\n GridCellKind,\n GridColumn,\n GridSelection,\n Item,\n Theme,\n} from "@glideapps/glide-data-grid"\nimport {\n CompactSelection,\n emptyGridSelection,\n} from "@glideapps/glide-data-grid"\n\nimport "@glideapps/glide-data-grid/dist/index.css"\n\nimport {\n ArrowLeft01Icon,\n ArrowRight01Icon,\n Download01Icon,\n MinusSignCircleIcon,\n MoreHorizontalIcon,\n PlusSignCircleIcon,\n Search01Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport Papa from "papaparse"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { Input } from "@/components/ui/input"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from "@/components/ui/popover"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\n\nconst ZOOM_OPTIONS = [0.75, 1, 1.25, 1.5, 2] as const\nconst CSV_SEARCH_BATCH_ROW_COUNT = 500\nconst CSV_SEARCH_DEBOUNCE_MS = 300\n\ntype GlideDataGridModule = typeof GlideDataGrid\ntype CsvViewerProps = {\n className?: string\n data?: string\n search?: boolean\n}\n\ntype CsvSearchResult = {\n col: number\n row: number\n displayValue: string\n columnTitle: string\n}\n\nfunction toDisplayString(value: unknown): string {\n return value === null || value === undefined ? "" : String(value)\n}\n\nfunction normalizeHeaderTitle(header: string, index: number): string {\n const trimmed = header.trim()\n return trimmed.length > 0 ? trimmed : `Column ${index + 1}`\n}\n\nfunction columnIndexToA1(col: number) {\n let columnNumber = col + 1\n let columnName = ""\n\n while (columnNumber > 0) {\n const remainder = (columnNumber - 1) % 26\n columnName = String.fromCharCode(65 + remainder) + columnName\n columnNumber = Math.floor((columnNumber - 1) / 26)\n }\n\n return columnName\n}\n\nfunction cellAddressToA1(col: number, row: number) {\n return `${columnIndexToA1(col)}${row + 1}`\n}\n\nfunction cellMatchesQuery(displayValue: string, query: string) {\n return displayValue.toLowerCase().includes(query)\n}\n\nfunction createSingleCellSelection(cell: Item): GridSelection {\n const [col, row] = cell\n\n return {\n columns: CompactSelection.empty(),\n rows: CompactSelection.empty(),\n current: {\n cell,\n range: { x: col, y: row, width: 1, height: 1 },\n rangeStack: [],\n },\n }\n}\n\nasync function findCsvSearchResults(\n headers: string[],\n rows: string[][],\n rawQuery: string\n) {\n const query = rawQuery.trim().toLowerCase()\n if (!query) return []\n\n const results: CsvSearchResult[] = []\n const columnCount = Math.max(\n headers.length,\n rows.reduce((maxCount, row) => Math.max(maxCount, row.length), 0)\n )\n\n for (\n let batchStartRow = 0;\n batchStartRow < rows.length;\n batchStartRow += CSV_SEARCH_BATCH_ROW_COUNT\n ) {\n const batchEndRow = Math.min(\n batchStartRow + CSV_SEARCH_BATCH_ROW_COUNT,\n rows.length\n )\n\n for (let row = batchStartRow; row < batchEndRow; row += 1) {\n const rowValues = rows[row] ?? []\n\n for (let col = 0; col < columnCount; col += 1) {\n const displayValue = rowValues[col] ?? ""\n if (!cellMatchesQuery(displayValue, query)) continue\n\n results.push({\n col,\n row,\n displayValue,\n columnTitle: headers[col] ?? `Column ${col + 1}`,\n })\n }\n }\n\n if (batchEndRow < rows.length) {\n await new Promise<void>((resolve) => {\n window.setTimeout(resolve, 0)\n })\n }\n }\n\n return results\n}\n\nfunction parseDelimitedText(text: string): {\n headers: string[]\n rows: string[][]\n error: string | null\n} {\n const results = Papa.parse<Record<string, unknown>>(text, {\n header: true,\n skipEmptyLines: "greedy",\n })\n\n const objectRows = Array.isArray(results.data)\n ? results.data.filter(\n (row): row is Record<string, unknown> =>\n !!row && typeof row === "object" && !Array.isArray(row)\n )\n : []\n const metaFields = Array.isArray(results.meta.fields)\n ? results.meta.fields.map((field) => String(field))\n : []\n const fieldKeys =\n metaFields.length > 0\n ? metaFields\n : Object.keys(objectRows[0] ?? {}).filter(\n (key) => key !== "__parsed_extra"\n )\n const extraColumnCount = objectRows.reduce((maxCount, row) => {\n const extras = row.__parsed_extra\n return Array.isArray(extras) ? Math.max(maxCount, extras.length) : maxCount\n }, 0)\n const headers = [\n ...fieldKeys.map((field, index) => normalizeHeaderTitle(field, index)),\n ...Array.from(\n { length: extraColumnCount },\n (_, index) => `Extra ${index + 1}`\n ),\n ]\n\n const rows = objectRows.map((row) => {\n const baseValues = fieldKeys.map((fieldKey) =>\n toDisplayString(row[fieldKey])\n )\n const extras = Array.isArray(row.__parsed_extra)\n ? row.__parsed_extra.map((value) => toDisplayString(value))\n : []\n const paddedExtras =\n extras.length >= extraColumnCount\n ? extras.slice(0, extraColumnCount)\n : [\n ...extras,\n ...Array.from(\n { length: extraColumnCount - extras.length },\n () => ""\n ),\n ]\n\n return [...baseValues, ...paddedExtras]\n })\n\n const firstError =\n Array.isArray(results.errors) && results.errors.length > 0\n ? results.errors[0]\n : null\n\n return {\n headers,\n rows,\n error:\n rows.length === 0 && firstError\n ? String(firstError.message ?? "Could not parse CSV file.")\n : null,\n }\n}\n\nfunction ensureCsvExtension(fileName: string) {\n const lowerFileName = fileName.toLowerCase()\n return lowerFileName.endsWith(".csv") || lowerFileName.endsWith(".tsv")\n ? fileName\n : `${fileName}.csv`\n}\n\nfunction downloadTextFile(text: string, fileName: string, type: string) {\n const url = URL.createObjectURL(new Blob([text], { type }))\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = fileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nfunction CsvFileActionsMenu({\n downloadDisabled,\n isPending,\n onDownload,\n onUploadClick,\n}: {\n downloadDisabled: boolean\n isPending: boolean\n onDownload: () => void\n onUploadClick: () => void\n}) {\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open CSV actions"\n disabled={isPending}\n >\n <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-40">\n <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n Download\n </DropdownMenuItem>\n <DropdownMenuItem disabled={isPending} onClick={onUploadClick}>\n {isPending ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n )}\n Upload\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction CsvSearchPopover({\n headers,\n rows,\n gridRef,\n dataIdentity,\n controlsDisabled,\n onGridSelectionChange,\n}: {\n headers: string[]\n rows: string[][]\n gridRef: React.RefObject<DataEditorRef | null>\n dataIdentity: string\n controlsDisabled: boolean\n onGridSelectionChange: (selection: GridSelection) => void\n}) {\n const [searchDraft, setSearchDraft] = React.useState("")\n const [searchQuery, setSearchQuery] = React.useState("")\n const [searchResults, setSearchResults] = React.useState<CsvSearchResult[]>(\n []\n )\n const [activeResultIndex, setActiveResultIndex] = React.useState(0)\n const [isSearching, setIsSearching] = React.useState(false)\n const searchRequestIdRef = React.useRef(0)\n const appliedResultKeyRef = React.useRef("")\n const activeResult = searchResults[activeResultIndex] ?? null\n const activeResultKey = activeResult\n ? `${activeResult.row}:${activeResult.col}`\n : ""\n const hasActiveQuery = Boolean(searchQuery.trim())\n const resultLabel = isSearching\n ? "Searching"\n : !hasActiveQuery\n ? "No search"\n : searchResults.length\n ? `${activeResultIndex + 1} / ${searchResults.length}`\n : "No results"\n\n const runSearch = React.useCallback(\n (rawQuery: string) => {\n const nextQuery = rawQuery.trim()\n const requestId = searchRequestIdRef.current + 1\n searchRequestIdRef.current = requestId\n appliedResultKeyRef.current = ""\n setSearchQuery(nextQuery)\n setActiveResultIndex(0)\n\n if (!nextQuery) {\n setSearchResults([])\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n void findCsvSearchResults(headers, rows, nextQuery)\n .then((nextResults) => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults(nextResults)\n })\n .catch(() => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults([])\n })\n .finally(() => {\n if (searchRequestIdRef.current !== requestId) return\n setIsSearching(false)\n })\n },\n [headers, rows]\n )\n\n React.useEffect(() => {\n const trimmedDraft = searchDraft.trim()\n\n if (!trimmedDraft) {\n runSearch("")\n return\n }\n\n setIsSearching(true)\n const timeoutId = window.setTimeout(() => {\n runSearch(searchDraft)\n }, CSV_SEARCH_DEBOUNCE_MS)\n\n return () => window.clearTimeout(timeoutId)\n }, [runSearch, searchDraft])\n\n const clearSearch = React.useCallback(() => {\n searchRequestIdRef.current += 1\n setSearchDraft("")\n setSearchQuery("")\n setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = ""\n onGridSelectionChange(emptyGridSelection)\n }, [onGridSelectionChange])\n\n const goToRelativeResult = React.useCallback(\n (direction: 1 | -1) => {\n if (!searchResults.length) return\n\n setActiveResultIndex((currentIndex) => {\n return (\n (currentIndex + direction + searchResults.length) %\n searchResults.length\n )\n })\n },\n [searchResults.length]\n )\n\n React.useEffect(() => {\n searchRequestIdRef.current += 1\n setSearchDraft("")\n setSearchQuery("")\n setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = ""\n onGridSelectionChange(emptyGridSelection)\n }, [dataIdentity, onGridSelectionChange])\n\n React.useEffect(() => {\n if (!activeResult) return\n\n if (appliedResultKeyRef.current === activeResultKey) return\n appliedResultKeyRef.current = activeResultKey\n\n const cell: Item = [activeResult.col, activeResult.row]\n onGridSelectionChange(createSingleCellSelection(cell))\n\n const frame = window.requestAnimationFrame(() => {\n gridRef.current?.scrollTo(\n activeResult.col,\n activeResult.row,\n "both",\n 48,\n 48,\n {\n vAlign: "center",\n hAlign: "center",\n }\n )\n })\n\n return () => window.cancelAnimationFrame(frame)\n }, [activeResult, activeResultKey, gridRef, onGridSelectionChange])\n\n return (\n <Popover>\n <ToolbarTooltip label="Search CSV">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search CSV"\n disabled={controlsDisabled}\n >\n <HugeiconsIcon icon={Search01Icon} className="size-4" />\n </Button>\n </PopoverTrigger>\n </ToolbarTooltip>\n <PopoverContent align="end" className="w-72">\n <div className="space-y-3">\n <Input\n placeholder="Search CSV"\n value={searchDraft}\n onChange={(event) => setSearchDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key !== "Enter") return\n\n event.preventDefault()\n if (event.shiftKey && searchResults.length) {\n goToRelativeResult(-1)\n } else if (searchResults.length) {\n goToRelativeResult(1)\n } else if (searchDraft.trim()) {\n runSearch(searchDraft)\n }\n }}\n />\n <div className="flex items-center justify-between gap-2">\n <div className="min-w-0 text-xs text-muted-foreground">\n <div className="truncate">\n {searchResults.length ? (\n <>\n <span className="text-primary">\n {activeResultIndex + 1}\n </span>\n {` / ${searchResults.length}`}\n </>\n ) : (\n resultLabel\n )}\n </div>\n {activeResult ? (\n <div className="mt-0.5 truncate">\n {activeResult.columnTitle}!\n {cellAddressToA1(activeResult.col, activeResult.row)}\n </div>\n ) : null}\n </div>\n <div className="flex shrink-0 items-center gap-1">\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Previous result"\n disabled={isSearching || searchResults.length === 0}\n onClick={() => goToRelativeResult(-1)}\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />\n </Button>\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Next result"\n disabled={isSearching || searchResults.length === 0}\n onClick={() => goToRelativeResult(1)}\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-4" />\n </Button>\n </div>\n </div>\n <div className="flex justify-end">\n <Button\n type="button"\n variant="outline"\n size="sm"\n onClick={clearSearch}\n >\n Clear\n </Button>\n </div>\n </div>\n </PopoverContent>\n </Popover>\n )\n}\n\nfunction readIsDarkTheme() {\n return (\n typeof document !== "undefined" &&\n document.documentElement.classList.contains("dark")\n )\n}\n\nfunction useIsDarkTheme() {\n const [isDark, setIsDark] = React.useState(readIsDarkTheme)\n\n React.useEffect(() => {\n if (typeof document === "undefined") return\n\n const updateTheme = () => setIsDark(readIsDarkTheme())\n\n updateTheme()\n\n if (typeof MutationObserver === "undefined") return\n\n const observer = new MutationObserver(updateTheme)\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ["class"],\n })\n\n return () => observer.disconnect()\n }, [])\n\n return isDark\n}\n\nexport function CsvViewer({ className, data, search = false }: CsvViewerProps) {\n const inputRef = React.useRef<HTMLInputElement | null>(null)\n const gridRef = React.useRef<DataEditorRef | null>(null)\n const isDark = useIsDarkTheme()\n const [glide, setGlide] = React.useState<GlideDataGridModule | null>(null)\n const [zoom, setZoom] = React.useState<(typeof ZOOM_OPTIONS)[number]>(1)\n const [gridSelection, setGridSelection] =\n React.useState<GridSelection>(emptyGridSelection)\n const [parsed, setParsed] = React.useState(() =>\n data ? parseDelimitedText(data) : { headers: [], rows: [], error: null }\n )\n const [uploadedFileName, setUploadedFileName] = React.useState<string | null>(\n null\n )\n const [isPending, setIsPending] = React.useState(false)\n const [dataRevision, setDataRevision] = React.useState(0)\n\n const dataIdentity = React.useMemo(\n () =>\n `${dataRevision}:${parsed.headers.join("\\u0001")}:${parsed.rows.length}:${parsed.error ?? ""}`,\n [dataRevision, parsed.error, parsed.headers, parsed.rows.length]\n )\n\n const handleGridSelectionChange = React.useCallback(\n (selection: GridSelection) => {\n setGridSelection(selection)\n },\n []\n )\n\n React.useEffect(() => {\n if (data) {\n setParsed(parseDelimitedText(data))\n setUploadedFileName(null)\n setDataRevision((revision) => revision + 1)\n }\n }, [data])\n\n React.useEffect(() => {\n if (!search) {\n setGridSelection(emptyGridSelection)\n }\n }, [search])\n\n React.useEffect(() => {\n let mounted = true\n\n void import("@glideapps/glide-data-grid").then((module) => {\n if (mounted) {\n setGlide(module)\n }\n })\n\n return () => {\n mounted = false\n }\n }, [])\n\n const columnCount = Math.max(1, parsed.headers.length)\n const scale = React.useCallback(\n (value: number) => Math.round(value * zoom),\n [zoom]\n )\n const searchDisabled =\n Boolean(parsed.error) || parsed.rows.length === 0 || isPending\n\n const theme = React.useMemo<Partial<Theme>>(\n () => ({\n accentColor: isDark ? "#60a5fa" : "#2563eb",\n accentLight: isDark ? "#1d4ed826" : "#dbeafe",\n accentFg: "#ffffff",\n textDark: isDark ? "#e5e5e5" : "#171717",\n textMedium: isDark ? "#a3a3a3" : "#525252",\n textLight: isDark ? "#737373" : "#a3a3a3",\n textBubble: isDark ? "#f5f5f5" : "#171717",\n textHeader: isDark ? "#f5f5f5" : "#171717",\n textGroupHeader: isDark ? "#a3a3a3" : "#525252",\n bgCell: isDark ? "#0a0a0a" : "#ffffff",\n bgCellMedium: isDark ? "#171717" : "#fafafa",\n bgHeader: isDark ? "#171717" : "#fafafa",\n bgHeaderHasFocus: isDark ? "#262626" : "#f5f5f5",\n bgHeaderHovered: isDark ? "#262626" : "#f5f5f5",\n borderColor: isDark ? "#262626" : "#e5e5e5",\n horizontalBorderColor: isDark ? "#262626" : "#e5e5e5",\n cellHorizontalPadding: scale(8),\n cellVerticalPadding: Math.max(2, scale(3)),\n headerIconSize: scale(18),\n baseFontStyle: `${scale(13)}px`,\n headerFontStyle: `600 ${scale(13)}px`,\n markerFontStyle: `${scale(11)}px`,\n fontFamily: \'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif\',\n editorFontSize: `${scale(13)}px`,\n }),\n [isDark, scale]\n )\n\n const columns = React.useMemo<GridColumn[]>(\n () =>\n Array.from({ length: columnCount }, (_, index) => ({\n id: `column-${index}`,\n title: parsed.headers[index] ?? `Column ${index + 1}`,\n width: scale(index === 0 ? 180 : 160),\n })),\n [columnCount, parsed.headers, scale]\n )\n\n const getCellContent = React.useCallback(\n ([col, row]: Item): GridCell => {\n const value = parsed.rows[row]?.[col] ?? ""\n const textKind = glide?.GridCellKind.Text as GridCellKind.Text\n\n return {\n kind: textKind,\n data: value,\n displayData: value,\n allowOverlay: true,\n readonly: true,\n }\n },\n [glide, parsed.rows]\n )\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n if (!file) return\n\n setIsPending(true)\n try {\n const text = await file.text()\n setParsed(parseDelimitedText(text))\n setUploadedFileName(file.name)\n setDataRevision((revision) => revision + 1)\n } catch (error) {\n setParsed({\n headers: [],\n rows: [],\n error:\n error instanceof Error ? error.message : "Could not read CSV file.",\n })\n setDataRevision((revision) => revision + 1)\n } finally {\n event.target.value = ""\n setIsPending(false)\n }\n }\n\n function stepZoom(direction: -1 | 1) {\n const index = ZOOM_OPTIONS.indexOf(zoom)\n const nextIndex = Math.min(\n ZOOM_OPTIONS.length - 1,\n Math.max(0, index + direction)\n )\n setZoom(ZOOM_OPTIONS[nextIndex])\n }\n\n function handleDownload() {\n const text = Papa.unparse({\n fields: parsed.headers,\n data: parsed.rows,\n })\n\n downloadTextFile(\n text,\n ensureCsvExtension(uploadedFileName ?? "data.csv"),\n "text/csv;charset=utf-8"\n )\n }\n\n return (\n <div\n className={cn(\n "flex h-[560px] w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n <div className="flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2">\n <TooltipProvider>\n <div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom out"\n disabled={zoom <= ZOOM_OPTIONS[0]}\n onClick={() => stepZoom(-1)}\n >\n <HugeiconsIcon\n icon={MinusSignCircleIcon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={zoom.toString()}\n onValueChange={(value) =>\n setZoom(Number(value) as (typeof ZOOM_OPTIONS)[number])\n }\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoom * 100)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align="end" alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((option) => (\n <SelectItem key={option} value={option.toString()}>\n {Math.round(option * 100)}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom in"\n disabled={zoom >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]}\n onClick={() => stepZoom(1)}\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n {search ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <CsvSearchPopover\n headers={parsed.headers}\n rows={parsed.rows}\n gridRef={gridRef}\n dataIdentity={dataIdentity}\n controlsDisabled={searchDisabled}\n onGridSelectionChange={handleGridSelectionChange}\n />\n </>\n ) : null}\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <input\n ref={inputRef}\n type="file"\n accept=".csv,.tsv,text/csv,text/tab-separated-values"\n className="hidden"\n onChange={handleUpload}\n />\n <CsvFileActionsMenu\n downloadDisabled={\n Boolean(parsed.error) ||\n isPending ||\n (parsed.headers.length === 0 && parsed.rows.length === 0)\n }\n isPending={isPending}\n onDownload={handleDownload}\n onUploadClick={() => inputRef.current?.click()}\n />\n </div>\n </TooltipProvider>\n </div>\n <div className="min-h-0 flex-1">\n {parsed.error ? (\n <div className="flex h-full items-center justify-center px-4 text-center text-sm text-destructive">\n {parsed.error}\n </div>\n ) : parsed.rows.length === 0 ? (\n <div className="grid h-full place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs">\n <p className="font-medium">Upload a CSV to preview</p>\n <p className="mt-1 text-muted-foreground">\n Pass delimited text with the <code>data</code> prop or upload a\n CSV file.\n </p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n loading={isPending}\n onClick={() => inputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload CSV\n </Button>\n </div>\n </div>\n ) : !glide ? (\n <div className="grid h-full place-items-center bg-background">\n <Spinner className="size-4" />\n </div>\n ) : (\n <glide.DataEditor\n ref={search ? gridRef : undefined}\n key={zoom}\n columns={columns}\n rows={parsed.rows.length}\n getCellContent={getCellContent}\n rowMarkers="number"\n rowSelectionMode="multi"\n gridSelection={search ? gridSelection : undefined}\n onGridSelectionChange={\n search ? handleGridSelectionChange : undefined\n }\n scrollToActiveCell={search}\n keybindings={{ search: true }}\n smoothScrollX\n smoothScrollY\n getCellsForSelection\n width="100%"\n height="100%"\n theme={theme}\n rowHeight={scale(34)}\n headerHeight={scale(36)}\n />\n )}\n </div>\n </div>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport type * as GlideDataGrid from "@glideapps/glide-data-grid"\nimport type {\n DataEditorRef,\n GridCell,\n GridCellKind,\n GridColumn,\n GridSelection,\n Item,\n Theme,\n} from "@glideapps/glide-data-grid"\nimport {\n CompactSelection,\n emptyGridSelection,\n} from "@glideapps/glide-data-grid"\n\nimport "@glideapps/glide-data-grid/dist/index.css"\n\nimport Papa from "papaparse"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { Input } from "@/components/ui/input"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from "@/components/ui/popover"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nconst ZOOM_OPTIONS = [0.75, 1, 1.25, 1.5, 2] as const\nconst CSV_SEARCH_BATCH_ROW_COUNT = 500\nconst CSV_SEARCH_DEBOUNCE_MS = 300\n\ntype GlideDataGridModule = typeof GlideDataGrid\ntype CsvViewerProps = {\n className?: string\n data?: string\n search?: boolean\n}\n\ntype CsvSearchResult = {\n col: number\n row: number\n displayValue: string\n columnTitle: string\n}\n\nfunction toDisplayString(value: unknown): string {\n return value === null || value === undefined ? "" : String(value)\n}\n\nfunction normalizeHeaderTitle(header: string, index: number): string {\n const trimmed = header.trim()\n return trimmed.length > 0 ? trimmed : `Column ${index + 1}`\n}\n\nfunction columnIndexToA1(col: number) {\n let columnNumber = col + 1\n let columnName = ""\n\n while (columnNumber > 0) {\n const remainder = (columnNumber - 1) % 26\n columnName = String.fromCharCode(65 + remainder) + columnName\n columnNumber = Math.floor((columnNumber - 1) / 26)\n }\n\n return columnName\n}\n\nfunction cellAddressToA1(col: number, row: number) {\n return `${columnIndexToA1(col)}${row + 1}`\n}\n\nfunction cellMatchesQuery(displayValue: string, query: string) {\n return displayValue.toLowerCase().includes(query)\n}\n\nfunction createSingleCellSelection(cell: Item): GridSelection {\n const [col, row] = cell\n\n return {\n columns: CompactSelection.empty(),\n rows: CompactSelection.empty(),\n current: {\n cell,\n range: { x: col, y: row, width: 1, height: 1 },\n rangeStack: [],\n },\n }\n}\n\nasync function findCsvSearchResults(\n headers: string[],\n rows: string[][],\n rawQuery: string\n) {\n const query = rawQuery.trim().toLowerCase()\n if (!query) return []\n\n const results: CsvSearchResult[] = []\n const columnCount = Math.max(\n headers.length,\n rows.reduce((maxCount, row) => Math.max(maxCount, row.length), 0)\n )\n\n for (\n let batchStartRow = 0;\n batchStartRow < rows.length;\n batchStartRow += CSV_SEARCH_BATCH_ROW_COUNT\n ) {\n const batchEndRow = Math.min(\n batchStartRow + CSV_SEARCH_BATCH_ROW_COUNT,\n rows.length\n )\n\n for (let row = batchStartRow; row < batchEndRow; row += 1) {\n const rowValues = rows[row] ?? []\n\n for (let col = 0; col < columnCount; col += 1) {\n const displayValue = rowValues[col] ?? ""\n if (!cellMatchesQuery(displayValue, query)) continue\n\n results.push({\n col,\n row,\n displayValue,\n columnTitle: headers[col] ?? `Column ${col + 1}`,\n })\n }\n }\n\n if (batchEndRow < rows.length) {\n await new Promise<void>((resolve) => {\n window.setTimeout(resolve, 0)\n })\n }\n }\n\n return results\n}\n\nfunction parseDelimitedText(text: string): {\n headers: string[]\n rows: string[][]\n error: string | null\n} {\n const results = Papa.parse<Record<string, unknown>>(text, {\n header: true,\n skipEmptyLines: "greedy",\n })\n\n const objectRows = Array.isArray(results.data)\n ? results.data.filter(\n (row): row is Record<string, unknown> =>\n !!row && typeof row === "object" && !Array.isArray(row)\n )\n : []\n const metaFields = Array.isArray(results.meta.fields)\n ? results.meta.fields.map((field) => String(field))\n : []\n const fieldKeys =\n metaFields.length > 0\n ? metaFields\n : Object.keys(objectRows[0] ?? {}).filter(\n (key) => key !== "__parsed_extra"\n )\n const extraColumnCount = objectRows.reduce((maxCount, row) => {\n const extras = row.__parsed_extra\n return Array.isArray(extras) ? Math.max(maxCount, extras.length) : maxCount\n }, 0)\n const headers = [\n ...fieldKeys.map((field, index) => normalizeHeaderTitle(field, index)),\n ...Array.from(\n { length: extraColumnCount },\n (_, index) => `Extra ${index + 1}`\n ),\n ]\n\n const rows = objectRows.map((row) => {\n const baseValues = fieldKeys.map((fieldKey) =>\n toDisplayString(row[fieldKey])\n )\n const extras = Array.isArray(row.__parsed_extra)\n ? row.__parsed_extra.map((value) => toDisplayString(value))\n : []\n const paddedExtras =\n extras.length >= extraColumnCount\n ? extras.slice(0, extraColumnCount)\n : [\n ...extras,\n ...Array.from(\n { length: extraColumnCount - extras.length },\n () => ""\n ),\n ]\n\n return [...baseValues, ...paddedExtras]\n })\n\n const firstError =\n Array.isArray(results.errors) && results.errors.length > 0\n ? results.errors[0]\n : null\n\n return {\n headers,\n rows,\n error:\n rows.length === 0 && firstError\n ? String(firstError.message ?? "Could not parse CSV file.")\n : null,\n }\n}\n\nfunction ensureCsvExtension(fileName: string) {\n const lowerFileName = fileName.toLowerCase()\n return lowerFileName.endsWith(".csv") || lowerFileName.endsWith(".tsv")\n ? fileName\n : `${fileName}.csv`\n}\n\nfunction downloadTextFile(text: string, fileName: string, type: string) {\n const url = URL.createObjectURL(new Blob([text], { type }))\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = fileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nfunction CsvFileActionsMenu({\n downloadDisabled,\n isPending,\n onDownload,\n onUploadClick,\n}: {\n downloadDisabled: boolean\n isPending: boolean\n onDownload: () => void\n onUploadClick: () => void\n}) {\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open CSV actions"\n disabled={isPending}\n >\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className="size-4"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-40">\n <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>\n <IconPlaceholder\n lucide="Download"\n tabler="IconDownload"\n hugeicons="Download01Icon"\n phosphor="DownloadSimpleIcon"\n remixicon="RiDownload2Line"\n className="size-4"\n />\n Download\n </DropdownMenuItem>\n <DropdownMenuItem disabled={isPending} onClick={onUploadClick}>\n {isPending ? (\n <Spinner className="size-4" />\n ) : (\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n )}\n Upload\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction CsvSearchPopover({\n headers,\n rows,\n gridRef,\n dataIdentity,\n controlsDisabled,\n onGridSelectionChange,\n}: {\n headers: string[]\n rows: string[][]\n gridRef: React.RefObject<DataEditorRef | null>\n dataIdentity: string\n controlsDisabled: boolean\n onGridSelectionChange: (selection: GridSelection) => void\n}) {\n const [searchDraft, setSearchDraft] = React.useState("")\n const [searchQuery, setSearchQuery] = React.useState("")\n const [searchResults, setSearchResults] = React.useState<CsvSearchResult[]>(\n []\n )\n const [activeResultIndex, setActiveResultIndex] = React.useState(0)\n const [isSearching, setIsSearching] = React.useState(false)\n const searchRequestIdRef = React.useRef(0)\n const appliedResultKeyRef = React.useRef("")\n const activeResult = searchResults[activeResultIndex] ?? null\n const activeResultKey = activeResult\n ? `${activeResult.row}:${activeResult.col}`\n : ""\n const hasActiveQuery = Boolean(searchQuery.trim())\n const resultLabel = isSearching\n ? "Searching"\n : !hasActiveQuery\n ? "No search"\n : searchResults.length\n ? `${activeResultIndex + 1} / ${searchResults.length}`\n : "No results"\n\n const runSearch = React.useCallback(\n (rawQuery: string) => {\n const nextQuery = rawQuery.trim()\n const requestId = searchRequestIdRef.current + 1\n searchRequestIdRef.current = requestId\n appliedResultKeyRef.current = ""\n setSearchQuery(nextQuery)\n setActiveResultIndex(0)\n\n if (!nextQuery) {\n setSearchResults([])\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n void findCsvSearchResults(headers, rows, nextQuery)\n .then((nextResults) => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults(nextResults)\n })\n .catch(() => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults([])\n })\n .finally(() => {\n if (searchRequestIdRef.current !== requestId) return\n setIsSearching(false)\n })\n },\n [headers, rows]\n )\n\n React.useEffect(() => {\n const trimmedDraft = searchDraft.trim()\n\n if (!trimmedDraft) {\n runSearch("")\n return\n }\n\n setIsSearching(true)\n const timeoutId = window.setTimeout(() => {\n runSearch(searchDraft)\n }, CSV_SEARCH_DEBOUNCE_MS)\n\n return () => window.clearTimeout(timeoutId)\n }, [runSearch, searchDraft])\n\n const clearSearch = React.useCallback(() => {\n searchRequestIdRef.current += 1\n setSearchDraft("")\n setSearchQuery("")\n setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = ""\n onGridSelectionChange(emptyGridSelection)\n }, [onGridSelectionChange])\n\n const goToRelativeResult = React.useCallback(\n (direction: 1 | -1) => {\n if (!searchResults.length) return\n\n setActiveResultIndex((currentIndex) => {\n return (\n (currentIndex + direction + searchResults.length) %\n searchResults.length\n )\n })\n },\n [searchResults.length]\n )\n\n React.useEffect(() => {\n searchRequestIdRef.current += 1\n setSearchDraft("")\n setSearchQuery("")\n setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = ""\n onGridSelectionChange(emptyGridSelection)\n }, [dataIdentity, onGridSelectionChange])\n\n React.useEffect(() => {\n if (!activeResult) return\n\n if (appliedResultKeyRef.current === activeResultKey) return\n appliedResultKeyRef.current = activeResultKey\n\n const cell: Item = [activeResult.col, activeResult.row]\n onGridSelectionChange(createSingleCellSelection(cell))\n\n const frame = window.requestAnimationFrame(() => {\n gridRef.current?.scrollTo(\n activeResult.col,\n activeResult.row,\n "both",\n 48,\n 48,\n {\n vAlign: "center",\n hAlign: "center",\n }\n )\n })\n\n return () => window.cancelAnimationFrame(frame)\n }, [activeResult, activeResultKey, gridRef, onGridSelectionChange])\n\n return (\n <Popover>\n <ToolbarTooltip label="Search CSV">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search CSV"\n disabled={controlsDisabled}\n >\n <IconPlaceholder\n lucide="Search"\n tabler="IconSearch"\n hugeicons="Search01Icon"\n phosphor="MagnifyingGlassIcon"\n remixicon="RiSearchLine"\n className="size-4"\n />\n </Button>\n </PopoverTrigger>\n </ToolbarTooltip>\n <PopoverContent align="end" className="w-72">\n <div className="space-y-3">\n <Input\n placeholder="Search CSV"\n value={searchDraft}\n onChange={(event) => setSearchDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key !== "Enter") return\n\n event.preventDefault()\n if (event.shiftKey && searchResults.length) {\n goToRelativeResult(-1)\n } else if (searchResults.length) {\n goToRelativeResult(1)\n } else if (searchDraft.trim()) {\n runSearch(searchDraft)\n }\n }}\n />\n <div className="flex items-center justify-between gap-2">\n <div className="min-w-0 text-xs text-muted-foreground">\n <div className="truncate">\n {searchResults.length ? (\n <>\n <span className="text-primary">\n {activeResultIndex + 1}\n </span>\n {` / ${searchResults.length}`}\n </>\n ) : (\n resultLabel\n )}\n </div>\n {activeResult ? (\n <div className="mt-0.5 truncate">\n {activeResult.columnTitle}!\n {cellAddressToA1(activeResult.col, activeResult.row)}\n </div>\n ) : null}\n </div>\n <div className="flex shrink-0 items-center gap-1">\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Previous result"\n disabled={isSearching || searchResults.length === 0}\n onClick={() => goToRelativeResult(-1)}\n >\n <IconPlaceholder\n lucide="ChevronLeft"\n tabler="IconChevronLeft"\n hugeicons="ArrowLeft01Icon"\n phosphor="CaretLeftIcon"\n remixicon="RiArrowLeftSLine"\n className="size-4"\n />\n </Button>\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Next result"\n disabled={isSearching || searchResults.length === 0}\n onClick={() => goToRelativeResult(1)}\n >\n <IconPlaceholder\n lucide="ArrowRight"\n tabler="IconArrowRight"\n hugeicons="ArrowRight01Icon"\n phosphor="ArrowRightIcon"\n remixicon="RiArrowRightLine"\n className="size-4"\n />\n </Button>\n </div>\n </div>\n <div className="flex justify-end">\n <Button\n type="button"\n variant="outline"\n size="sm"\n onClick={clearSearch}\n >\n Clear\n </Button>\n </div>\n </div>\n </PopoverContent>\n </Popover>\n )\n}\n\nfunction readIsDarkTheme() {\n return (\n typeof document !== "undefined" &&\n document.documentElement.classList.contains("dark")\n )\n}\n\nfunction useIsDarkTheme() {\n const [isDark, setIsDark] = React.useState(readIsDarkTheme)\n\n React.useEffect(() => {\n if (typeof document === "undefined") return\n\n const updateTheme = () => setIsDark(readIsDarkTheme())\n\n updateTheme()\n\n if (typeof MutationObserver === "undefined") return\n\n const observer = new MutationObserver(updateTheme)\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ["class"],\n })\n\n return () => observer.disconnect()\n }, [])\n\n return isDark\n}\n\nexport function CsvViewer({ className, data, search = false }: CsvViewerProps) {\n const inputRef = React.useRef<HTMLInputElement | null>(null)\n const gridRef = React.useRef<DataEditorRef | null>(null)\n const isDark = useIsDarkTheme()\n const [glide, setGlide] = React.useState<GlideDataGridModule | null>(null)\n const [zoom, setZoom] = React.useState<(typeof ZOOM_OPTIONS)[number]>(1)\n const [gridSelection, setGridSelection] =\n React.useState<GridSelection>(emptyGridSelection)\n const [parsed, setParsed] = React.useState(() =>\n data ? parseDelimitedText(data) : { headers: [], rows: [], error: null }\n )\n const [uploadedFileName, setUploadedFileName] = React.useState<string | null>(\n null\n )\n const [isPending, setIsPending] = React.useState(false)\n const [dataRevision, setDataRevision] = React.useState(0)\n\n const dataIdentity = React.useMemo(\n () =>\n `${dataRevision}:${parsed.headers.join("\\u0001")}:${parsed.rows.length}:${parsed.error ?? ""}`,\n [dataRevision, parsed.error, parsed.headers, parsed.rows.length]\n )\n\n const handleGridSelectionChange = React.useCallback(\n (selection: GridSelection) => {\n setGridSelection(selection)\n },\n []\n )\n\n React.useEffect(() => {\n if (data) {\n setParsed(parseDelimitedText(data))\n setUploadedFileName(null)\n setDataRevision((revision) => revision + 1)\n }\n }, [data])\n\n React.useEffect(() => {\n if (!search) {\n setGridSelection(emptyGridSelection)\n }\n }, [search])\n\n React.useEffect(() => {\n let mounted = true\n\n void import("@glideapps/glide-data-grid").then((module) => {\n if (mounted) {\n setGlide(module)\n }\n })\n\n return () => {\n mounted = false\n }\n }, [])\n\n const columnCount = Math.max(1, parsed.headers.length)\n const scale = React.useCallback(\n (value: number) => Math.round(value * zoom),\n [zoom]\n )\n const searchDisabled =\n Boolean(parsed.error) || parsed.rows.length === 0 || isPending\n\n const theme = React.useMemo<Partial<Theme>>(\n () => ({\n accentColor: isDark ? "#60a5fa" : "#2563eb",\n accentLight: isDark ? "#1d4ed826" : "#dbeafe",\n accentFg: "#ffffff",\n textDark: isDark ? "#e5e5e5" : "#171717",\n textMedium: isDark ? "#a3a3a3" : "#525252",\n textLight: isDark ? "#737373" : "#a3a3a3",\n textBubble: isDark ? "#f5f5f5" : "#171717",\n textHeader: isDark ? "#f5f5f5" : "#171717",\n textGroupHeader: isDark ? "#a3a3a3" : "#525252",\n bgCell: isDark ? "#0a0a0a" : "#ffffff",\n bgCellMedium: isDark ? "#171717" : "#fafafa",\n bgHeader: isDark ? "#171717" : "#fafafa",\n bgHeaderHasFocus: isDark ? "#262626" : "#f5f5f5",\n bgHeaderHovered: isDark ? "#262626" : "#f5f5f5",\n borderColor: isDark ? "#262626" : "#e5e5e5",\n horizontalBorderColor: isDark ? "#262626" : "#e5e5e5",\n cellHorizontalPadding: scale(8),\n cellVerticalPadding: Math.max(2, scale(3)),\n headerIconSize: scale(18),\n baseFontStyle: `${scale(13)}px`,\n headerFontStyle: `600 ${scale(13)}px`,\n markerFontStyle: `${scale(11)}px`,\n fontFamily: \'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif\',\n editorFontSize: `${scale(13)}px`,\n }),\n [isDark, scale]\n )\n\n const columns = React.useMemo<GridColumn[]>(\n () =>\n Array.from({ length: columnCount }, (_, index) => ({\n id: `column-${index}`,\n title: parsed.headers[index] ?? `Column ${index + 1}`,\n width: scale(index === 0 ? 180 : 160),\n })),\n [columnCount, parsed.headers, scale]\n )\n\n const getCellContent = React.useCallback(\n ([col, row]: Item): GridCell => {\n const value = parsed.rows[row]?.[col] ?? ""\n const textKind = glide?.GridCellKind.Text as GridCellKind.Text\n\n return {\n kind: textKind,\n data: value,\n displayData: value,\n allowOverlay: true,\n readonly: true,\n }\n },\n [glide, parsed.rows]\n )\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n if (!file) return\n\n setIsPending(true)\n try {\n const text = await file.text()\n setParsed(parseDelimitedText(text))\n setUploadedFileName(file.name)\n setDataRevision((revision) => revision + 1)\n } catch (error) {\n setParsed({\n headers: [],\n rows: [],\n error:\n error instanceof Error ? error.message : "Could not read CSV file.",\n })\n setDataRevision((revision) => revision + 1)\n } finally {\n event.target.value = ""\n setIsPending(false)\n }\n }\n\n function stepZoom(direction: -1 | 1) {\n const index = ZOOM_OPTIONS.indexOf(zoom)\n const nextIndex = Math.min(\n ZOOM_OPTIONS.length - 1,\n Math.max(0, index + direction)\n )\n setZoom(ZOOM_OPTIONS[nextIndex])\n }\n\n function handleDownload() {\n const text = Papa.unparse({\n fields: parsed.headers,\n data: parsed.rows,\n })\n\n downloadTextFile(\n text,\n ensureCsvExtension(uploadedFileName ?? "data.csv"),\n "text/csv;charset=utf-8"\n )\n }\n\n return (\n <div\n className={cn(\n "flex h-[560px] w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n <div className="flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2">\n <TooltipProvider>\n <div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom out"\n disabled={zoom <= ZOOM_OPTIONS[0]}\n onClick={() => stepZoom(-1)}\n >\n <IconPlaceholder\n lucide="CircleMinus"\n tabler="IconCircleMinus"\n hugeicons="MinusSignCircleIcon"\n phosphor="MinusCircleIcon"\n remixicon="RiIndeterminateCircleLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={zoom.toString()}\n onValueChange={(value) =>\n setZoom(Number(value) as (typeof ZOOM_OPTIONS)[number])\n }\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoom * 100)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align="end" alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((option) => (\n <SelectItem key={option} value={option.toString()}>\n {Math.round(option * 100)}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom in"\n disabled={zoom >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]}\n onClick={() => stepZoom(1)}\n >\n <IconPlaceholder\n lucide="CirclePlusIcon"\n tabler="IconCirclePlusFilled"\n hugeicons="PlusSignCircleIcon"\n phosphor="PlusCircleIcon"\n remixicon="RiAddCircleFill"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n {search ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <CsvSearchPopover\n headers={parsed.headers}\n rows={parsed.rows}\n gridRef={gridRef}\n dataIdentity={dataIdentity}\n controlsDisabled={searchDisabled}\n onGridSelectionChange={handleGridSelectionChange}\n />\n </>\n ) : null}\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <input\n ref={inputRef}\n type="file"\n accept=".csv,.tsv,text/csv,text/tab-separated-values"\n className="hidden"\n onChange={handleUpload}\n />\n <CsvFileActionsMenu\n downloadDisabled={\n Boolean(parsed.error) ||\n isPending ||\n (parsed.headers.length === 0 && parsed.rows.length === 0)\n }\n isPending={isPending}\n onDownload={handleDownload}\n onUploadClick={() => inputRef.current?.click()}\n />\n </div>\n </TooltipProvider>\n </div>\n <div className="min-h-0 flex-1">\n {parsed.error ? (\n <div className="flex h-full items-center justify-center px-4 text-center text-sm text-destructive">\n {parsed.error}\n </div>\n ) : parsed.rows.length === 0 ? (\n <div className="grid h-full place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs">\n <p className="font-medium">Upload a CSV to preview</p>\n <p className="mt-1 text-muted-foreground">\n Pass delimited text with the <code>data</code> prop or upload a\n CSV file.\n </p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n loading={isPending}\n onClick={() => inputRef.current?.click()}\n >\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload CSV\n </Button>\n </div>\n </div>\n ) : !glide ? (\n <div className="grid h-full place-items-center bg-background">\n <Spinner className="size-4" />\n </div>\n ) : (\n <glide.DataEditor\n ref={search ? gridRef : undefined}\n key={zoom}\n columns={columns}\n rows={parsed.rows.length}\n getCellContent={getCellContent}\n rowMarkers="number"\n rowSelectionMode="multi"\n gridSelection={search ? gridSelection : undefined}\n onGridSelectionChange={\n search ? handleGridSelectionChange : undefined\n }\n scrollToActiveCell={search}\n keybindings={{ search: true }}\n smoothScrollX\n smoothScrollY\n getCellsForSelection\n width="100%"\n height="100%"\n theme={theme}\n rowHeight={scale(34)}\n headerHeight={scale(36)}\n />\n )}\n </div>\n </div>\n )\n}\n'export function CsvViewerSource() {return (diff --git a/apps/v4/components/document-splitter-docs.tsx b/apps/v4/components/document-splitter-docs.tsxindex 71d4037..d9d4b73 100644--- a/apps/v4/components/document-splitter-docs.tsx+++ b/apps/v4/components/document-splitter-docs.tsx@@ -1580,7 +1580,7 @@ export function DocumentSplitsExample() {}`const documentSplitterSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n closestCenter,\n DndContext,\n DragOverlay,\n PointerSensor,\n useDroppable,\n useSensor,\n useSensors,\n type CollisionDetection,\n type DragEndEvent,\n type DragOverEvent,\n type DragStartEvent,\n} from "@dnd-kit/core"\nimport {\n arrayMove,\n horizontalListSortingStrategy,\n SortableContext,\n useSortable,\n verticalListSortingStrategy,\n} from "@dnd-kit/sortable"\nimport { CSS } from "@dnd-kit/utilities"\nimport {\n Add01Icon,\n Delete02Icon,\n DragDropVerticalIcon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\n\nimport { cn } from "@/lib/utils"\nimport { FileThumbnail } from "@/components/extend/file-thumbnail"\nimport { Button } from "@/components/ui/button"\nimport { ScrollArea } from "@/components/ui/scroll-area"\n\nexport type DocumentSplitPageId = `page-${number}`\nexport type DocumentSplit = {\n id: string\n title: string\n pages: DocumentSplitPageId[]\n}\n\ntype PageId = DocumentSplitPageId\ntype SplitGroup = DocumentSplit\n\nconst THUMBNAIL_WIDTH = 72\nconst THUMBNAIL_HEIGHT = 92\nconst DRAG_OVERLAY_DROP_ANIMATION = null\nconst THUMBNAIL_SURFACE_CLASS_NAME =\n "relative overflow-hidden rounded-lg border border-border bg-background shadow-xs"\nconst THUMBNAIL_BUTTON_CLASS_NAME = cn(\n THUMBNAIL_SURFACE_CLASS_NAME,\n "cursor-grab text-left transition-[border-color,box-shadow,opacity] outline-none hover:border-ring/40 hover:ring-2 hover:ring-ring focus-visible:border-ring/40 focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"\n)\n\nconst splitterCollisionDetection: CollisionDetection = (args) => {\n const dragType = args.active.data.current?.type\n\n if (dragType === "page") {\n return closestCenter({\n ...args,\n droppableContainers: args.droppableContainers.filter(\n (container) =>\n container.data.current?.type === "page" ||\n (container.data.current?.type === "page-dropzone" &&\n container.data.current?.isEmpty)\n ),\n })\n }\n\n if (dragType === "split") {\n return closestCenter({\n ...args,\n droppableContainers: args.droppableContainers.filter(\n (container) => container.data.current?.type === "split"\n ),\n })\n }\n\n return closestCenter(args)\n}\n\nexport const INITIAL_SPLITS: DocumentSplit[] = [\n {\n id: "split-1",\n title: "Abstract and intro",\n pages: ["page-1", "page-2", "page-3"],\n },\n {\n id: "split-2",\n title: "Model architecture",\n pages: ["page-4", "page-5", "page-6", "page-7"],\n },\n {\n id: "split-3",\n title: "Training and results",\n pages: ["page-8", "page-9", "page-10"],\n },\n]\n\nexport function createInitialSplits(pageCount: number) {\n if (pageCount <= 0) return INITIAL_SPLITS\n\n const pages = Array.from(\n { length: pageCount },\n (_, index) => `page-${index + 1}` as PageId\n )\n const chunkSize = Math.max(1, Math.ceil(pageCount / 3))\n\n return Array.from(\n { length: Math.ceil(pageCount / chunkSize) },\n (_, index) => {\n const startIndex = index * chunkSize\n const groupPages = pages.slice(startIndex, startIndex + chunkSize)\n const firstPage = getPageNumber(groupPages[0])\n const lastPage = getPageNumber(groupPages[groupPages.length - 1])\n\n return {\n id: `split-${index + 1}`,\n title:\n firstPage === lastPage\n ? `Page ${firstPage}`\n : `Pages ${firstPage}-${lastPage}`,\n pages: groupPages,\n }\n }\n )\n}\n\nfunction getPageNumber(pageId: PageId) {\n return Number(pageId.replace("page-", ""))\n}\n\nfunction getSplitSortableId(groupId: string) {\n return `split-sortable-${groupId}`\n}\n\nfunction findGroupId(groups: SplitGroup[], id: string) {\n if (groups.some((group) => group.id === id)) return id\n\n return groups.find((group) => group.pages.includes(id as PageId))?.id ?? null\n}\n\nfunction getGroupPages(groups: SplitGroup[], groupId: string | null) {\n return groups.find((group) => group.id === groupId)?.pages ?? []\n}\n\nfunction movePageToGroup({\n draggedPageId,\n groups,\n insertIndex,\n targetGroupId,\n}: {\n draggedPageId: PageId\n groups: SplitGroup[]\n insertIndex: number\n targetGroupId: string\n}) {\n return groups.map((group) => {\n const pagesWithoutDragged = group.pages.filter(\n (pageId) => pageId !== draggedPageId\n )\n\n if (group.id !== targetGroupId) {\n return { ...group, pages: pagesWithoutDragged }\n }\n\n const nextPages = [...pagesWithoutDragged]\n nextPages.splice(insertIndex, 0, draggedPageId)\n\n return { ...group, pages: nextPages }\n })\n}\n\nfunction areSplitGroupsEqual(left: SplitGroup[], right: SplitGroup[]) {\n if (left === right) return true\n if (left.length !== right.length) return false\n\n return left.every((leftGroup, groupIndex) => {\n const rightGroup = right[groupIndex]\n if (!rightGroup) return false\n\n return (\n leftGroup.id === rightGroup.id &&\n leftGroup.title === rightGroup.title &&\n leftGroup.pages.length === rightGroup.pages.length &&\n leftGroup.pages.every(\n (pageId, pageIndex) => pageId === rightGroup.pages[pageIndex]\n )\n )\n })\n}\n\nfunction reorderPageInGroup({\n draggedPageId,\n groups,\n overPageId,\n}: {\n draggedPageId: PageId\n groups: SplitGroup[]\n overPageId: PageId\n}) {\n const groupId = findGroupId(groups, draggedPageId)\n const pages = getGroupPages(groups, groupId)\n const draggedIndex = pages.indexOf(draggedPageId)\n const overIndex = pages.indexOf(overPageId)\n\n if (!groupId || draggedIndex === -1 || overIndex === -1) return groups\n\n return groups.map((group) =>\n group.id === groupId\n ? {\n ...group,\n pages: arrayMove(group.pages, draggedIndex, overIndex),\n }\n : group\n )\n}\n\nfunction createPageRangeLabel(pageIds: PageId[]) {\n if (pageIds.length === 0) return "No pages"\n\n return `Pages ${pageIds.map(getPageNumber).join(", ")}`\n}\n\nfunction SplitGroupDropzone({\n children,\n group,\n}: {\n children: React.ReactNode\n group: SplitGroup\n}) {\n const { isOver, setNodeRef } = useDroppable({\n id: group.id,\n data: { type: "page-dropzone", isEmpty: group.pages.length === 0 },\n })\n\n return (\n <div\n ref={setNodeRef}\n className={cn(\n "min-h-[116px] rounded-lg p-2 transition-[background-color,box-shadow]",\n isOver && "bg-accent/30 shadow-[inset_0_0_0_1px_var(--border)]"\n )}\n >\n {children}\n </div>\n )\n}\n\nfunction PageThumbnail({\n imageUrl,\n onSelect,\n pageId,\n}: {\n imageUrl?: string\n onSelect: (pageNumber: number) => void\n pageId: PageId\n}) {\n const pageNumber = getPageNumber(pageId)\n const {\n attributes,\n isDragging,\n listeners,\n setNodeRef,\n transform,\n transition,\n } = useSortable({\n id: pageId,\n data: { type: "page" },\n })\n\n return (\n <button\n ref={setNodeRef}\n type="button"\n className={cn(\n THUMBNAIL_BUTTON_CLASS_NAME,\n "shrink-0",\n isDragging && "opacity-0"\n )}\n style={{\n width: THUMBNAIL_WIDTH,\n height: THUMBNAIL_HEIGHT,\n transform: CSS.Transform.toString(transform),\n transition,\n }}\n onClick={() => onSelect(pageNumber)}\n {...attributes}\n {...listeners}\n >\n <FileThumbnail\n file={{\n name: `page-${pageNumber}.pdf`,\n type: "application/pdf",\n }}\n previewImageUrl={imageUrl}\n isLoading={!imageUrl}\n previewClassName="h-full aspect-auto"\n className="size-full rounded-[inherit] border-0 bg-transparent"\n />\n <span className="absolute right-1 bottom-1 rounded bg-background/95 px-1.5 py-0.5 text-[10px] font-semibold text-foreground shadow-xs ring-1 ring-border/80">\n {pageNumber}\n </span>\n </button>\n )\n}\n\nfunction SplitGroupCard({\n canRemove,\n group,\n dragHandleProps,\n thumbnailImages,\n onRemove,\n onSelectPage,\n}: {\n canRemove: boolean\n group: SplitGroup\n dragHandleProps?: React.ComponentPropsWithoutRef<"button">\n thumbnailImages: Record<PageId, string>\n onRemove: () => void\n onSelectPage: (pageNumber: number) => void\n}) {\n return (\n <section className="w-full rounded-lg border bg-background">\n <div className="flex items-center justify-between gap-3 border-b p-3">\n <div className="flex min-w-0 items-center gap-2">\n <button\n type="button"\n aria-label={`Reorder ${group.title}`}\n className="inline-flex size-7 shrink-0 cursor-grab items-center justify-center rounded-md text-muted-foreground hover:bg-muted active:cursor-grabbing"\n {...dragHandleProps}\n >\n <HugeiconsIcon icon={DragDropVerticalIcon} className="size-4" />\n </button>\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">{group.title}</div>\n <div className="mt-1 text-xs text-muted-foreground">\n {createPageRangeLabel(group.pages)}\n </div>\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-2">\n <div className="rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">\n {group.pages.length}\n </div>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label={`Remove ${group.title}`}\n disabled={!canRemove}\n onClick={onRemove}\n >\n <HugeiconsIcon icon={Delete02Icon} className="size-4" />\n </Button>\n </div>\n </div>\n <SplitGroupDropzone group={group}>\n {group.pages.length ? (\n <SortableContext\n items={group.pages}\n strategy={horizontalListSortingStrategy}\n >\n <ScrollArea\n className="h-[110px] w-full overflow-hidden"\n orientation="horizontal"\n scrollbarGutter\n scrollbarOverflowOnly\n viewportClassName="overflow-y-hidden"\n >\n <div className="flex w-max gap-2 overflow-y-hidden py-1 pr-6">\n {group.pages.map((pageId) => (\n <PageThumbnail\n key={pageId}\n pageId={pageId}\n imageUrl={thumbnailImages[pageId]}\n onSelect={onSelectPage}\n />\n ))}\n </div>\n </ScrollArea>\n </SortableContext>\n ) : (\n <div className="grid h-[104px] place-items-center rounded-lg bg-muted/35 text-xs text-muted-foreground">\n Drop pages here\n </div>\n )}\n </SplitGroupDropzone>\n </section>\n )\n}\n\nfunction SortableSplitGroupCard({\n canRemove,\n group,\n thumbnailImages,\n onRemove,\n onSelectPage,\n}: {\n canRemove: boolean\n group: SplitGroup\n thumbnailImages: Record<PageId, string>\n onRemove: () => void\n onSelectPage: (pageNumber: number) => void\n}) {\n const {\n attributes,\n isDragging,\n listeners,\n setNodeRef,\n transform,\n transition,\n } = useSortable({\n id: getSplitSortableId(group.id),\n data: { type: "split", groupId: group.id },\n })\n\n return (\n <div\n ref={setNodeRef}\n className={cn("w-full", isDragging && "opacity-0")}\n style={{\n transform: CSS.Transform.toString(transform),\n transition,\n }}\n >\n <SplitGroupCard\n canRemove={canRemove}\n group={group}\n thumbnailImages={thumbnailImages}\n dragHandleProps={{ ...attributes, ...listeners }}\n onRemove={onRemove}\n onSelectPage={onSelectPage}\n />\n </div>\n )\n}\n\nfunction SplitGroupDragOverlay({\n group,\n thumbnailImages,\n width,\n onSelectPage,\n}: {\n group: SplitGroup\n thumbnailImages: Record<PageId, string>\n width?: number\n onSelectPage: (pageNumber: number) => void\n}) {\n return (\n <div\n className="relative z-40 max-w-[calc(100vw-2rem)]"\n style={{ width }}\n >\n <SplitGroupCard\n canRemove={false}\n group={group}\n thumbnailImages={thumbnailImages}\n onRemove={() => {}}\n onSelectPage={onSelectPage}\n />\n </div>\n )\n}\n\nexport function DocumentSplits({\n className,\n splits,\n thumbnailImages = {},\n withFrameDivider = true,\n onSelectPage,\n onSplitsChange,\n}: {\n className?: string\n splits: SplitGroup[]\n thumbnailImages?: Record<PageId, string>\n withFrameDivider?: boolean\n onSelectPage: (pageNumber: number) => void\n onSplitsChange: (splits: SplitGroup[]) => void\n}) {\n const [draggedPageId, setDraggedPageId] = React.useState<PageId | null>(null)\n const [activeSplitGroupId, setActiveSplitGroupId] = React.useState<\n string | null\n >(null)\n const [activeSplitGroupWidth, setActiveSplitGroupWidth] = React.useState<\n number | undefined\n >()\n const dragStartGroupIdRef = React.useRef<string | null>(null)\n const dragStartSplitsRef = React.useRef<SplitGroup[] | null>(null)\n const sensors = useSensors(\n useSensor(PointerSensor, { activationConstraint: { distance: 6 } })\n )\n\n const handleDragStart = React.useCallback(\n (event: DragStartEvent) => {\n const dragType = event.active.data.current?.type\n\n if (dragType === "split") {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(\n (event.active.data.current?.groupId as string | undefined) ?? null\n )\n setActiveSplitGroupWidth(event.active.rect.current.initial?.width)\n return\n }\n\n if (dragType !== "page") {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n const pageId = String(event.active.id) as PageId\n dragStartGroupIdRef.current = findGroupId(splits, pageId)\n dragStartSplitsRef.current = splits\n setDraggedPageId(pageId)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n },\n [splits]\n )\n\n const handleDragOver = React.useCallback(\n (event: DragOverEvent) => {\n if (event.active.data.current?.type !== "page" || !event.over) return\n\n const pageId = String(event.active.id) as PageId\n const overId = String(event.over.id)\n\n const sourceGroupId = findGroupId(splits, pageId)\n const targetGroupId = findGroupId(splits, overId)\n\n if (!sourceGroupId || !targetGroupId || sourceGroupId === targetGroupId) {\n return\n }\n\n const targetPages = getGroupPages(splits, targetGroupId)\n const overIndex = targetPages.indexOf(overId as PageId)\n const insertIndex = overIndex === -1 ? targetPages.length : overIndex\n\n const nextSplits = movePageToGroup({\n draggedPageId: pageId,\n groups: splits,\n insertIndex,\n targetGroupId,\n })\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n },\n [onSplitsChange, splits]\n )\n\n const handleDragEnd = React.useCallback(\n (event: DragEndEvent) => {\n if (event.active.data.current?.type === "split" && event.over) {\n const activeGroupId = event.active.data.current.groupId\n const overGroupId = event.over.data.current?.groupId\n\n const draggedIndex = splits.findIndex(\n (group) => group.id === activeGroupId\n )\n const overIndex = splits.findIndex((group) => group.id === overGroupId)\n\n if (draggedIndex !== -1 && overIndex !== -1) {\n const nextSplits = arrayMove(splits, draggedIndex, overIndex)\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n }\n\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n if (event.active.data.current?.type !== "page" || !event.over) {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n const pageId = String(event.active.id) as PageId\n const overId = String(event.over.id) as PageId\n const overGroupId = findGroupId(splits, overId)\n\n if (dragStartGroupIdRef.current === overGroupId) {\n const nextSplits = reorderPageInGroup({\n draggedPageId: pageId,\n groups: splits,\n overPageId: overId,\n })\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n }\n\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n },\n [onSplitsChange, splits]\n )\n\n const handleDragCancel = React.useCallback(() => {\n if (dragStartSplitsRef.current) {\n onSplitsChange(dragStartSplitsRef.current)\n }\n\n dragStartSplitsRef.current = null\n dragStartGroupIdRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n }, [onSplitsChange])\n\n const activeSplitGroup = activeSplitGroupId\n ? splits.find((group) => group.id === activeSplitGroupId)\n : null\n\n return (\n <aside\n className={cn(\n "flex h-full min-h-0 flex-col bg-muted/20",\n withFrameDivider && "border-t md:border-t-0 md:border-l",\n className\n )}\n >\n <div className="flex min-h-12 items-center justify-end gap-3 border-b bg-background px-3">\n <Button\n type="button"\n variant="outline"\n size="sm"\n onClick={() =>\n onSplitsChange([\n ...splits,\n {\n id: `split-${Date.now()}`,\n title: `Split ${splits.length + 1}`,\n pages: [],\n },\n ])\n }\n >\n <HugeiconsIcon icon={Add01Icon} className="size-4" />\n Add split\n </Button>\n </div>\n <DndContext\n id="document-splits-dnd"\n sensors={sensors}\n collisionDetection={splitterCollisionDetection}\n onDragStart={handleDragStart}\n onDragOver={handleDragOver}\n onDragEnd={handleDragEnd}\n onDragCancel={handleDragCancel}\n >\n <ScrollArea className="min-h-0 flex-1" scrollFade>\n <SortableContext\n items={splits.map((group) => getSplitSortableId(group.id))}\n strategy={verticalListSortingStrategy}\n >\n <div className="space-y-3 p-3">\n {splits.map((group) => (\n <SortableSplitGroupCard\n key={group.id}\n canRemove={splits.length > 1}\n group={group}\n thumbnailImages={thumbnailImages}\n onRemove={() => {\n if (splits.length <= 1) return\n onSplitsChange(\n splits.filter((split) => split.id !== group.id)\n )\n }}\n onSelectPage={onSelectPage}\n />\n ))}\n </div>\n </SortableContext>\n </ScrollArea>\n <DragOverlay dropAnimation={DRAG_OVERLAY_DROP_ANIMATION} zIndex={40}>\n {draggedPageId ? (\n <div\n className={cn(\n THUMBNAIL_SURFACE_CLASS_NAME,\n "shadow-lg shadow-black/10"\n )}\n style={{ width: THUMBNAIL_WIDTH, height: THUMBNAIL_HEIGHT }}\n >\n <FileThumbnail\n file={{ name: `${draggedPageId}.pdf`, type: "application/pdf" }}\n previewImageUrl={thumbnailImages[draggedPageId]}\n isLoading={!thumbnailImages[draggedPageId]}\n previewClassName="h-full aspect-auto"\n className="size-full rounded-[inherit] border-0 bg-transparent"\n />\n </div>\n ) : activeSplitGroup ? (\n <SplitGroupDragOverlay\n group={activeSplitGroup}\n thumbnailImages={thumbnailImages}\n width={activeSplitGroupWidth}\n onSelectPage={onSelectPage}\n />\n ) : null}\n </DragOverlay>\n </DndContext>\n </aside>\n )\n}'+ '"use client"\n\nimport * as React from "react"\nimport {\n closestCenter,\n DndContext,\n DragOverlay,\n PointerSensor,\n useDroppable,\n useSensor,\n useSensors,\n type CollisionDetection,\n type DragEndEvent,\n type DragOverEvent,\n type DragStartEvent,\n} from "@dnd-kit/core"\nimport {\n arrayMove,\n horizontalListSortingStrategy,\n SortableContext,\n useSortable,\n verticalListSortingStrategy,\n} from "@dnd-kit/sortable"\nimport { CSS } from "@dnd-kit/utilities"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport { FileThumbnail } from "@/components/extend/file-thumbnail"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nexport type DocumentSplitPageId = `page-${number}`\nexport type DocumentSplit = {\n id: string\n title: string\n pages: DocumentSplitPageId[]\n}\n\ntype PageId = DocumentSplitPageId\ntype SplitGroup = DocumentSplit\n\nconst THUMBNAIL_WIDTH = 72\nconst THUMBNAIL_HEIGHT = 92\nconst DRAG_OVERLAY_DROP_ANIMATION = null\nconst THUMBNAIL_SURFACE_CLASS_NAME =\n "relative overflow-hidden rounded-lg border border-border bg-background shadow-xs"\nconst THUMBNAIL_BUTTON_CLASS_NAME = cn(\n THUMBNAIL_SURFACE_CLASS_NAME,\n "cursor-grab text-left transition-[border-color,box-shadow,opacity] outline-none hover:border-ring/40 hover:ring-2 hover:ring-ring focus-visible:border-ring/40 focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"\n)\n\nconst splitterCollisionDetection: CollisionDetection = (args) => {\n const dragType = args.active.data.current?.type\n\n if (dragType === "page") {\n return closestCenter({\n ...args,\n droppableContainers: args.droppableContainers.filter(\n (container) =>\n container.data.current?.type === "page" ||\n (container.data.current?.type === "page-dropzone" &&\n container.data.current?.isEmpty)\n ),\n })\n }\n\n if (dragType === "split") {\n return closestCenter({\n ...args,\n droppableContainers: args.droppableContainers.filter(\n (container) => container.data.current?.type === "split"\n ),\n })\n }\n\n return closestCenter(args)\n}\n\nexport const INITIAL_SPLITS: DocumentSplit[] = [\n {\n id: "split-1",\n title: "Abstract and intro",\n pages: ["page-1", "page-2", "page-3"],\n },\n {\n id: "split-2",\n title: "Model architecture",\n pages: ["page-4", "page-5", "page-6", "page-7"],\n },\n {\n id: "split-3",\n title: "Training and results",\n pages: ["page-8", "page-9", "page-10"],\n },\n]\n\nexport function createInitialSplits(pageCount: number) {\n if (pageCount <= 0) return INITIAL_SPLITS\n\n const pages = Array.from(\n { length: pageCount },\n (_, index) => `page-${index + 1}` as PageId\n )\n const chunkSize = Math.max(1, Math.ceil(pageCount / 3))\n\n return Array.from(\n { length: Math.ceil(pageCount / chunkSize) },\n (_, index) => {\n const startIndex = index * chunkSize\n const groupPages = pages.slice(startIndex, startIndex + chunkSize)\n const firstPage = getPageNumber(groupPages[0])\n const lastPage = getPageNumber(groupPages[groupPages.length - 1])\n\n return {\n id: `split-${index + 1}`,\n title:\n firstPage === lastPage\n ? `Page ${firstPage}`\n : `Pages ${firstPage}-${lastPage}`,\n pages: groupPages,\n }\n }\n )\n}\n\nfunction getPageNumber(pageId: PageId) {\n return Number(pageId.replace("page-", ""))\n}\n\nfunction getSplitSortableId(groupId: string) {\n return `split-sortable-${groupId}`\n}\n\nfunction findGroupId(groups: SplitGroup[], id: string) {\n if (groups.some((group) => group.id === id)) return id\n\n return groups.find((group) => group.pages.includes(id as PageId))?.id ?? null\n}\n\nfunction getGroupPages(groups: SplitGroup[], groupId: string | null) {\n return groups.find((group) => group.id === groupId)?.pages ?? []\n}\n\nfunction movePageToGroup({\n draggedPageId,\n groups,\n insertIndex,\n targetGroupId,\n}: {\n draggedPageId: PageId\n groups: SplitGroup[]\n insertIndex: number\n targetGroupId: string\n}) {\n return groups.map((group) => {\n const pagesWithoutDragged = group.pages.filter(\n (pageId) => pageId !== draggedPageId\n )\n\n if (group.id !== targetGroupId) {\n return { ...group, pages: pagesWithoutDragged }\n }\n\n const nextPages = [...pagesWithoutDragged]\n nextPages.splice(insertIndex, 0, draggedPageId)\n\n return { ...group, pages: nextPages }\n })\n}\n\nfunction areSplitGroupsEqual(left: SplitGroup[], right: SplitGroup[]) {\n if (left === right) return true\n if (left.length !== right.length) return false\n\n return left.every((leftGroup, groupIndex) => {\n const rightGroup = right[groupIndex]\n if (!rightGroup) return false\n\n return (\n leftGroup.id === rightGroup.id &&\n leftGroup.title === rightGroup.title &&\n leftGroup.pages.length === rightGroup.pages.length &&\n leftGroup.pages.every(\n (pageId, pageIndex) => pageId === rightGroup.pages[pageIndex]\n )\n )\n })\n}\n\nfunction reorderPageInGroup({\n draggedPageId,\n groups,\n overPageId,\n}: {\n draggedPageId: PageId\n groups: SplitGroup[]\n overPageId: PageId\n}) {\n const groupId = findGroupId(groups, draggedPageId)\n const pages = getGroupPages(groups, groupId)\n const draggedIndex = pages.indexOf(draggedPageId)\n const overIndex = pages.indexOf(overPageId)\n\n if (!groupId || draggedIndex === -1 || overIndex === -1) return groups\n\n return groups.map((group) =>\n group.id === groupId\n ? {\n ...group,\n pages: arrayMove(group.pages, draggedIndex, overIndex),\n }\n : group\n )\n}\n\nfunction createPageRangeLabel(pageIds: PageId[]) {\n if (pageIds.length === 0) return "No pages"\n\n return `Pages ${pageIds.map(getPageNumber).join(", ")}`\n}\n\nfunction SplitGroupDropzone({\n children,\n group,\n}: {\n children: React.ReactNode\n group: SplitGroup\n}) {\n const { isOver, setNodeRef } = useDroppable({\n id: group.id,\n data: { type: "page-dropzone", isEmpty: group.pages.length === 0 },\n })\n\n return (\n <div\n ref={setNodeRef}\n className={cn(\n "min-h-[116px] rounded-lg p-2 transition-[background-color,box-shadow]",\n isOver && "bg-accent/30 shadow-[inset_0_0_0_1px_var(--border)]"\n )}\n >\n {children}\n </div>\n )\n}\n\nfunction PageThumbnail({\n imageUrl,\n onSelect,\n pageId,\n}: {\n imageUrl?: string\n onSelect: (pageNumber: number) => void\n pageId: PageId\n}) {\n const pageNumber = getPageNumber(pageId)\n const {\n attributes,\n isDragging,\n listeners,\n setNodeRef,\n transform,\n transition,\n } = useSortable({\n id: pageId,\n data: { type: "page" },\n })\n\n return (\n <button\n ref={setNodeRef}\n type="button"\n className={cn(\n THUMBNAIL_BUTTON_CLASS_NAME,\n "shrink-0",\n isDragging && "opacity-0"\n )}\n style={{\n width: THUMBNAIL_WIDTH,\n height: THUMBNAIL_HEIGHT,\n transform: CSS.Transform.toString(transform),\n transition,\n }}\n onClick={() => onSelect(pageNumber)}\n {...attributes}\n {...listeners}\n >\n <FileThumbnail\n file={{\n name: `page-${pageNumber}.pdf`,\n type: "application/pdf",\n }}\n previewImageUrl={imageUrl}\n isLoading={!imageUrl}\n previewClassName="h-full aspect-auto"\n className="size-full rounded-[inherit] border-0 bg-transparent"\n />\n <span className="absolute right-1 bottom-1 rounded bg-background/95 px-1.5 py-0.5 text-[10px] font-semibold text-foreground shadow-xs ring-1 ring-border/80">\n {pageNumber}\n </span>\n </button>\n )\n}\n\nfunction SplitGroupCard({\n canRemove,\n group,\n dragHandleProps,\n thumbnailImages,\n onRemove,\n onSelectPage,\n}: {\n canRemove: boolean\n group: SplitGroup\n dragHandleProps?: React.ComponentPropsWithoutRef<"button">\n thumbnailImages: Record<PageId, string>\n onRemove: () => void\n onSelectPage: (pageNumber: number) => void\n}) {\n return (\n <section className="w-full rounded-lg border bg-background">\n <div className="flex items-center justify-between gap-3 border-b p-3">\n <div className="flex min-w-0 items-center gap-2">\n <button\n type="button"\n aria-label={`Reorder ${group.title}`}\n className="inline-flex size-7 shrink-0 cursor-grab items-center justify-center rounded-md text-muted-foreground hover:bg-muted active:cursor-grabbing"\n {...dragHandleProps}\n >\n <IconPlaceholder\n lucide="GripVertical"\n tabler="IconGripVertical"\n hugeicons="DragDropVerticalIcon"\n phosphor="DotsSixVerticalIcon"\n remixicon="RiDraggable"\n className="size-4"\n />\n </button>\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">{group.title}</div>\n <div className="mt-1 text-xs text-muted-foreground">\n {createPageRangeLabel(group.pages)}\n </div>\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-2">\n <div className="rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">\n {group.pages.length}\n </div>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label={`Remove ${group.title}`}\n disabled={!canRemove}\n onClick={onRemove}\n >\n <IconPlaceholder\n lucide="Trash2Icon"\n tabler="IconTrash"\n hugeicons="Delete02Icon"\n phosphor="TrashIcon"\n remixicon="RiDeleteBinLine"\n className="size-4"\n />\n </Button>\n </div>\n </div>\n <SplitGroupDropzone group={group}>\n {group.pages.length ? (\n <SortableContext\n items={group.pages}\n strategy={horizontalListSortingStrategy}\n >\n <ScrollArea\n className="h-[110px] w-full overflow-hidden"\n orientation="horizontal"\n scrollbarGutter\n scrollbarOverflowOnly\n viewportClassName="overflow-y-hidden"\n >\n <div className="flex w-max gap-2 overflow-y-hidden py-1 pr-6">\n {group.pages.map((pageId) => (\n <PageThumbnail\n key={pageId}\n pageId={pageId}\n imageUrl={thumbnailImages[pageId]}\n onSelect={onSelectPage}\n />\n ))}\n </div>\n </ScrollArea>\n </SortableContext>\n ) : (\n <div className="grid h-[104px] place-items-center rounded-lg bg-muted/35 text-xs text-muted-foreground">\n Drop pages here\n </div>\n )}\n </SplitGroupDropzone>\n </section>\n )\n}\n\nfunction SortableSplitGroupCard({\n canRemove,\n group,\n thumbnailImages,\n onRemove,\n onSelectPage,\n}: {\n canRemove: boolean\n group: SplitGroup\n thumbnailImages: Record<PageId, string>\n onRemove: () => void\n onSelectPage: (pageNumber: number) => void\n}) {\n const {\n attributes,\n isDragging,\n listeners,\n setNodeRef,\n transform,\n transition,\n } = useSortable({\n id: getSplitSortableId(group.id),\n data: { type: "split", groupId: group.id },\n })\n\n return (\n <div\n ref={setNodeRef}\n className={cn("w-full", isDragging && "opacity-0")}\n style={{\n transform: CSS.Transform.toString(transform),\n transition,\n }}\n >\n <SplitGroupCard\n canRemove={canRemove}\n group={group}\n thumbnailImages={thumbnailImages}\n dragHandleProps={{ ...attributes, ...listeners }}\n onRemove={onRemove}\n onSelectPage={onSelectPage}\n />\n </div>\n )\n}\n\nfunction SplitGroupDragOverlay({\n group,\n thumbnailImages,\n width,\n onSelectPage,\n}: {\n group: SplitGroup\n thumbnailImages: Record<PageId, string>\n width?: number\n onSelectPage: (pageNumber: number) => void\n}) {\n return (\n <div className="relative z-40 max-w-[calc(100vw-2rem)]" style={{ width }}>\n <SplitGroupCard\n canRemove={false}\n group={group}\n thumbnailImages={thumbnailImages}\n onRemove={() => {}}\n onSelectPage={onSelectPage}\n />\n </div>\n )\n}\n\nexport function DocumentSplits({\n className,\n splits,\n thumbnailImages = {},\n withFrameDivider = true,\n onSelectPage,\n onSplitsChange,\n}: {\n className?: string\n splits: SplitGroup[]\n thumbnailImages?: Record<PageId, string>\n withFrameDivider?: boolean\n onSelectPage: (pageNumber: number) => void\n onSplitsChange: (splits: SplitGroup[]) => void\n}) {\n const [draggedPageId, setDraggedPageId] = React.useState<PageId | null>(null)\n const [activeSplitGroupId, setActiveSplitGroupId] = React.useState<\n string | null\n >(null)\n const [activeSplitGroupWidth, setActiveSplitGroupWidth] = React.useState<\n number | undefined\n >()\n const dragStartGroupIdRef = React.useRef<string | null>(null)\n const dragStartSplitsRef = React.useRef<SplitGroup[] | null>(null)\n const sensors = useSensors(\n useSensor(PointerSensor, { activationConstraint: { distance: 6 } })\n )\n\n const handleDragStart = React.useCallback(\n (event: DragStartEvent) => {\n const dragType = event.active.data.current?.type\n\n if (dragType === "split") {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(\n (event.active.data.current?.groupId as string | undefined) ?? null\n )\n setActiveSplitGroupWidth(event.active.rect.current.initial?.width)\n return\n }\n\n if (dragType !== "page") {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n const pageId = String(event.active.id) as PageId\n dragStartGroupIdRef.current = findGroupId(splits, pageId)\n dragStartSplitsRef.current = splits\n setDraggedPageId(pageId)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n },\n [splits]\n )\n\n const handleDragOver = React.useCallback(\n (event: DragOverEvent) => {\n if (event.active.data.current?.type !== "page" || !event.over) return\n\n const pageId = String(event.active.id) as PageId\n const overId = String(event.over.id)\n\n const sourceGroupId = findGroupId(splits, pageId)\n const targetGroupId = findGroupId(splits, overId)\n\n if (!sourceGroupId || !targetGroupId || sourceGroupId === targetGroupId) {\n return\n }\n\n const targetPages = getGroupPages(splits, targetGroupId)\n const overIndex = targetPages.indexOf(overId as PageId)\n const insertIndex = overIndex === -1 ? targetPages.length : overIndex\n\n const nextSplits = movePageToGroup({\n draggedPageId: pageId,\n groups: splits,\n insertIndex,\n targetGroupId,\n })\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n },\n [onSplitsChange, splits]\n )\n\n const handleDragEnd = React.useCallback(\n (event: DragEndEvent) => {\n if (event.active.data.current?.type === "split" && event.over) {\n const activeGroupId = event.active.data.current.groupId\n const overGroupId = event.over.data.current?.groupId\n\n const draggedIndex = splits.findIndex(\n (group) => group.id === activeGroupId\n )\n const overIndex = splits.findIndex((group) => group.id === overGroupId)\n\n if (draggedIndex !== -1 && overIndex !== -1) {\n const nextSplits = arrayMove(splits, draggedIndex, overIndex)\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n }\n\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n if (event.active.data.current?.type !== "page" || !event.over) {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n const pageId = String(event.active.id) as PageId\n const overId = String(event.over.id) as PageId\n const overGroupId = findGroupId(splits, overId)\n\n if (dragStartGroupIdRef.current === overGroupId) {\n const nextSplits = reorderPageInGroup({\n draggedPageId: pageId,\n groups: splits,\n overPageId: overId,\n })\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n }\n\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n },\n [onSplitsChange, splits]\n )\n\n const handleDragCancel = React.useCallback(() => {\n if (dragStartSplitsRef.current) {\n onSplitsChange(dragStartSplitsRef.current)\n }\n\n dragStartSplitsRef.current = null\n dragStartGroupIdRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n }, [onSplitsChange])\n\n const activeSplitGroup = activeSplitGroupId\n ? splits.find((group) => group.id === activeSplitGroupId)\n : null\n\n return (\n <aside\n className={cn(\n "flex h-full min-h-0 flex-col bg-muted/20",\n withFrameDivider && "border-t md:border-t-0 md:border-l",\n className\n )}\n >\n <div className="flex min-h-12 items-center justify-end gap-3 border-b bg-background px-3">\n <Button\n type="button"\n variant="outline"\n size="sm"\n onClick={() =>\n onSplitsChange([\n ...splits,\n {\n id: `split-${Date.now()}`,\n title: `Split ${splits.length + 1}`,\n pages: [],\n },\n ])\n }\n >\n <IconPlaceholder\n lucide="Plus"\n tabler="IconPlus"\n hugeicons="Add01Icon"\n phosphor="PlusIcon"\n remixicon="RiAddLine"\n className="size-4"\n />\n Add split\n </Button>\n </div>\n <DndContext\n id="document-splits-dnd"\n sensors={sensors}\n collisionDetection={splitterCollisionDetection}\n onDragStart={handleDragStart}\n onDragOver={handleDragOver}\n onDragEnd={handleDragEnd}\n onDragCancel={handleDragCancel}\n >\n <ScrollArea className="min-h-0 flex-1" scrollFade>\n <SortableContext\n items={splits.map((group) => getSplitSortableId(group.id))}\n strategy={verticalListSortingStrategy}\n >\n <div className="space-y-3 p-3">\n {splits.map((group) => (\n <SortableSplitGroupCard\n key={group.id}\n canRemove={splits.length > 1}\n group={group}\n thumbnailImages={thumbnailImages}\n onRemove={() => {\n if (splits.length <= 1) return\n onSplitsChange(\n splits.filter((split) => split.id !== group.id)\n )\n }}\n onSelectPage={onSelectPage}\n />\n ))}\n </div>\n </SortableContext>\n </ScrollArea>\n <DragOverlay dropAnimation={DRAG_OVERLAY_DROP_ANIMATION} zIndex={40}>\n {draggedPageId ? (\n <div\n className={cn(\n THUMBNAIL_SURFACE_CLASS_NAME,\n "shadow-lg shadow-black/10"\n )}\n style={{ width: THUMBNAIL_WIDTH, height: THUMBNAIL_HEIGHT }}\n >\n <FileThumbnail\n file={{ name: `${draggedPageId}.pdf`, type: "application/pdf" }}\n previewImageUrl={thumbnailImages[draggedPageId]}\n isLoading={!thumbnailImages[draggedPageId]}\n previewClassName="h-full aspect-auto"\n className="size-full rounded-[inherit] border-0 bg-transparent"\n />\n </div>\n ) : activeSplitGroup ? (\n <SplitGroupDragOverlay\n group={activeSplitGroup}\n thumbnailImages={thumbnailImages}\n width={activeSplitGroupWidth}\n onSelectPage={onSelectPage}\n />\n ) : null}\n </DragOverlay>\n </DndContext>\n </aside>\n )\n}\n'export function DocumentSplitsSource() {return (diff --git a/apps/v4/components/docx-editor-docs.tsx b/apps/v4/components/docx-editor-docs.tsxindex a071c48..edf9cd6 100644--- a/apps/v4/components/docx-editor-docs.tsx+++ b/apps/v4/components/docx-editor-docs.tsx@@ -86,7 +86,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 useDocxComments,\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 Comment01Icon,\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"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport { ColorPicker } from "@/components/ui/color-picker"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/extend/document-viewer-sidebar"\nimport {\n createDocxCommentCardRenderer,\n createDocxTrackedChangeCardRenderer,\n} from "@/components/extend/docx-annotation-card"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { FileThumbnail } from "@/components/extend/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 { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_EDITOR_DEFAULT_ZOOM_SCALE = 100\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\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\ntype DocxFontToggleValue =\n | "bold"\n | "italic"\n | "underline"\n | "strike"\n | "superscript"\n | "subscript"\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\nasync function loadDocxFile(\n url: string,\n displayFileName: string\n): Promise<File> {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n return new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\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 normalizeDocxZoomScale(value: number | undefined): number {\n return typeof value === "number" &&\n ZOOM_OPTIONS.includes(value as (typeof ZOOM_OPTIONS)[number])\n ? value\n : DOCX_EDITOR_DEFAULT_ZOOM_SCALE\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 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 ToolbarSeparator() {\n return <Separator orientation="vertical" className="mx-1 h-4 self-center" />\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="rounded-md 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 isLoading={isLoading}\n hasError={hasError}\n className={cn(\n "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",\n isActive && "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 onIsDarkChange,\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 onIsDarkChange: (checked: boolean) => 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 { showComments, setShowComments } = useDocxComments(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 const fontToggleValues = React.useMemo<DocxFontToggleValue[]>(() => {\n const values: DocxFontToggleValue[] = []\n\n if (selectedRunStyle?.bold) values.push("bold")\n if (selectedRunStyle?.italic) values.push("italic")\n if (selectedRunStyle?.underline) values.push("underline")\n if (selectedRunStyle?.strike) values.push("strike")\n if (selectedRunStyle?.verticalAlign === "superscript") {\n values.push("superscript")\n }\n if (selectedRunStyle?.verticalAlign === "subscript") {\n values.push("subscript")\n }\n\n return values\n }, [selectedRunStyle])\n\n const preserveTextSelection = React.useCallback(\n (event: React.MouseEvent<HTMLElement> | React.PointerEvent<HTMLElement>) =>\n event.preventDefault(),\n []\n )\n const applyFontToggleValues = React.useCallback(\n (nextValues: DocxFontToggleValue[]) => {\n const changedValue =\n nextValues.find((value) => !fontToggleValues.includes(value)) ??\n fontToggleValues.find((value) => !nextValues.includes(value))\n\n if (changedValue === "bold") {\n editor.toggleBold()\n } else if (changedValue === "italic") {\n editor.toggleItalic()\n } else if (changedValue === "underline") {\n editor.toggleUnderline()\n } else if (changedValue === "strike") {\n editor.toggleStrike()\n } else if (changedValue === "superscript") {\n editor.toggleSuperscript()\n } else if (changedValue === "subscript") {\n editor.toggleSubscript()\n }\n },\n [editor, fontToggleValues]\n )\n\n return (\n <div className="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 const nextIsDark = documentTheme !== "dark"\n setDocumentTheme(nextIsDark ? "dark" : "light")\n onIsDarkChange(nextIsDark)\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="Show comments"\n active={showComments}\n disabled={controlsDisabled}\n onClick={() => setShowComments(!showComments)}\n >\n <HugeiconsIcon icon={Comment01Icon} 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 <ToolbarSeparator />\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-40 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-40 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-40"\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-40"\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-40"\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 <ToolbarSeparator />\n\n <ToggleGroup\n className="shrink-0"\n disabled={!canEdit}\n multiple\n spacing="default"\n value={fontToggleValues}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onValueChange={(value) =>\n applyFontToggleValues(value as DocxFontToggleValue[])\n }\n >\n <ToolbarTooltip label="Bold">\n <ToggleGroupItem aria-label="Bold" size="sm" value="bold">\n <HugeiconsIcon icon={TextBoldIcon} className="size-4" />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Italic">\n <ToggleGroupItem aria-label="Italic" size="sm" value="italic">\n <HugeiconsIcon icon={TextItalicIcon} className="size-4" />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Underline">\n <ToggleGroupItem\n aria-label="Underline"\n size="sm"\n value="underline"\n >\n <HugeiconsIcon icon={TextUnderlineIcon} className="size-4" />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Strikethrough">\n <ToggleGroupItem\n aria-label="Strikethrough"\n size="sm"\n value="strike"\n >\n <HugeiconsIcon\n icon={TextStrikethroughIcon}\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Superscript">\n <ToggleGroupItem\n aria-label="Superscript"\n size="sm"\n value="superscript"\n >\n <HugeiconsIcon icon={TextSuperscriptIcon} className="size-4" />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Subscript">\n <ToggleGroupItem\n aria-label="Subscript"\n size="sm"\n value="subscript"\n >\n <HugeiconsIcon icon={TextSubscriptIcon} className="size-4" />\n </ToggleGroupItem>\n </ToolbarTooltip>\n </ToggleGroup>\n\n <ToolbarSeparator />\n\n <div className="flex shrink-0 items-center gap-1">\n <ColorPicker\n label="Text color"\n icon={TextColorIcon}\n color={textColorValue}\n disabled={!canEdit}\n onTriggerMouseDown={preserveTextSelection}\n onTriggerPointerDown={preserveTextSelection}\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-40 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 <ToolbarSeparator />\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 <ToolbarSeparator />\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 <ToolbarSeparator />\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-40 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 <ToolbarSeparator />\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 <ToolbarSeparator />\n\n <div className="ml-auto flex flex-none 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-40"\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 defaultZoomScale = DOCX_EDITOR_DEFAULT_ZOOM_SCALE,\n fileName,\n isDark,\n onIsDarkChange,\n src,\n}: {\n className?: string\n defaultZoomScale?: number\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n src?: string\n}) {\n return (\n <DocxEditorContent\n className={className}\n defaultZoomScale={defaultZoomScale}\n effectiveIsDark={isDark}\n fileName={fileName}\n setIsDark={onIsDarkChange}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction DocxEditorContent({\n className,\n defaultZoomScale,\n effectiveIsDark,\n fileName,\n setIsDark,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n defaultZoomScale?: number\n effectiveIsDark: boolean\n fileName?: string\n setIsDark: (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 [viewportElement, setViewportElement] =\n React.useState<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 resolvedDefaultZoomScale = normalizeDocxZoomScale(defaultZoomScale)\n const [zoomScale, setZoomScale] = React.useState<number>(\n resolvedDefaultZoomScale\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 [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 { layout: pageLayout } = useDocxPageLayout(editor)\n const { importDocxFile, setDocumentTheme, status } = editor\n const [reportedPageCount, setReportedPageCount] = React.useState(0)\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, reportedPageCount]\n )\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(\n thumbnailEditor,\n thumbnailOptions\n )\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <EditorLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const renderTrackedChangeCard = React.useMemo(\n () => createDocxTrackedChangeCardRenderer(editor.documentTheme),\n [editor.documentTheme]\n )\n const renderCommentCard = React.useMemo(\n () => createDocxCommentCardRenderer(editor.documentTheme),\n [editor.documentTheme]\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const thumbnailSidebarOpen = Boolean(\n sidebarOpen && (pageCount || isLoadingDocument)\n )\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n const setViewportRef = React.useCallback((element: HTMLDivElement | null) => {\n viewportRef.current = element\n setViewportElement(element)\n }, [])\n const pageVirtualization = React.useMemo(\n () => ({\n enabled: true,\n overscan: 1,\n scrollElement: viewportElement,\n zoomScale: zoomScale / 100,\n }),\n [viewportElement, zoomScale]\n )\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(resolvedDefaultZoomScale)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [resolvedDefaultZoomScale, 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 setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url ? await loadDocxFile(url, displayFileName) : 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 }, [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(\n (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) return\n\n if (!page) {\n const pageStridePx =\n (pageLayout.pageHeightPx + pageLayout.viewportDefaults.pageGapPx) *\n (zoomScale / 100)\n\n viewport.scrollTo({\n top: Math.max(0, targetPageIndex * pageStridePx - 24),\n behavior: "auto",\n })\n return\n }\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 [pageLayout.pageHeightPx, pageLayout.viewportDefaults.pageGapPx, zoomScale]\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(resolvedDefaultZoomScale)\n setActivePage(1)\n setReportedPageCount(0)\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 onIsDarkChange={setIsDark}\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={thumbnailSidebarOpen}\n >\n <ScrollArea\n className="h-full"\n scrollFade\n viewportClassName="overscroll-contain"\n >\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\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 shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground"\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 <ScrollArea\n className="min-h-0 flex-1"\n style={{ backgroundColor: viewerBackgroundColor }}\n viewportClassName="overscroll-contain p-4"\n viewportRef={setViewportRef}\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 renderTrackedChangeCard={renderTrackedChangeCard}\n showComments={editor.showComments}\n renderCommentCard={renderCommentCard}\n loadingState={loadingState}\n pageBackgroundColor={\n editor.documentTheme === "dark" ? "#0a0a0a" : undefined\n }\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={pageVirtualization}\n deferInitialPaginationPaint={false}\n onPageCountChange={handlePageCountChange}\n />\n </div>\n </div>\n )}\n </ScrollArea>\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 useDocxComments,\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"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport { ColorPicker } from "@/components/ui/color-picker"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\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 { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/extend/document-viewer-sidebar"\nimport {\n createDocxCommentCardRenderer,\n createDocxTrackedChangeCardRenderer,\n} from "@/components/extend/docx-annotation-card"\nimport { FileThumbnail } from "@/components/extend/file-thumbnail"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nfunction ArrowExpandDiagonal01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="ArrowDownRight"\n tabler="IconArrowDownRight"\n hugeicons="ArrowExpandDiagonal01Icon"\n phosphor="ArrowDownRightIcon"\n remixicon="RiArrowRightDownLine"\n {...props}\n />\n )\n}\n\nfunction ArrowExpandDiagonal02Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="ArrowUpRight"\n tabler="IconArrowUpRight"\n hugeicons="ArrowExpandDiagonal02Icon"\n phosphor="ArrowUpRightIcon"\n remixicon="RiArrowRightUpLine"\n {...props}\n />\n )\n}\n\nfunction BorderAll01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Grid2x2"\n tabler="IconBorderAll"\n hugeicons="BorderAll01Icon"\n phosphor="GridFourIcon"\n remixicon="RiGridLine"\n {...props}\n />\n )\n}\n\nfunction BorderBottom01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelBottom"\n tabler="IconBorderBottom"\n hugeicons="BorderBottom01Icon"\n phosphor="SquareHalfBottomIcon"\n remixicon="RiLayoutBottomLine"\n {...props}\n />\n )\n}\n\nfunction BorderHorizontalGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="SeparatorHorizontal"\n tabler="IconBorderHorizontal"\n hugeicons="BorderHorizontalIcon"\n phosphor="MinusIcon"\n remixicon="RiSeparator"\n {...props}\n />\n )\n}\n\nfunction BorderInnerGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="SquarePlus"\n tabler="IconBorderInner"\n hugeicons="BorderInnerIcon"\n phosphor="PlusSquareIcon"\n remixicon="RiAddBoxLine"\n {...props}\n />\n )\n}\n\nfunction BorderLeft01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelLeft"\n tabler="IconBorderLeft"\n hugeicons="BorderLeft01Icon"\n phosphor="SquareHalfIcon"\n remixicon="RiLayoutLeftLine"\n {...props}\n />\n )\n}\n\nfunction BorderNone01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="SquareDashed"\n tabler="IconBorderNone"\n hugeicons="BorderNone01Icon"\n phosphor="SelectionIcon"\n remixicon="RiCheckboxBlankLine"\n {...props}\n />\n )\n}\n\nfunction BorderRight01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelRight"\n tabler="IconBorderRight"\n hugeicons="BorderRight01Icon"\n phosphor="SquareHalfIcon"\n remixicon="RiLayoutRightLine"\n {...props}\n />\n )\n}\n\nfunction BorderTop01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelTop"\n tabler="IconBorderTop"\n hugeicons="BorderTop01Icon"\n phosphor="AlignTopSimpleIcon"\n remixicon="RiLayoutTopLine"\n {...props}\n />\n )\n}\n\nfunction BorderVerticalGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="SeparatorVertical"\n tabler="IconBorderVertical"\n hugeicons="BorderVerticalIcon"\n phosphor="LineVerticalIcon"\n remixicon="RiLayoutColumnLine"\n {...props}\n />\n )\n}\n\nfunction LineGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Minus"\n tabler="IconMinus"\n hugeicons="LineIcon"\n phosphor="MinusIcon"\n remixicon="RiSubtractLine"\n {...props}\n />\n )\n}\n\nfunction Moon02Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Moon"\n tabler="IconMoon"\n hugeicons="Moon02Icon"\n phosphor="MoonIcon"\n remixicon="RiMoonLine"\n {...props}\n />\n )\n}\n\nfunction Sun03Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Sun"\n tabler="IconSun"\n hugeicons="Sun03Icon"\n phosphor="SunIcon"\n remixicon="RiSunLine"\n {...props}\n />\n )\n}\n\nfunction TextColorGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Baseline"\n tabler="IconTextColor"\n hugeicons="TextColorIcon"\n phosphor="TextAaIcon"\n remixicon="RiFontColor"\n {...props}\n />\n )\n}\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_EDITOR_DEFAULT_ZOOM_SCALE = 100\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\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\ntype DocxFontToggleValue =\n | "bold"\n | "italic"\n | "underline"\n | "strike"\n | "superscript"\n | "subscript"\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 BorderBottom01Glyph\n case "top":\n return BorderTop01Glyph\n case "left":\n return BorderLeft01Glyph\n case "right":\n return BorderRight01Glyph\n case "none":\n return BorderNone01Glyph\n case "inside":\n return BorderInnerGlyph\n case "inside-horizontal":\n return BorderHorizontalGlyph\n case "inside-vertical":\n return BorderVerticalGlyph\n case "diagonal-down":\n return ArrowExpandDiagonal01Glyph\n case "diagonal-up":\n return ArrowExpandDiagonal02Glyph\n case "horizontal-line":\n return LineGlyph\n default:\n return BorderAll01Glyph\n }\n}\n\nasync function loadDocxFile(\n url: string,\n displayFileName: string\n): Promise<File> {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n return new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\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 normalizeDocxZoomScale(value: number | undefined): number {\n return typeof value === "number" &&\n ZOOM_OPTIONS.includes(value as (typeof ZOOM_OPTIONS)[number])\n ? value\n : DOCX_EDITOR_DEFAULT_ZOOM_SCALE\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 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 ToolbarSeparator() {\n return <Separator orientation="vertical" className="mx-1 h-4 self-center" />\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="rounded-md 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 isLoading={isLoading}\n hasError={hasError}\n className={cn(\n "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",\n isActive && "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 onIsDarkChange,\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 onIsDarkChange: (checked: boolean) => 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 { showComments, setShowComments } = useDocxComments(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 = React.createElement(\n borderControlOptionIcon(\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].id\n : "all"\n ),\n { className: "size-4" }\n )\n const canEdit = !controlsDisabled && !isReadOnly\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n const fontToggleValues = React.useMemo<DocxFontToggleValue[]>(() => {\n const values: DocxFontToggleValue[] = []\n\n if (selectedRunStyle?.bold) values.push("bold")\n if (selectedRunStyle?.italic) values.push("italic")\n if (selectedRunStyle?.underline) values.push("underline")\n if (selectedRunStyle?.strike) values.push("strike")\n if (selectedRunStyle?.verticalAlign === "superscript") {\n values.push("superscript")\n }\n if (selectedRunStyle?.verticalAlign === "subscript") {\n values.push("subscript")\n }\n\n return values\n }, [selectedRunStyle])\n\n const preserveTextSelection = React.useCallback(\n (event: React.MouseEvent<HTMLElement> | React.PointerEvent<HTMLElement>) =>\n event.preventDefault(),\n []\n )\n const applyFontToggleValues = React.useCallback(\n (nextValues: DocxFontToggleValue[]) => {\n const changedValue =\n nextValues.find((value) => !fontToggleValues.includes(value)) ??\n fontToggleValues.find((value) => !nextValues.includes(value))\n\n if (changedValue === "bold") {\n editor.toggleBold()\n } else if (changedValue === "italic") {\n editor.toggleItalic()\n } else if (changedValue === "underline") {\n editor.toggleUnderline()\n } else if (changedValue === "strike") {\n editor.toggleStrike()\n } else if (changedValue === "superscript") {\n editor.toggleSuperscript()\n } else if (changedValue === "subscript") {\n editor.toggleSubscript()\n }\n },\n [editor, fontToggleValues]\n )\n\n return (\n <div className="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 <IconPlaceholder\n lucide="PanelLeft"\n tabler="IconLayoutSidebar"\n hugeicons="SidebarLeftIcon"\n phosphor="SidebarIcon"\n remixicon="RiLayoutLeftLine"\n className="size-4"\n />\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 const nextIsDark = documentTheme !== "dark"\n setDocumentTheme(nextIsDark ? "dark" : "light")\n onIsDarkChange(nextIsDark)\n }}\n >\n {documentTheme === "dark" ? (\n <Sun03Glyph className="size-4" />\n ) : (\n <Moon02Glyph 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 <IconPlaceholder\n lucide="FileDiff"\n tabler="IconFileDiff"\n hugeicons="FileDiffIcon"\n phosphor="GitDiffIcon"\n remixicon="RiFileHistoryLine"\n className="size-4"\n />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Show comments"\n active={showComments}\n disabled={controlsDisabled}\n onClick={() => setShowComments(!showComments)}\n >\n <IconPlaceholder\n lucide="MessageSquare"\n tabler="IconMessage"\n hugeicons="Comment01Icon"\n phosphor="ChatIcon"\n remixicon="RiChat1Line"\n className="size-4"\n />\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 <IconPlaceholder\n lucide="PencilOff"\n tabler="IconPencilOff"\n hugeicons="EditOffIcon"\n phosphor="PencilSlashIcon"\n remixicon="RiLockLine"\n className="size-4"\n />\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 <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n )}\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Download DOCX"\n disabled={controlsDisabled || editor.isImporting}\n onClick={editor.exportDocx}\n >\n <IconPlaceholder\n lucide="Download"\n tabler="IconDownload"\n hugeicons="Download01Icon"\n phosphor="DownloadSimpleIcon"\n remixicon="RiDownload2Line"\n className="size-4"\n />\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 <IconPlaceholder\n lucide="Undo2"\n tabler="IconArrowBackUp"\n hugeicons="Undo02Icon"\n phosphor="ArrowUUpLeftIcon"\n remixicon="RiArrowGoBackLine"\n className="size-4"\n />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Redo"\n disabled={!editor.canRedo || isReadOnly}\n onClick={editor.redo}\n >\n <IconPlaceholder\n lucide="Redo2"\n tabler="IconArrowForwardUp"\n hugeicons="Redo02Icon"\n phosphor="ArrowUUpRightIcon"\n remixicon="RiArrowGoForwardLine"\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <ToolbarSeparator />\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-40 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-40 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-40"\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-40"\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-40"\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 <ToolbarSeparator />\n\n <ToggleGroup\n className="shrink-0"\n disabled={!canEdit}\n multiple\n spacing="default"\n value={fontToggleValues}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onValueChange={(value) =>\n applyFontToggleValues(value as DocxFontToggleValue[])\n }\n >\n <ToolbarTooltip label="Bold">\n <ToggleGroupItem aria-label="Bold" size="sm" value="bold">\n <IconPlaceholder\n lucide="Bold"\n tabler="IconBold"\n hugeicons="TextBoldIcon"\n phosphor="TextBIcon"\n remixicon="RiBold"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Italic">\n <ToggleGroupItem aria-label="Italic" size="sm" value="italic">\n <IconPlaceholder\n lucide="Italic"\n tabler="IconItalic"\n hugeicons="TextItalicIcon"\n phosphor="TextItalicIcon"\n remixicon="RiItalic"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Underline">\n <ToggleGroupItem\n aria-label="Underline"\n size="sm"\n value="underline"\n >\n <IconPlaceholder\n lucide="Underline"\n tabler="IconUnderline"\n hugeicons="TextUnderlineIcon"\n phosphor="TextUnderlineIcon"\n remixicon="RiUnderline"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Strikethrough">\n <ToggleGroupItem\n aria-label="Strikethrough"\n size="sm"\n value="strike"\n >\n <IconPlaceholder\n lucide="Strikethrough"\n tabler="IconStrikethrough"\n hugeicons="TextStrikethroughIcon"\n phosphor="TextStrikethroughIcon"\n remixicon="RiStrikethrough"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Superscript">\n <ToggleGroupItem\n aria-label="Superscript"\n size="sm"\n value="superscript"\n >\n <IconPlaceholder\n lucide="Superscript"\n tabler="IconSuperscript"\n hugeicons="TextSuperscriptIcon"\n phosphor="TextSuperscriptIcon"\n remixicon="RiSuperscript"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Subscript">\n <ToggleGroupItem\n aria-label="Subscript"\n size="sm"\n value="subscript"\n >\n <IconPlaceholder\n lucide="Subscript"\n tabler="IconSubscript"\n hugeicons="TextSubscriptIcon"\n phosphor="TextSubscriptIcon"\n remixicon="RiSubscript"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n </ToggleGroup>\n\n <ToolbarSeparator />\n\n <div className="flex shrink-0 items-center gap-1">\n <ColorPicker\n label="Text color"\n icon={TextColorGlyph}\n color={textColorValue}\n disabled={!canEdit}\n onTriggerMouseDown={preserveTextSelection}\n onTriggerPointerDown={preserveTextSelection}\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 <IconPlaceholder\n lucide="Highlighter"\n tabler="IconHighlight"\n hugeicons="HighlighterIcon"\n phosphor="HighlighterIcon"\n remixicon="RiMarkPenLine"\n className="size-4"\n />\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-40 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 <IconPlaceholder\n lucide="Link"\n tabler="IconLink"\n hugeicons="Link02Icon"\n phosphor="LinkIcon"\n remixicon="RiLink"\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <ToolbarSeparator />\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 <IconPlaceholder\n lucide="AlignLeft"\n tabler="IconAlignLeft"\n hugeicons="TextAlignLeft01Icon"\n phosphor="TextAlignLeftIcon"\n remixicon="RiAlignLeft"\n className="size-4"\n />\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 <IconPlaceholder\n lucide="AlignCenter"\n tabler="IconAlignCenter"\n hugeicons="TextAlignCenterIcon"\n phosphor="TextAlignCenterIcon"\n remixicon="RiAlignCenter"\n className="size-4"\n />\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 <IconPlaceholder\n lucide="AlignRight"\n tabler="IconAlignRight"\n hugeicons="TextAlignRight01Icon"\n phosphor="TextAlignRightIcon"\n remixicon="RiAlignRight"\n className="size-4"\n />\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 <IconPlaceholder\n lucide="AlignJustify"\n tabler="IconAlignJustified"\n hugeicons="TextAlignJustifyLeftIcon"\n phosphor="TextAlignJustifyIcon"\n remixicon="RiAlignJustify"\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <ToolbarSeparator />\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 <IconPlaceholder\n lucide="Columns3Icon"\n tabler="IconLayoutColumns"\n hugeicons="LeftToRightListBulletIcon"\n phosphor="ColumnsIcon"\n remixicon="RiLayoutColumnLine"\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 <IconPlaceholder\n lucide="ListOrdered"\n tabler="IconListNumbers"\n hugeicons="LeftToRightListNumberIcon"\n phosphor="ListNumbersIcon"\n remixicon="RiListOrdered"\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <ToolbarSeparator />\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 {borderTriggerIcon}\n {borderTriggerLabel}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-40 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 <BorderOptionIcon className="size-4 text-muted-foreground" />\n {option.label}\n </DropdownMenuCheckboxItem>\n </React.Fragment>\n )\n })}\n </DropdownMenuContent>\n </DropdownMenu>\n\n <ToolbarSeparator />\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 <IconPlaceholder\n lucide="ImagePlus"\n tabler="IconPhotoPlus"\n hugeicons="ImageAdd01Icon"\n phosphor="ImageIcon"\n remixicon="RiImageAddLine"\n className="size-4"\n />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Insert table"\n disabled={!canEdit}\n onClick={editor.insertTable}\n >\n <IconPlaceholder\n lucide="TableIcon"\n tabler="IconTable"\n hugeicons="TableIcon"\n phosphor="TableIcon"\n remixicon="RiTableLine"\n className="size-4"\n />\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 <IconPlaceholder\n lucide="Columns3Cog"\n tabler="IconColumns3"\n hugeicons="ColumnsThreeCogIcon"\n phosphor="ColumnsIcon"\n remixicon="RiLayoutColumnLine"\n className="size-4"\n />\n {activeColumns ? `${activeColumns.count} cols` : "1 col"}\n </div>\n </ToolbarTooltip>\n </div>\n\n <ToolbarSeparator />\n\n <div className="ml-auto flex flex-none 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 <IconPlaceholder\n lucide="CircleMinus"\n tabler="IconCircleMinus"\n hugeicons="MinusSignCircleIcon"\n phosphor="MinusCircleIcon"\n remixicon="RiIndeterminateCircleLine"\n className="size-4"\n />\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-40"\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 <IconPlaceholder\n lucide="CirclePlusIcon"\n tabler="IconCirclePlusFilled"\n hugeicons="PlusSignCircleIcon"\n phosphor="PlusCircleIcon"\n remixicon="RiAddCircleFill"\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function DocxEditorPreview({\n className,\n defaultZoomScale = DOCX_EDITOR_DEFAULT_ZOOM_SCALE,\n fileName,\n isDark,\n onIsDarkChange,\n src,\n}: {\n className?: string\n defaultZoomScale?: number\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n src?: string\n}) {\n return (\n <DocxEditorContent\n className={className}\n defaultZoomScale={defaultZoomScale}\n effectiveIsDark={isDark}\n fileName={fileName}\n setIsDark={onIsDarkChange}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction DocxEditorContent({\n className,\n defaultZoomScale,\n effectiveIsDark,\n fileName,\n setIsDark,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n defaultZoomScale?: number\n effectiveIsDark: boolean\n fileName?: string\n setIsDark: (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 [viewportElement, setViewportElement] =\n React.useState<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 resolvedDefaultZoomScale = normalizeDocxZoomScale(defaultZoomScale)\n const [zoomScale, setZoomScale] = React.useState<number>(\n resolvedDefaultZoomScale\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 [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 { layout: pageLayout } = useDocxPageLayout(editor)\n const { importDocxFile, setDocumentTheme, status } = editor\n const [reportedPageCount, setReportedPageCount] = React.useState(0)\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, reportedPageCount]\n )\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(\n thumbnailEditor,\n thumbnailOptions\n )\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <EditorLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const renderTrackedChangeCard = React.useMemo(\n () => createDocxTrackedChangeCardRenderer(editor.documentTheme),\n [editor.documentTheme]\n )\n const renderCommentCard = React.useMemo(\n () => createDocxCommentCardRenderer(editor.documentTheme),\n [editor.documentTheme]\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const thumbnailSidebarOpen = Boolean(\n sidebarOpen && (pageCount || isLoadingDocument)\n )\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n const setViewportRef = React.useCallback((element: HTMLDivElement | null) => {\n viewportRef.current = element\n setViewportElement(element)\n }, [])\n const pageVirtualization = React.useMemo(\n () => ({\n enabled: true,\n overscan: 1,\n scrollElement: viewportElement,\n zoomScale: zoomScale / 100,\n }),\n [viewportElement, zoomScale]\n )\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(resolvedDefaultZoomScale)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [resolvedDefaultZoomScale, 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 setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url ? await loadDocxFile(url, displayFileName) : 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 }, [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(\n (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) return\n\n if (!page) {\n const pageStridePx =\n (pageLayout.pageHeightPx + pageLayout.viewportDefaults.pageGapPx) *\n (zoomScale / 100)\n\n viewport.scrollTo({\n top: Math.max(0, targetPageIndex * pageStridePx - 24),\n behavior: "auto",\n })\n return\n }\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 [pageLayout.pageHeightPx, pageLayout.viewportDefaults.pageGapPx, zoomScale]\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(resolvedDefaultZoomScale)\n setActivePage(1)\n setReportedPageCount(0)\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 onIsDarkChange={setIsDark}\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={thumbnailSidebarOpen}\n >\n <ScrollArea\n className="h-full"\n scrollFade\n viewportClassName="overscroll-contain"\n >\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\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 shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground"\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 <ScrollArea\n className="min-h-0 flex-1"\n style={{ backgroundColor: viewerBackgroundColor }}\n viewportClassName="overscroll-contain p-4"\n viewportRef={setViewportRef}\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 <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\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 renderTrackedChangeCard={renderTrackedChangeCard}\n showComments={editor.showComments}\n renderCommentCard={renderCommentCard}\n loadingState={loadingState}\n pageBackgroundColor={\n editor.documentTheme === "dark" ? "#0a0a0a" : undefined\n }\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={pageVirtualization}\n deferInitialPaginationPaint={false}\n onPageCountChange={handlePageCountChange}\n />\n </div>\n </div>\n )}\n </ScrollArea>\n </div>\n </div>\n )\n}\n'export function DocxEditorSource() {return (diff --git a/apps/v4/components/docx-viewer-docs.tsx b/apps/v4/components/docx-viewer-docs.tsxindex 2d1f7db..8804a3f 100644--- a/apps/v4/components/docx-viewer-docs.tsx+++ b/apps/v4/components/docx-viewer-docs.tsx@@ -67,7 +67,7 @@ export function DocxViewerExample() {}`const docxViewerSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n useDocxComments,\n useDocxEditor,\n useDocxPageLayout,\n useDocxTrackChanges,\n useDocxViewerThumbnails,\n type DocxDocumentTheme,\n type DocxEditorController,\n type DocxPageThumbnailItem,\n} from "@extend-ai/react-docx"\nimport {\n Comment01Icon,\n Download01Icon,\n FileDiffIcon,\n MinusSignCircleIcon,\n Moon02Icon,\n MoreHorizontalIcon,\n PlusSignCircleIcon,\n SidebarLeftIcon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { useVirtualizer } from "@tanstack/react-virtual"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/extend/document-viewer-sidebar"\nimport {\n createDocxCommentCardRenderer,\n createDocxTrackedChangeCardRenderer,\n} from "@/components/extend/docx-annotation-card"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { FileThumbnail } from "@/components/extend/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 { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_THUMBNAIL_LIST_PADDING = 16\nconst DOCX_THUMBNAIL_ROW_ESTIMATE = 172\nconst DEFAULT_ZOOM = 50\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"\nconst DOCX_THUMBNAIL_FOCUS_RING_CLASS =\n "group-focus-visible/docx-thumbnail-sidebar:ring-2 group-focus-visible/docx-thumbnail-sidebar:ring-ring group-focus-visible/docx-thumbnail-sidebar:ring-offset-1 group-focus-visible/docx-thumbnail-sidebar:ring-offset-background"\nconst DOCX_THUMBNAIL_PREFETCH_ROWS = 4\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n sourceUrl: string | undefined\n}\n\ntype DocxActivePageStore = {\n getSnapshot: () => number\n setActivePage: React.Dispatch<React.SetStateAction<number>>\n subscribe: (listener: () => void) => () => void\n}\n\ntype DocxThumbnailRenderWindowState = {\n visiblePageIndexes: number[]\n prefetchPageIndexes: number[]\n}\n\nfunction createDocxActivePageStore(): DocxActivePageStore {\n let activePage = 1\n const listeners = new Set<() => void>()\n\n return {\n getSnapshot: () => activePage,\n setActivePage: (nextPage) => {\n const value =\n typeof nextPage === "function" ? nextPage(activePage) : nextPage\n const normalizedValue = Math.max(1, Math.round(value || 1))\n\n if (normalizedValue === activePage) return\n\n activePage = normalizedValue\n listeners.forEach((listener) => listener())\n },\n subscribe: (listener) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n }\n}\n\nfunction useDocxActivePage(activePageStore: DocxActivePageStore) {\n return React.useSyncExternalStore(\n activePageStore.subscribe,\n activePageStore.getSnapshot,\n activePageStore.getSnapshot\n )\n}\n\nfunction areNumberArraysEqual(left: number[], right: number[]) {\n return (\n left.length === right.length &&\n left.every((value, index) => value === right[index])\n )\n}\n\nasync function loadDocxFile(\n url: string,\n displayFileName: string\n): Promise<File> {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n return new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\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 ensureDocxExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(".docx")\n ? fileName\n : `${fileName}.docx`\n}\n\nfunction downloadBlob(blob: Blob, fileName: string) {\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = fileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nasync function downloadDocxFile({\n file,\n fileName,\n url,\n}: {\n file?: File\n fileName: string\n url?: string\n}) {\n if (file) {\n downloadBlob(file, ensureDocxExtension(fileName))\n return\n }\n\n if (!url) return\n\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to download DOCX (${response.status})`)\n }\n\n downloadBlob(await response.blob(), ensureDocxExtension(fileName))\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 normalizeDocxZoomScale(value: number | undefined): number {\n return typeof value === "number" &&\n ZOOM_OPTIONS.includes(value as (typeof ZOOM_OPTIONS)[number])\n ? value\n : DEFAULT_ZOOM\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) return\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => {\n window.clearTimeout(timeoutId)\n setShowSpinner(false)\n }\n }, [delayMs, isLoading])\n\n return isLoading && showSpinner\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 isInteractiveViewerTarget(target: EventTarget | null) {\n return (\n target instanceof Element &&\n Boolean(\n target.closest(\n \'a[href], button, input, select, textarea, [contenteditable="true"], [role="button"], [role="link"]\'\n )\n )\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 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 DocxFileActionsMenu({\n controlsDisabled,\n downloadDisabled,\n isPreparingDownload,\n isDark,\n onDownload,\n onShowCommentsChange,\n onShowTrackedChangesChange,\n onIsDarkChange,\n onUploadClick,\n showComments,\n showDownloadButton,\n showNightRenderToggle,\n showTrackedChanges,\n showUploadButton,\n}: {\n controlsDisabled: boolean\n downloadDisabled: boolean\n isPreparingDownload: boolean\n isDark: boolean\n onDownload: () => void\n onShowCommentsChange: (checked: boolean) => void\n onShowTrackedChangesChange: (checked: boolean) => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n showComments: boolean\n showDownloadButton: boolean\n showNightRenderToggle: boolean\n showTrackedChanges: boolean\n showUploadButton: boolean\n}) {\n const showFileActions = showDownloadButton || showUploadButton\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open DOCX actions"\n >\n <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-52">\n {showNightRenderToggle ? (\n <>\n <DropdownMenuCheckboxItem\n checked={isDark}\n disabled={controlsDisabled}\n variant="switch"\n onCheckedChange={(checked) => onIsDarkChange(checked === true)}\n >\n <span className="flex min-w-0 items-center gap-2">\n <HugeiconsIcon icon={Moon02Icon} className="size-4" />\n Dark mode\n </span>\n </DropdownMenuCheckboxItem>\n <DropdownMenuSeparator />\n </>\n ) : null}\n <DropdownMenuCheckboxItem\n checked={showComments}\n disabled={controlsDisabled}\n variant="switch"\n onCheckedChange={(checked) => onShowCommentsChange(checked === true)}\n >\n <span className="flex min-w-0 items-center gap-2">\n <HugeiconsIcon icon={Comment01Icon} className="size-4" />\n Comments\n </span>\n </DropdownMenuCheckboxItem>\n <DropdownMenuCheckboxItem\n checked={showTrackedChanges}\n disabled={controlsDisabled}\n variant="switch"\n onCheckedChange={(checked) =>\n onShowTrackedChangesChange(checked === true)\n }\n >\n <span className="flex min-w-0 items-center gap-2">\n <HugeiconsIcon icon={FileDiffIcon} className="size-4" />\n Edits\n </span>\n </DropdownMenuCheckboxItem>\n {showFileActions ? <DropdownMenuSeparator /> : null}\n {showDownloadButton ? (\n <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>\n {isPreparingDownload ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n )}\n Download\n </DropdownMenuItem>\n ) : null}\n {showUploadButton ? (\n <DropdownMenuItem onClick={onUploadClick}>\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction DocxPageNumberControl({\n activePageStore,\n controlsDisabled,\n onPageChange,\n pageCount,\n}: {\n activePageStore: DocxActivePageStore\n controlsDisabled: boolean\n onPageChange: (pageNumber: number) => void\n pageCount: number\n}) {\n const activePage = useDocxActivePage(activePageStore)\n const inputRef = React.useRef<HTMLInputElement>(null)\n const displayPage = pageCount ? activePage : 1\n const [isEditing, setIsEditing] = React.useState(false)\n const [draftPage, setDraftPage] = React.useState(() => String(displayPage))\n\n React.useEffect(() => {\n if (!isEditing) {\n setDraftPage(String(displayPage))\n }\n }, [displayPage, isEditing])\n\n React.useEffect(() => {\n if (!isEditing) return\n\n inputRef.current?.focus()\n inputRef.current?.select()\n }, [isEditing])\n\n const applyPageDraft = React.useCallback(\n (value: string) => {\n const trimmedValue = value.trim()\n\n if (!trimmedValue) return\n\n const parsedPage = Number(trimmedValue)\n\n if (!Number.isInteger(parsedPage)) return\n\n onPageChange(Math.min(Math.max(parsedPage, 1), Math.max(pageCount, 1)))\n },\n [onPageChange, pageCount]\n )\n\n return (\n <div className="flex items-center text-sm whitespace-nowrap text-primary">\n <span>Page</span>\n {isEditing ? (\n <Input\n ref={inputRef}\n aria-label="Page number"\n inputMode="numeric"\n pattern="[0-9]*"\n size="sm"\n value={draftPage}\n className="mx-1 w-14 min-w-14 rounded-md [&_[data-slot=input]]:text-center"\n onBlur={() => setIsEditing(false)}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) => {\n const nextValue = event.target.value\n\n setDraftPage(nextValue)\n applyPageDraft(nextValue)\n }}\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === "Enter" || event.key === "Escape") {\n event.currentTarget.blur()\n }\n }}\n />\n ) : (\n <Button\n type="button"\n variant="ghost"\n size="sm"\n className="font-normal"\n aria-label={`Current page ${displayPage}. Edit page number`}\n disabled={controlsDisabled || !pageCount}\n onClick={() => {\n setDraftPage(String(displayPage))\n setIsEditing(true)\n }}\n >\n {displayPage}\n </Button>\n )}\n <span>of {pageCount || "-"}</span>\n </div>\n )\n}\n\nfunction DocxToolbar({\n activePageStore,\n controlsDisabled,\n isDark,\n isPreparingDownload,\n onDownload,\n onIsDarkChange,\n onPageChange,\n onShowCommentsChange,\n onShowTrackedChangesChange,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showComments,\n showDownloadButton = true,\n showNightRenderToggle,\n showTrackedChanges,\n showUploadButton = true,\n toolbarActions,\n zoomScale,\n}: {\n activePageStore: DocxActivePageStore\n controlsDisabled: boolean\n isDark: boolean\n isPreparingDownload: boolean\n onDownload: () => void\n onIsDarkChange: (checked: boolean) => void\n onPageChange: (pageNumber: number) => void\n onShowCommentsChange: (checked: boolean) => void\n onShowTrackedChangesChange: (checked: boolean) => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showComments: boolean\n showDownloadButton?: boolean\n showNightRenderToggle: boolean\n showTrackedChanges: boolean\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\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 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2">\n <TooltipProvider>\n <div className="flex min-w-0 flex-wrap 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 <DocxPageNumberControl\n activePageStore={activePageStore}\n controlsDisabled={controlsDisabled}\n onPageChange={onPageChange}\n pageCount={pageCount}\n />\n </div>\n <div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n 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 </div>\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <DocxFileActionsMenu\n controlsDisabled={controlsDisabled}\n downloadDisabled={controlsDisabled || isPreparingDownload}\n isPreparingDownload={isPreparingDownload}\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onShowCommentsChange={onShowCommentsChange}\n onShowTrackedChangesChange={onShowTrackedChangesChange}\n onUploadClick={onUploadClick}\n showComments={showComments}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showTrackedChanges={showTrackedChanges}\n showUploadButton={showUploadButton}\n />\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="rounded-md 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 isLoading={isLoading}\n hasError={hasError}\n className={cn(\n "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",\n isActive && "shadow-sm"\n )}\n />\n )\n}\n\nfunction DocxThumbnailSidebarList({\n activePage,\n displayFileName,\n isLoadingDocument,\n onSelectPage,\n onThumbnailRenderWindowChange,\n pageCount,\n sidebarOpen,\n thumbnails,\n}: {\n activePage: number\n displayFileName: string\n isLoadingDocument: boolean\n onSelectPage: (pageNumber: number) => void\n onThumbnailRenderWindowChange: (\n renderWindow: DocxThumbnailRenderWindowState\n ) => void\n pageCount: number\n sidebarOpen: boolean\n thumbnails: DocxPageThumbnailItem[]\n}) {\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const thumbnailListboxId = React.useId()\n const visibleThumbnails = React.useMemo(\n () => thumbnails.slice(0, pageCount || 0),\n [pageCount, thumbnails]\n )\n const activeDescendantId =\n activePage > 0 && visibleThumbnails.length\n ? `${thumbnailListboxId}-page-${activePage}`\n : undefined\n const virtualizer = useVirtualizer({\n count: visibleThumbnails.length,\n estimateSize: () => DOCX_THUMBNAIL_ROW_ESTIMATE,\n getItemKey: (index) => visibleThumbnails[index]?.pageIndex ?? index,\n getScrollElement: () => viewportRef.current,\n overscan: 3,\n })\n const virtualItems = virtualizer.getVirtualItems()\n const renderWindowSignature = virtualItems\n .map((virtualRow) => virtualRow.index)\n .join(",")\n\n React.useEffect(() => {\n if (!sidebarOpen || isLoadingDocument || !visibleThumbnails.length) {\n onThumbnailRenderWindowChange({\n prefetchPageIndexes: [],\n visiblePageIndexes: [],\n })\n return\n }\n\n const visiblePageIndexes = virtualItems\n .map((virtualRow) => visibleThumbnails[virtualRow.index]?.pageIndex)\n .filter((pageIndex): pageIndex is number => pageIndex !== undefined)\n\n const firstVirtualIndex = virtualItems[0]?.index ?? 0\n const lastVirtualIndex =\n virtualItems[virtualItems.length - 1]?.index ?? firstVirtualIndex\n const firstPrefetchIndex = Math.max(\n 0,\n firstVirtualIndex - DOCX_THUMBNAIL_PREFETCH_ROWS\n )\n const lastPrefetchIndex = Math.min(\n visibleThumbnails.length - 1,\n lastVirtualIndex + DOCX_THUMBNAIL_PREFETCH_ROWS\n )\n const visiblePageIndexSet = new Set(visiblePageIndexes)\n const prefetchPageIndexes: number[] = []\n\n for (\n let index = firstPrefetchIndex;\n index <= lastPrefetchIndex;\n index += 1\n ) {\n const pageIndex = visibleThumbnails[index]?.pageIndex\n\n if (pageIndex !== undefined && !visiblePageIndexSet.has(pageIndex)) {\n prefetchPageIndexes.push(pageIndex)\n }\n }\n\n onThumbnailRenderWindowChange({\n prefetchPageIndexes,\n visiblePageIndexes,\n })\n }, [\n isLoadingDocument,\n onThumbnailRenderWindowChange,\n renderWindowSignature,\n sidebarOpen,\n visibleThumbnails,\n virtualItems,\n ])\n\n React.useEffect(() => {\n if (!sidebarOpen || activePage < 1 || !visibleThumbnails.length) return\n\n virtualizer.scrollToIndex(\n Math.min(activePage - 1, visibleThumbnails.length - 1),\n { align: "auto" }\n )\n }, [activePage, sidebarOpen, virtualizer, visibleThumbnails.length])\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (pageCount < 1) return\n\n const currentPage = activePage > 0 ? activePage : 1\n let nextPage: number | null = null\n\n if (event.key === "ArrowDown") {\n nextPage = Math.min(pageCount, currentPage + 1)\n } else if (event.key === "ArrowUp") {\n nextPage = Math.max(1, currentPage - 1)\n } else if (event.key === "Home") {\n nextPage = 1\n } else if (event.key === "End") {\n nextPage = pageCount\n }\n\n if (nextPage === null) return\n\n event.preventDefault()\n onSelectPage(nextPage)\n },\n [activePage, onSelectPage, pageCount]\n )\n\n return (\n <ScrollArea\n className="h-full"\n scrollFade\n viewportClassName="group/docx-thumbnail-sidebar focus-visible:ring-0 focus-visible:ring-offset-0"\n viewportProps={{\n "aria-activedescendant": activeDescendantId,\n "aria-busy": isLoadingDocument || undefined,\n "aria-label": "DOCX pages",\n onKeyDown: handleKeyDown,\n onMouseDown: (event) => {\n event.currentTarget.focus({ preventScroll: true })\n },\n role: "listbox",\n tabIndex: 0,\n }}\n viewportRef={viewportRef}\n >\n {isLoadingDocument ? (\n <div className="p-4">\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </div>\n ) : visibleThumbnails.length ? (\n <div\n className="relative"\n style={{\n height:\n virtualizer.getTotalSize() + DOCX_THUMBNAIL_LIST_PADDING * 2,\n }}\n >\n {virtualItems.map((virtualRow) => {\n const thumbnail = visibleThumbnails[virtualRow.index]\n if (!thumbnail) return null\n\n return (\n <div\n key={virtualRow.key}\n ref={virtualizer.measureElement}\n data-index={virtualRow.index}\n className={cn(\n "absolute top-0 right-3 left-3 pb-3 [contain:layout]",\n thumbnail.pageNumber === activePage && "z-10"\n )}\n style={{\n transform: `translateY(${\n virtualRow.start + DOCX_THUMBNAIL_LIST_PADDING\n }px)`,\n }}\n >\n <div\n id={`${thumbnailListboxId}-page-${thumbnail.pageNumber}`}\n role="option"\n aria-current={\n thumbnail.pageNumber === activePage ? "page" : undefined\n }\n aria-label={`Page ${thumbnail.pageNumber}`}\n aria-posinset={thumbnail.pageNumber}\n aria-selected={thumbnail.pageNumber === activePage}\n aria-setsize={pageCount}\n data-docx-viewer-thumbnail-option={thumbnail.pageNumber}\n className={cn(\n "flex h-auto w-full cursor-default flex-col items-center gap-2 rounded-md p-2 text-xs transition-shadow outline-none select-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground",\n thumbnail.pageNumber === activePage &&\n DOCX_THUMBNAIL_FOCUS_RING_CLASS\n )}\n onClick={() => onSelectPage(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.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 </div>\n </div>\n )\n })}\n </div>\n ) : null}\n </ScrollArea>\n )\n}\n\nfunction DocxThumbnailSidebarContent({\n activePageStore,\n displayFileName,\n editor,\n isLoadingDocument,\n onSelectPage,\n pageCount,\n reportedPageCount,\n sidebarOpen,\n}: {\n activePageStore: DocxActivePageStore\n displayFileName: string\n editor: DocxEditorController\n isLoadingDocument: boolean\n onSelectPage: (pageNumber: number) => void\n pageCount: number\n reportedPageCount: number\n sidebarOpen: boolean\n}) {\n const [thumbnailRenderWindow, setThumbnailRenderWindow] =\n React.useState<DocxThumbnailRenderWindowState>({\n prefetchPageIndexes: [],\n visiblePageIndexes: [],\n })\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n // Detached thumbnail rendering handles offscreen pages; keep the raster\n // queue dormant while the sidebar is closed.\n disabled: !sidebarOpen,\n pixelRatio: 2,\n renderWindow: thumbnailRenderWindow,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n [sidebarOpen, thumbnailRenderWindow]\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const activePage = useDocxActivePage(activePageStore)\n const handleThumbnailRenderWindowChange = React.useCallback(\n (nextRenderWindow: DocxThumbnailRenderWindowState) => {\n setThumbnailRenderWindow((currentRenderWindow) => {\n if (\n areNumberArraysEqual(\n currentRenderWindow.visiblePageIndexes,\n nextRenderWindow.visiblePageIndexes\n ) &&\n areNumberArraysEqual(\n currentRenderWindow.prefetchPageIndexes,\n nextRenderWindow.prefetchPageIndexes\n )\n ) {\n return currentRenderWindow\n }\n\n return nextRenderWindow\n })\n },\n []\n )\n\n if (!sidebarOpen) return null\n\n return (\n <DocxThumbnailSidebarList\n activePage={activePage}\n displayFileName={displayFileName}\n isLoadingDocument={isLoadingDocument}\n onSelectPage={onSelectPage}\n onThumbnailRenderWindowChange={handleThumbnailRenderWindowChange}\n pageCount={pageCount}\n sidebarOpen={sidebarOpen}\n thumbnails={thumbnails}\n />\n )\n}\n\nexport function DocxViewerPreview({\n className,\n defaultZoom = DEFAULT_ZOOM,\n fileName,\n isDark,\n onIsDarkChange,\n showDownload = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n}: {\n className?: string\n defaultZoom?: number\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n showDownload?: boolean\n showToolbar?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n}) {\n return (\n <DocxViewerContent\n className={className}\n defaultZoom={defaultZoom}\n effectiveIsDark={isDark}\n fileName={fileName}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n showDownload={showDownload}\n showToolbar={showToolbar}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n url={src}\n />\n )\n}\n\nfunction DocxViewerContent({\n className,\n defaultZoom,\n effectiveIsDark,\n fileName,\n setNightRenderEnabled,\n shouldRenderNightMode,\n showDownload,\n showToolbar = true,\n showUpload,\n toolbarActions,\n url,\n}: {\n className?: string\n defaultZoom?: number\n effectiveIsDark: boolean\n fileName?: string\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n showDownload: boolean\n showToolbar?: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewportElement, setViewportElement] =\n React.useState<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const activePageStore = React.useMemo(createDocxActivePageStore, [])\n const resolvedDefaultZoomScale = normalizeDocxZoomScale(defaultZoom)\n const activeUploadedDocxFile =\n uploadedDocxFile?.sourceUrl === url ? uploadedDocxFile : null\n const documentKey = activeUploadedDocxFile?.identity ?? url ?? ""\n const setActivePage = activePageStore.setActivePage\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n activeUploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [activeUploadedDocxFile?.file.name, fileName, 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 { layout: pageLayout } = useDocxPageLayout(editor)\n const { importDocxFile, setDocumentTheme, status } = editor\n const { showComments, setShowComments } = useDocxComments(editor)\n const { showTrackedChanges, setShowTrackedChanges } =\n useDocxTrackChanges(editor)\n const [reportedPageCount, setReportedPageCount] = React.useState(0)\n const [zoomScaleState, setZoomScaleState] = React.useState({\n documentKey: "",\n value: resolvedDefaultZoomScale,\n })\n const zoomScale =\n zoomScaleState.documentKey === documentKey\n ? zoomScaleState.value\n : resolvedDefaultZoomScale\n const setZoomScale = React.useCallback<\n React.Dispatch<React.SetStateAction<number>>\n >(\n (nextZoomScale) => {\n setZoomScaleState((currentState) => {\n const currentZoomScale =\n currentState.documentKey === documentKey\n ? currentState.value\n : resolvedDefaultZoomScale\n const value =\n typeof nextZoomScale === "function"\n ? nextZoomScale(currentZoomScale)\n : nextZoomScale\n\n return { documentKey, value }\n })\n },\n [documentKey, resolvedDefaultZoomScale]\n )\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <ViewerLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const documentTheme = effectiveIsDark ? "dark" : "light"\n const renderTrackedChangeCard = React.useMemo(\n () => createDocxTrackedChangeCardRenderer(documentTheme),\n [documentTheme]\n )\n const renderCommentCard = React.useMemo(\n () => createDocxCommentCardRenderer(documentTheme),\n [documentTheme]\n )\n const hasDocument = Boolean(url || activeUploadedDocxFile)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const thumbnailSidebarVisible = Boolean(\n sidebarOpen && (pageCount || isLoadingDocument)\n )\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n const setViewportRef = React.useCallback((element: HTMLDivElement | null) => {\n viewportRef.current = element\n setViewportElement(element)\n }, [])\n const pageVirtualization = React.useMemo(\n () => ({\n enabled: true,\n overscan: 1,\n scrollElement: viewportElement,\n zoomScale: zoomScale / 100,\n }),\n [viewportElement, zoomScale]\n )\n const handleDownload = React.useCallback(async () => {\n if (isPreparingDownload) return\n if (!activeUploadedDocxFile && !url) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadDocxFile({\n file: activeUploadedDocxFile?.file,\n fileName: displayFileName,\n url,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [activeUploadedDocxFile, displayFileName, isPreparingDownload, url])\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [documentKey, setActivePage])\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 const frame = window.requestAnimationFrame(() => {\n setLoadError(status)\n setIsLoadingDocument(false)\n })\n\n return () => window.cancelAnimationFrame(frame)\n }\n }, [status])\n\n // Imports mutate the shared editor instance; concurrent calls (effect\n // re-runs, StrictMode double-invoke) race inside the parser and surface as\n // bogus "Invalid DOCX ZIP" errors, so every import is chained through here.\n const importQueueRef = React.useRef<Promise<void>>(Promise.resolve())\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n // Superseded while queued — let the newest import run instead.\n if (!isCurrent) return\n if (!activeUploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n activeUploadedDocxFile?.file ??\n (url ? await loadDocxFile(url, displayFileName) : 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 importQueueRef.current = importQueueRef.current.then(load)\n\n return () => {\n isCurrent = false\n }\n }, [\n activeUploadedDocxFile,\n displayFileName,\n importDocxFile,\n setActivePage,\n url,\n ])\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 activePageStore.setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [activePageStore, 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(\n (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) return\n\n if (!page) {\n const pageStridePx =\n (pageLayout.pageHeightPx + pageLayout.viewportDefaults.pageGapPx) *\n (zoomScale / 100)\n\n viewport.scrollTo({\n top: Math.max(0, targetPageIndex * pageStridePx - 24),\n behavior: "auto",\n })\n return\n }\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 pageLayout.pageHeightPx,\n pageLayout.viewportDefaults.pageGapPx,\n setActivePage,\n zoomScale,\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(resolvedDefaultZoomScale)\n setActivePage(1)\n setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n sourceUrl: url,\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=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n {showToolbar ? (\n <DocxToolbar\n activePageStore={activePageStore}\n controlsDisabled={controlsDisabled}\n isDark={effectiveIsDark}\n isPreparingDownload={isPreparingDownload}\n onDownload={handleDownload}\n onIsDarkChange={setNightRenderEnabled}\n onPageChange={scrollToPage}\n onShowCommentsChange={setShowComments}\n onShowTrackedChangesChange={setShowTrackedChanges}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showComments={showComments}\n showDownloadButton={showDownload}\n showNightRenderToggle={shouldRenderNightMode}\n showTrackedChanges={showTrackedChanges}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n zoomScale={zoomScale}\n />\n ) : null}\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={thumbnailSidebarVisible}\n >\n <DocxThumbnailSidebarContent\n activePageStore={activePageStore}\n displayFileName={displayFileName}\n editor={editor}\n isLoadingDocument={isLoadingDocument}\n onSelectPage={scrollToPage}\n pageCount={pageCount}\n reportedPageCount={reportedPageCount}\n sidebarOpen={thumbnailSidebarVisible}\n />\n </DocumentViewerThumbnailSidebar>\n <ScrollArea\n className="min-h-0 flex-1"\n style={{ backgroundColor: viewerBackgroundColor }}\n viewportClassName="px-4 py-6"\n viewportProps={{\n "aria-label": "DOCX document",\n onMouseDown: (event) => {\n if (isInteractiveViewerTarget(event.target)) return\n event.currentTarget.focus({ preventScroll: true })\n },\n tabIndex: 0,\n }}\n viewportRef={setViewportRef}\n >\n {!url && !activeUploadedDocxFile ? (\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">\n Upload a Word document to preview\n </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 <div className="mt-1 text-muted-foreground">\n Legacy <code>.doc</code> support is limited and experimental;\n convert to DOCX for best fidelity.\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 Word document\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="flex min-h-full w-max min-w-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 showTrackedChanges={showTrackedChanges}\n renderTrackedChangeCard={renderTrackedChangeCard}\n showComments={showComments}\n renderCommentCard={renderCommentCard}\n loadingState={loadingState}\n pageBackgroundColor={effectiveIsDark ? "#0a0a0a" : undefined}\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={pageVirtualization}\n deferInitialPaginationPaint={false}\n onPageCountChange={handlePageCountChange}\n />\n </div>\n </div>\n )}\n </ScrollArea>\n </div>\n </div>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n useDocxComments,\n useDocxEditor,\n useDocxPageLayout,\n useDocxTrackChanges,\n useDocxViewerThumbnails,\n type DocxDocumentTheme,\n type DocxEditorController,\n type DocxPageThumbnailItem,\n} from "@extend-ai/react-docx"\nimport { useVirtualizer } from "@tanstack/react-virtual"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\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 { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/extend/document-viewer-sidebar"\nimport {\n createDocxCommentCardRenderer,\n createDocxTrackedChangeCardRenderer,\n} from "@/components/extend/docx-annotation-card"\nimport { FileThumbnail } from "@/components/extend/file-thumbnail"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_THUMBNAIL_LIST_PADDING = 16\nconst DOCX_THUMBNAIL_ROW_ESTIMATE = 172\nconst DEFAULT_ZOOM = 50\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"\nconst DOCX_THUMBNAIL_FOCUS_RING_CLASS =\n "group-focus-visible/docx-thumbnail-sidebar:ring-2 group-focus-visible/docx-thumbnail-sidebar:ring-ring group-focus-visible/docx-thumbnail-sidebar:ring-offset-1 group-focus-visible/docx-thumbnail-sidebar:ring-offset-background"\nconst DOCX_THUMBNAIL_PREFETCH_ROWS = 4\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n sourceUrl: string | undefined\n}\n\ntype DocxActivePageStore = {\n getSnapshot: () => number\n setActivePage: React.Dispatch<React.SetStateAction<number>>\n subscribe: (listener: () => void) => () => void\n}\n\ntype DocxThumbnailRenderWindowState = {\n visiblePageIndexes: number[]\n prefetchPageIndexes: number[]\n}\n\nfunction createDocxActivePageStore(): DocxActivePageStore {\n let activePage = 1\n const listeners = new Set<() => void>()\n\n return {\n getSnapshot: () => activePage,\n setActivePage: (nextPage) => {\n const value =\n typeof nextPage === "function" ? nextPage(activePage) : nextPage\n const normalizedValue = Math.max(1, Math.round(value || 1))\n\n if (normalizedValue === activePage) return\n\n activePage = normalizedValue\n listeners.forEach((listener) => listener())\n },\n subscribe: (listener) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n }\n}\n\nfunction useDocxActivePage(activePageStore: DocxActivePageStore) {\n return React.useSyncExternalStore(\n activePageStore.subscribe,\n activePageStore.getSnapshot,\n activePageStore.getSnapshot\n )\n}\n\nfunction areNumberArraysEqual(left: number[], right: number[]) {\n return (\n left.length === right.length &&\n left.every((value, index) => value === right[index])\n )\n}\n\nasync function loadDocxFile(\n url: string,\n displayFileName: string\n): Promise<File> {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n return new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\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 ensureDocxExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(".docx")\n ? fileName\n : `${fileName}.docx`\n}\n\nfunction downloadBlob(blob: Blob, fileName: string) {\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = fileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nasync function downloadDocxFile({\n file,\n fileName,\n url,\n}: {\n file?: File\n fileName: string\n url?: string\n}) {\n if (file) {\n downloadBlob(file, ensureDocxExtension(fileName))\n return\n }\n\n if (!url) return\n\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to download DOCX (${response.status})`)\n }\n\n downloadBlob(await response.blob(), ensureDocxExtension(fileName))\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 normalizeDocxZoomScale(value: number | undefined): number {\n return typeof value === "number" &&\n ZOOM_OPTIONS.includes(value as (typeof ZOOM_OPTIONS)[number])\n ? value\n : DEFAULT_ZOOM\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) return\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => {\n window.clearTimeout(timeoutId)\n setShowSpinner(false)\n }\n }, [delayMs, isLoading])\n\n return isLoading && showSpinner\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 isInteractiveViewerTarget(target: EventTarget | null) {\n return (\n target instanceof Element &&\n Boolean(\n target.closest(\n \'a[href], button, input, select, textarea, [contenteditable="true"], [role="button"], [role="link"]\'\n )\n )\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 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 DocxFileActionsMenu({\n controlsDisabled,\n downloadDisabled,\n isPreparingDownload,\n isDark,\n onDownload,\n onShowCommentsChange,\n onShowTrackedChangesChange,\n onIsDarkChange,\n onUploadClick,\n showComments,\n showDownloadButton,\n showNightRenderToggle,\n showTrackedChanges,\n showUploadButton,\n}: {\n controlsDisabled: boolean\n downloadDisabled: boolean\n isPreparingDownload: boolean\n isDark: boolean\n onDownload: () => void\n onShowCommentsChange: (checked: boolean) => void\n onShowTrackedChangesChange: (checked: boolean) => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n showComments: boolean\n showDownloadButton: boolean\n showNightRenderToggle: boolean\n showTrackedChanges: boolean\n showUploadButton: boolean\n}) {\n const showFileActions = showDownloadButton || showUploadButton\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open DOCX actions"\n >\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className="size-4"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-52">\n {showNightRenderToggle ? (\n <>\n <DropdownMenuCheckboxItem\n checked={isDark}\n disabled={controlsDisabled}\n variant="switch"\n onCheckedChange={(checked) => onIsDarkChange(checked === true)}\n >\n <span className="flex min-w-0 items-center gap-2">\n <IconPlaceholder\n lucide="Moon"\n tabler="IconMoon"\n hugeicons="Moon02Icon"\n phosphor="MoonIcon"\n remixicon="RiMoonLine"\n className="size-4"\n />\n Dark mode\n </span>\n </DropdownMenuCheckboxItem>\n <DropdownMenuSeparator />\n </>\n ) : null}\n <DropdownMenuCheckboxItem\n checked={showComments}\n disabled={controlsDisabled}\n variant="switch"\n onCheckedChange={(checked) => onShowCommentsChange(checked === true)}\n >\n <span className="flex min-w-0 items-center gap-2">\n <IconPlaceholder\n lucide="MessageSquare"\n tabler="IconMessage"\n hugeicons="Comment01Icon"\n phosphor="ChatIcon"\n remixicon="RiChat1Line"\n className="size-4"\n />\n Comments\n </span>\n </DropdownMenuCheckboxItem>\n <DropdownMenuCheckboxItem\n checked={showTrackedChanges}\n disabled={controlsDisabled}\n variant="switch"\n onCheckedChange={(checked) =>\n onShowTrackedChangesChange(checked === true)\n }\n >\n <span className="flex min-w-0 items-center gap-2">\n <IconPlaceholder\n lucide="FileDiff"\n tabler="IconFileDiff"\n hugeicons="FileDiffIcon"\n phosphor="GitDiffIcon"\n remixicon="RiFileHistoryLine"\n className="size-4"\n />\n Edits\n </span>\n </DropdownMenuCheckboxItem>\n {showFileActions ? <DropdownMenuSeparator /> : null}\n {showDownloadButton ? (\n <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>\n {isPreparingDownload ? (\n <Spinner className="size-4" />\n ) : (\n <IconPlaceholder\n lucide="Download"\n tabler="IconDownload"\n hugeicons="Download01Icon"\n phosphor="DownloadSimpleIcon"\n remixicon="RiDownload2Line"\n className="size-4"\n />\n )}\n Download\n </DropdownMenuItem>\n ) : null}\n {showUploadButton ? (\n <DropdownMenuItem onClick={onUploadClick}>\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction DocxPageNumberControl({\n activePageStore,\n controlsDisabled,\n onPageChange,\n pageCount,\n}: {\n activePageStore: DocxActivePageStore\n controlsDisabled: boolean\n onPageChange: (pageNumber: number) => void\n pageCount: number\n}) {\n const activePage = useDocxActivePage(activePageStore)\n const inputRef = React.useRef<HTMLInputElement>(null)\n const displayPage = pageCount ? activePage : 1\n const [isEditing, setIsEditing] = React.useState(false)\n const [draftPage, setDraftPage] = React.useState(() => String(displayPage))\n\n React.useEffect(() => {\n if (!isEditing) {\n setDraftPage(String(displayPage))\n }\n }, [displayPage, isEditing])\n\n React.useEffect(() => {\n if (!isEditing) return\n\n inputRef.current?.focus()\n inputRef.current?.select()\n }, [isEditing])\n\n const applyPageDraft = React.useCallback(\n (value: string) => {\n const trimmedValue = value.trim()\n\n if (!trimmedValue) return\n\n const parsedPage = Number(trimmedValue)\n\n if (!Number.isInteger(parsedPage)) return\n\n onPageChange(Math.min(Math.max(parsedPage, 1), Math.max(pageCount, 1)))\n },\n [onPageChange, pageCount]\n )\n\n return (\n <div className="flex items-center text-sm whitespace-nowrap text-primary">\n <span>Page</span>\n {isEditing ? (\n <Input\n ref={inputRef}\n aria-label="Page number"\n inputMode="numeric"\n pattern="[0-9]*"\n size="sm"\n value={draftPage}\n className="mx-1 w-14 min-w-14 rounded-md [&_[data-slot=input]]:text-center"\n onBlur={() => setIsEditing(false)}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) => {\n const nextValue = event.target.value\n\n setDraftPage(nextValue)\n applyPageDraft(nextValue)\n }}\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === "Enter" || event.key === "Escape") {\n event.currentTarget.blur()\n }\n }}\n />\n ) : (\n <Button\n type="button"\n variant="ghost"\n size="sm"\n className="font-normal"\n aria-label={`Current page ${displayPage}. Edit page number`}\n disabled={controlsDisabled || !pageCount}\n onClick={() => {\n setDraftPage(String(displayPage))\n setIsEditing(true)\n }}\n >\n {displayPage}\n </Button>\n )}\n <span>of {pageCount || "-"}</span>\n </div>\n )\n}\n\nfunction DocxToolbar({\n activePageStore,\n controlsDisabled,\n isDark,\n isPreparingDownload,\n onDownload,\n onIsDarkChange,\n onPageChange,\n onShowCommentsChange,\n onShowTrackedChangesChange,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showComments,\n showDownloadButton = true,\n showNightRenderToggle,\n showTrackedChanges,\n showUploadButton = true,\n toolbarActions,\n zoomScale,\n}: {\n activePageStore: DocxActivePageStore\n controlsDisabled: boolean\n isDark: boolean\n isPreparingDownload: boolean\n onDownload: () => void\n onIsDarkChange: (checked: boolean) => void\n onPageChange: (pageNumber: number) => void\n onShowCommentsChange: (checked: boolean) => void\n onShowTrackedChangesChange: (checked: boolean) => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showComments: boolean\n showDownloadButton?: boolean\n showNightRenderToggle: boolean\n showTrackedChanges: boolean\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\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 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2">\n <TooltipProvider>\n <div className="flex min-w-0 flex-wrap 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 <IconPlaceholder\n lucide="PanelLeft"\n tabler="IconLayoutSidebar"\n hugeicons="SidebarLeftIcon"\n phosphor="SidebarIcon"\n remixicon="RiLayoutLeftLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <DocxPageNumberControl\n activePageStore={activePageStore}\n controlsDisabled={controlsDisabled}\n onPageChange={onPageChange}\n pageCount={pageCount}\n />\n </div>\n <div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n 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 <IconPlaceholder\n lucide="CircleMinus"\n tabler="IconCircleMinus"\n hugeicons="MinusSignCircleIcon"\n phosphor="MinusCircleIcon"\n remixicon="RiIndeterminateCircleLine"\n className="size-4"\n />\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 <IconPlaceholder\n lucide="CirclePlusIcon"\n tabler="IconCirclePlusFilled"\n hugeicons="PlusSignCircleIcon"\n phosphor="PlusCircleIcon"\n remixicon="RiAddCircleFill"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <DocxFileActionsMenu\n controlsDisabled={controlsDisabled}\n downloadDisabled={controlsDisabled || isPreparingDownload}\n isPreparingDownload={isPreparingDownload}\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onShowCommentsChange={onShowCommentsChange}\n onShowTrackedChangesChange={onShowTrackedChangesChange}\n onUploadClick={onUploadClick}\n showComments={showComments}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showTrackedChanges={showTrackedChanges}\n showUploadButton={showUploadButton}\n />\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="rounded-md 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 isLoading={isLoading}\n hasError={hasError}\n className={cn(\n "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",\n isActive && "shadow-sm"\n )}\n />\n )\n}\n\nfunction DocxThumbnailSidebarList({\n activePage,\n displayFileName,\n isLoadingDocument,\n onSelectPage,\n onThumbnailRenderWindowChange,\n pageCount,\n sidebarOpen,\n thumbnails,\n}: {\n activePage: number\n displayFileName: string\n isLoadingDocument: boolean\n onSelectPage: (pageNumber: number) => void\n onThumbnailRenderWindowChange: (\n renderWindow: DocxThumbnailRenderWindowState\n ) => void\n pageCount: number\n sidebarOpen: boolean\n thumbnails: DocxPageThumbnailItem[]\n}) {\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const thumbnailListboxId = React.useId()\n const visibleThumbnails = React.useMemo(\n () => thumbnails.slice(0, pageCount || 0),\n [pageCount, thumbnails]\n )\n const activeDescendantId =\n activePage > 0 && visibleThumbnails.length\n ? `${thumbnailListboxId}-page-${activePage}`\n : undefined\n const virtualizer = useVirtualizer({\n count: visibleThumbnails.length,\n estimateSize: () => DOCX_THUMBNAIL_ROW_ESTIMATE,\n getItemKey: (index) => visibleThumbnails[index]?.pageIndex ?? index,\n getScrollElement: () => viewportRef.current,\n overscan: 3,\n })\n const virtualItems = virtualizer.getVirtualItems()\n const renderWindowSignature = virtualItems\n .map((virtualRow) => virtualRow.index)\n .join(",")\n\n React.useEffect(() => {\n if (!sidebarOpen || isLoadingDocument || !visibleThumbnails.length) {\n onThumbnailRenderWindowChange({\n prefetchPageIndexes: [],\n visiblePageIndexes: [],\n })\n return\n }\n\n const visiblePageIndexes = virtualItems\n .map((virtualRow) => visibleThumbnails[virtualRow.index]?.pageIndex)\n .filter((pageIndex): pageIndex is number => pageIndex !== undefined)\n\n const firstVirtualIndex = virtualItems[0]?.index ?? 0\n const lastVirtualIndex =\n virtualItems[virtualItems.length - 1]?.index ?? firstVirtualIndex\n const firstPrefetchIndex = Math.max(\n 0,\n firstVirtualIndex - DOCX_THUMBNAIL_PREFETCH_ROWS\n )\n const lastPrefetchIndex = Math.min(\n visibleThumbnails.length - 1,\n lastVirtualIndex + DOCX_THUMBNAIL_PREFETCH_ROWS\n )\n const visiblePageIndexSet = new Set(visiblePageIndexes)\n const prefetchPageIndexes: number[] = []\n\n for (\n let index = firstPrefetchIndex;\n index <= lastPrefetchIndex;\n index += 1\n ) {\n const pageIndex = visibleThumbnails[index]?.pageIndex\n\n if (pageIndex !== undefined && !visiblePageIndexSet.has(pageIndex)) {\n prefetchPageIndexes.push(pageIndex)\n }\n }\n\n onThumbnailRenderWindowChange({\n prefetchPageIndexes,\n visiblePageIndexes,\n })\n }, [\n isLoadingDocument,\n onThumbnailRenderWindowChange,\n renderWindowSignature,\n sidebarOpen,\n visibleThumbnails,\n virtualItems,\n ])\n\n React.useEffect(() => {\n if (!sidebarOpen || activePage < 1 || !visibleThumbnails.length) return\n\n virtualizer.scrollToIndex(\n Math.min(activePage - 1, visibleThumbnails.length - 1),\n { align: "auto" }\n )\n }, [activePage, sidebarOpen, virtualizer, visibleThumbnails.length])\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (pageCount < 1) return\n\n const currentPage = activePage > 0 ? activePage : 1\n let nextPage: number | null = null\n\n if (event.key === "ArrowDown") {\n nextPage = Math.min(pageCount, currentPage + 1)\n } else if (event.key === "ArrowUp") {\n nextPage = Math.max(1, currentPage - 1)\n } else if (event.key === "Home") {\n nextPage = 1\n } else if (event.key === "End") {\n nextPage = pageCount\n }\n\n if (nextPage === null) return\n\n event.preventDefault()\n onSelectPage(nextPage)\n },\n [activePage, onSelectPage, pageCount]\n )\n\n return (\n <ScrollArea\n className="h-full"\n scrollFade\n viewportClassName="group/docx-thumbnail-sidebar focus-visible:ring-0 focus-visible:ring-offset-0"\n viewportProps={{\n "aria-activedescendant": activeDescendantId,\n "aria-busy": isLoadingDocument || undefined,\n "aria-label": "DOCX pages",\n onKeyDown: handleKeyDown,\n onMouseDown: (event) => {\n event.currentTarget.focus({ preventScroll: true })\n },\n role: "listbox",\n tabIndex: 0,\n }}\n viewportRef={viewportRef}\n >\n {isLoadingDocument ? (\n <div className="p-4">\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </div>\n ) : visibleThumbnails.length ? (\n <div\n className="relative"\n style={{\n height:\n virtualizer.getTotalSize() + DOCX_THUMBNAIL_LIST_PADDING * 2,\n }}\n >\n {virtualItems.map((virtualRow) => {\n const thumbnail = visibleThumbnails[virtualRow.index]\n if (!thumbnail) return null\n\n return (\n <div\n key={virtualRow.key}\n ref={virtualizer.measureElement}\n data-index={virtualRow.index}\n className={cn(\n "absolute top-0 right-3 left-3 pb-3 [contain:layout]",\n thumbnail.pageNumber === activePage && "z-10"\n )}\n style={{\n transform: `translateY(${\n virtualRow.start + DOCX_THUMBNAIL_LIST_PADDING\n }px)`,\n }}\n >\n <div\n id={`${thumbnailListboxId}-page-${thumbnail.pageNumber}`}\n role="option"\n aria-current={\n thumbnail.pageNumber === activePage ? "page" : undefined\n }\n aria-label={`Page ${thumbnail.pageNumber}`}\n aria-posinset={thumbnail.pageNumber}\n aria-selected={thumbnail.pageNumber === activePage}\n aria-setsize={pageCount}\n data-docx-viewer-thumbnail-option={thumbnail.pageNumber}\n className={cn(\n "flex h-auto w-full cursor-default flex-col items-center gap-2 rounded-md p-2 text-xs transition-shadow outline-none select-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground",\n thumbnail.pageNumber === activePage &&\n DOCX_THUMBNAIL_FOCUS_RING_CLASS\n )}\n onClick={() => onSelectPage(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.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 </div>\n </div>\n )\n })}\n </div>\n ) : null}\n </ScrollArea>\n )\n}\n\nfunction DocxThumbnailSidebarContent({\n activePageStore,\n displayFileName,\n editor,\n isLoadingDocument,\n onSelectPage,\n pageCount,\n reportedPageCount,\n sidebarOpen,\n}: {\n activePageStore: DocxActivePageStore\n displayFileName: string\n editor: DocxEditorController\n isLoadingDocument: boolean\n onSelectPage: (pageNumber: number) => void\n pageCount: number\n reportedPageCount: number\n sidebarOpen: boolean\n}) {\n const [thumbnailRenderWindow, setThumbnailRenderWindow] =\n React.useState<DocxThumbnailRenderWindowState>({\n prefetchPageIndexes: [],\n visiblePageIndexes: [],\n })\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n // Detached thumbnail rendering handles offscreen pages; keep the raster\n // queue dormant while the sidebar is closed.\n disabled: !sidebarOpen,\n pixelRatio: 2,\n renderWindow: thumbnailRenderWindow,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n [sidebarOpen, thumbnailRenderWindow]\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const activePage = useDocxActivePage(activePageStore)\n const handleThumbnailRenderWindowChange = React.useCallback(\n (nextRenderWindow: DocxThumbnailRenderWindowState) => {\n setThumbnailRenderWindow((currentRenderWindow) => {\n if (\n areNumberArraysEqual(\n currentRenderWindow.visiblePageIndexes,\n nextRenderWindow.visiblePageIndexes\n ) &&\n areNumberArraysEqual(\n currentRenderWindow.prefetchPageIndexes,\n nextRenderWindow.prefetchPageIndexes\n )\n ) {\n return currentRenderWindow\n }\n\n return nextRenderWindow\n })\n },\n []\n )\n\n if (!sidebarOpen) return null\n\n return (\n <DocxThumbnailSidebarList\n activePage={activePage}\n displayFileName={displayFileName}\n isLoadingDocument={isLoadingDocument}\n onSelectPage={onSelectPage}\n onThumbnailRenderWindowChange={handleThumbnailRenderWindowChange}\n pageCount={pageCount}\n sidebarOpen={sidebarOpen}\n thumbnails={thumbnails}\n />\n )\n}\n\nexport function DocxViewerPreview({\n className,\n defaultZoom = DEFAULT_ZOOM,\n fileName,\n isDark,\n onIsDarkChange,\n showDownload = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n}: {\n className?: string\n defaultZoom?: number\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n showDownload?: boolean\n showToolbar?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n}) {\n return (\n <DocxViewerContent\n className={className}\n defaultZoom={defaultZoom}\n effectiveIsDark={isDark}\n fileName={fileName}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n showDownload={showDownload}\n showToolbar={showToolbar}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n url={src}\n />\n )\n}\n\nfunction DocxViewerContent({\n className,\n defaultZoom,\n effectiveIsDark,\n fileName,\n setNightRenderEnabled,\n shouldRenderNightMode,\n showDownload,\n showToolbar = true,\n showUpload,\n toolbarActions,\n url,\n}: {\n className?: string\n defaultZoom?: number\n effectiveIsDark: boolean\n fileName?: string\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n showDownload: boolean\n showToolbar?: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewportElement, setViewportElement] =\n React.useState<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const activePageStore = React.useMemo(createDocxActivePageStore, [])\n const resolvedDefaultZoomScale = normalizeDocxZoomScale(defaultZoom)\n const activeUploadedDocxFile =\n uploadedDocxFile?.sourceUrl === url ? uploadedDocxFile : null\n const documentKey = activeUploadedDocxFile?.identity ?? url ?? ""\n const setActivePage = activePageStore.setActivePage\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n activeUploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [activeUploadedDocxFile?.file.name, fileName, 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 { layout: pageLayout } = useDocxPageLayout(editor)\n const { importDocxFile, setDocumentTheme, status } = editor\n const { showComments, setShowComments } = useDocxComments(editor)\n const { showTrackedChanges, setShowTrackedChanges } =\n useDocxTrackChanges(editor)\n const [reportedPageCount, setReportedPageCount] = React.useState(0)\n const [zoomScaleState, setZoomScaleState] = React.useState({\n documentKey: "",\n value: resolvedDefaultZoomScale,\n })\n const zoomScale =\n zoomScaleState.documentKey === documentKey\n ? zoomScaleState.value\n : resolvedDefaultZoomScale\n const setZoomScale = React.useCallback<\n React.Dispatch<React.SetStateAction<number>>\n >(\n (nextZoomScale) => {\n setZoomScaleState((currentState) => {\n const currentZoomScale =\n currentState.documentKey === documentKey\n ? currentState.value\n : resolvedDefaultZoomScale\n const value =\n typeof nextZoomScale === "function"\n ? nextZoomScale(currentZoomScale)\n : nextZoomScale\n\n return { documentKey, value }\n })\n },\n [documentKey, resolvedDefaultZoomScale]\n )\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <ViewerLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const documentTheme = effectiveIsDark ? "dark" : "light"\n const renderTrackedChangeCard = React.useMemo(\n () => createDocxTrackedChangeCardRenderer(documentTheme),\n [documentTheme]\n )\n const renderCommentCard = React.useMemo(\n () => createDocxCommentCardRenderer(documentTheme),\n [documentTheme]\n )\n const hasDocument = Boolean(url || activeUploadedDocxFile)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const thumbnailSidebarVisible = Boolean(\n sidebarOpen && (pageCount || isLoadingDocument)\n )\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n const setViewportRef = React.useCallback((element: HTMLDivElement | null) => {\n viewportRef.current = element\n setViewportElement(element)\n }, [])\n const pageVirtualization = React.useMemo(\n () => ({\n enabled: true,\n overscan: 1,\n scrollElement: viewportElement,\n zoomScale: zoomScale / 100,\n }),\n [viewportElement, zoomScale]\n )\n const handleDownload = React.useCallback(async () => {\n if (isPreparingDownload) return\n if (!activeUploadedDocxFile && !url) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadDocxFile({\n file: activeUploadedDocxFile?.file,\n fileName: displayFileName,\n url,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [activeUploadedDocxFile, displayFileName, isPreparingDownload, url])\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [documentKey, setActivePage])\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 const frame = window.requestAnimationFrame(() => {\n setLoadError(status)\n setIsLoadingDocument(false)\n })\n\n return () => window.cancelAnimationFrame(frame)\n }\n }, [status])\n\n // Imports mutate the shared editor instance; concurrent calls (effect\n // re-runs, StrictMode double-invoke) race inside the parser and surface as\n // bogus "Invalid DOCX ZIP" errors, so every import is chained through here.\n const importQueueRef = React.useRef<Promise<void>>(Promise.resolve())\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n // Superseded while queued \u2014 let the newest import run instead.\n if (!isCurrent) return\n if (!activeUploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n activeUploadedDocxFile?.file ??\n (url ? await loadDocxFile(url, displayFileName) : 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 importQueueRef.current = importQueueRef.current.then(load)\n\n return () => {\n isCurrent = false\n }\n }, [\n activeUploadedDocxFile,\n displayFileName,\n importDocxFile,\n setActivePage,\n url,\n ])\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 activePageStore.setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [activePageStore, 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(\n (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) return\n\n if (!page) {\n const pageStridePx =\n (pageLayout.pageHeightPx + pageLayout.viewportDefaults.pageGapPx) *\n (zoomScale / 100)\n\n viewport.scrollTo({\n top: Math.max(0, targetPageIndex * pageStridePx - 24),\n behavior: "auto",\n })\n return\n }\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 pageLayout.pageHeightPx,\n pageLayout.viewportDefaults.pageGapPx,\n setActivePage,\n zoomScale,\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(resolvedDefaultZoomScale)\n setActivePage(1)\n setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n sourceUrl: url,\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=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n {showToolbar ? (\n <DocxToolbar\n activePageStore={activePageStore}\n controlsDisabled={controlsDisabled}\n isDark={effectiveIsDark}\n isPreparingDownload={isPreparingDownload}\n onDownload={handleDownload}\n onIsDarkChange={setNightRenderEnabled}\n onPageChange={scrollToPage}\n onShowCommentsChange={setShowComments}\n onShowTrackedChangesChange={setShowTrackedChanges}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showComments={showComments}\n showDownloadButton={showDownload}\n showNightRenderToggle={shouldRenderNightMode}\n showTrackedChanges={showTrackedChanges}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n zoomScale={zoomScale}\n />\n ) : null}\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={thumbnailSidebarVisible}\n >\n <DocxThumbnailSidebarContent\n activePageStore={activePageStore}\n displayFileName={displayFileName}\n editor={editor}\n isLoadingDocument={isLoadingDocument}\n onSelectPage={scrollToPage}\n pageCount={pageCount}\n reportedPageCount={reportedPageCount}\n sidebarOpen={thumbnailSidebarVisible}\n />\n </DocumentViewerThumbnailSidebar>\n <ScrollArea\n className="min-h-0 flex-1"\n style={{ backgroundColor: viewerBackgroundColor }}\n viewportClassName="px-4 py-6"\n viewportProps={{\n "aria-label": "DOCX document",\n onMouseDown: (event) => {\n if (isInteractiveViewerTarget(event.target)) return\n event.currentTarget.focus({ preventScroll: true })\n },\n tabIndex: 0,\n }}\n viewportRef={setViewportRef}\n >\n {!url && !activeUploadedDocxFile ? (\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">\n Upload a Word document to preview\n </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 <div className="mt-1 text-muted-foreground">\n Legacy <code>.doc</code> support is limited and experimental;\n convert to DOCX for best fidelity.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload Word document\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="flex min-h-full w-max min-w-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 showTrackedChanges={showTrackedChanges}\n renderTrackedChangeCard={renderTrackedChangeCard}\n showComments={showComments}\n renderCommentCard={renderCommentCard}\n loadingState={loadingState}\n pageBackgroundColor={effectiveIsDark ? "#0a0a0a" : undefined}\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={pageVirtualization}\n deferInitialPaginationPaint={false}\n onPageCountChange={handlePageCountChange}\n />\n </div>\n </div>\n )}\n </ScrollArea>\n </div>\n </div>\n )\n}\n'export function DocxViewerSource() {return (diff --git a/apps/v4/components/e-signature-docs.tsx b/apps/v4/components/e-signature-docs.tsxindex 24a382d..12fa1d6 100644--- a/apps/v4/components/e-signature-docs.tsx+++ b/apps/v4/components/e-signature-docs.tsx@@ -907,7 +907,7 @@ export function ESignatureExample() {}`const eSignatureSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n Download01Icon,\n FilePenIcon,\n Pen01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport type SignaturePad from "signature_pad"\n\nimport { cn } from "@/lib/utils"\nimport { PDFViewer } from "@/components/extend/pdf-viewer"\nimport { PdfBlockResizableShell } from "@/components/extend/pdf-block-resizable-shell"\nimport { Button } from "@/components/ui/button"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogPanel,\n DialogTitle,\n} from "@/components/ui/dialog"\nimport { ScrollArea } from "@/components/ui/scroll-area"\n\ntype BoundingBox = {\n x: number\n y: number\n width: number\n height: number\n}\n\ntype SignatureField = {\n id: string\n label: string\n page: number\n bbox: BoundingBox\n imageDataUrl?: string\n}\n\nconst PAGE_WIDTH = 612\nconst PAGE_HEIGHT = 792\nconst DEFAULT_ZOOM = 1\nconst SIGNATURE_PAD_PADDING = 8\nconst SIGNATURE_PAD_BACKGROUND_COLOR = "#ffffff"\nconst SIGNATURE_PAD_PEN_COLOR = "#000000"\nconst DEFAULT_SIGNATURE_ASPECT_RATIO = 3\n\nconst INITIAL_FIELD: SignatureField = {\n id: "signature-1",\n label: "Signature",\n page: 1,\n bbox: { x: 300, y: 504, width: 250, height: 58 },\n}\n\nfunction bboxToStyle(bbox: BoundingBox): React.CSSProperties {\n return {\n left: `${(bbox.x / PAGE_WIDTH) * 100}%`,\n top: `${(bbox.y / PAGE_HEIGHT) * 100}%`,\n width: `${(bbox.width / PAGE_WIDTH) * 100}%`,\n height: `${(bbox.height / PAGE_HEIGHT) * 100}%`,\n }\n}\n\nfunction getSignatureAspectRatio(bbox?: BoundingBox): number {\n if (!bbox || bbox.width <= 0 || bbox.height <= 0) {\n return DEFAULT_SIGNATURE_ASPECT_RATIO\n }\n\n return bbox.width / bbox.height\n}\n\nfunction getSignatureGuideSize({\n containerWidth,\n containerHeight,\n aspectRatio,\n}: {\n containerWidth: number\n containerHeight: number\n aspectRatio: number\n}): { width: number; height: number } {\n const maxWidth = Math.max(containerWidth - SIGNATURE_PAD_PADDING * 2, 1)\n const maxHeight = Math.max(containerHeight - SIGNATURE_PAD_PADDING * 2, 1)\n\n if (maxWidth / maxHeight > aspectRatio) {\n const height = maxHeight\n return {\n width: height * aspectRatio,\n height,\n }\n }\n\n const width = maxWidth\n return {\n width,\n height: width / aspectRatio,\n }\n}\n\nfunction getSignatureDataUrl(canvas: HTMLCanvasElement): string {\n return canvas.toDataURL("image/png")\n}\n\nfunction SignatureDialog({\n open,\n fieldBbox,\n initialValue,\n onOpenChange,\n onConfirm,\n}: {\n open: boolean\n fieldBbox: BoundingBox\n initialValue?: string\n onOpenChange: (open: boolean) => void\n onConfirm: (value: string) => void\n}) {\n const canvasContainerRef = React.useRef<HTMLDivElement>(null)\n const canvasRef = React.useRef<HTMLCanvasElement>(null)\n const signaturePadRef = React.useRef<SignaturePad | null>(null)\n const [isReady, setIsReady] = React.useState(false)\n const [hasSignature, setHasSignature] = React.useState(false)\n const [guideSize, setGuideSize] = React.useState<{\n width: number\n height: number\n } | null>(null)\n const signatureAspectRatio = React.useMemo(\n () => getSignatureAspectRatio(fieldBbox),\n [fieldBbox]\n )\n\n React.useEffect(() => {\n if (!open) {\n setGuideSize(null)\n return\n }\n\n let frameId = 0\n let resizeObserver: ResizeObserver | null = null\n\n const updateGuideSize = (container?: HTMLDivElement | null) => {\n const currentContainer = container ?? canvasContainerRef.current\n if (\n !currentContainer ||\n currentContainer.clientWidth <= 0 ||\n currentContainer.clientHeight <= 0\n ) {\n return false\n }\n\n const nextSize = getSignatureGuideSize({\n containerWidth: currentContainer.clientWidth,\n containerHeight: currentContainer.clientHeight,\n aspectRatio: signatureAspectRatio,\n })\n\n setGuideSize((previousSize) => {\n if (\n previousSize &&\n Math.abs(previousSize.width - nextSize.width) < 0.5 &&\n Math.abs(previousSize.height - nextSize.height) < 0.5\n ) {\n return previousSize\n }\n\n return nextSize\n })\n\n return true\n }\n\n const connect = () => {\n const container = canvasContainerRef.current\n if (!updateGuideSize(container)) {\n frameId = window.requestAnimationFrame(connect)\n return\n }\n\n if (container) {\n resizeObserver = new ResizeObserver(() => {\n updateGuideSize(container)\n })\n resizeObserver.observe(container)\n }\n }\n\n connect()\n\n return () => {\n window.cancelAnimationFrame(frameId)\n resizeObserver?.disconnect()\n }\n }, [open, signatureAspectRatio])\n\n React.useEffect(() => {\n if (!open || !guideSize || guideSize.width <= 1 || guideSize.height <= 1) {\n signaturePadRef.current?.off()\n signaturePadRef.current = null\n setIsReady(false)\n if (!open) {\n setHasSignature(false)\n }\n return\n }\n\n let cancelled = false\n let resizeObserver: ResizeObserver | null = null\n\n const syncCanvasSize = (canvas: HTMLCanvasElement) => {\n const width = Math.max(canvas.offsetWidth, 1)\n const height = Math.max(canvas.offsetHeight, 1)\n const ratio = Math.max(window.devicePixelRatio || 1, 1)\n\n canvas.style.width = `${width}px`\n canvas.style.height = `${height}px`\n canvas.width = Math.floor(width * ratio)\n canvas.height = Math.floor(height * ratio)\n const context = canvas.getContext("2d")\n context?.setTransform(1, 0, 0, 1, 0, 0)\n context?.scale(ratio, ratio)\n\n return { width, height, ratio }\n }\n\n const initialize = async () => {\n const canvas = canvasRef.current\n if (!canvas) return\n\n const { default: SignaturePadConstructor } = await import("signature_pad")\n if (cancelled) return\n\n const signaturePad = new SignaturePadConstructor(canvas, {\n minWidth: 1,\n maxWidth: 2,\n penColor: SIGNATURE_PAD_PEN_COLOR,\n })\n\n signaturePadRef.current = signaturePad\n\n const loadSignature = async (dataUrl?: string) => {\n const size = syncCanvasSize(canvas)\n\n if (dataUrl) {\n await signaturePad.fromDataURL(dataUrl, size)\n setHasSignature(true)\n return\n }\n\n signaturePad.clear()\n setHasSignature(false)\n }\n\n await loadSignature(initialValue)\n if (cancelled) return\n\n signaturePad.addEventListener("endStroke", () => {\n setHasSignature(true)\n })\n\n resizeObserver = new ResizeObserver(() => {\n const currentCanvas = canvasRef.current\n const currentSignaturePad = signaturePadRef.current\n if (!currentCanvas || !currentSignaturePad) return\n\n const previousSignature = currentSignaturePad.isEmpty()\n ? undefined\n : currentSignaturePad.toDataURL("image/png")\n void loadSignature(previousSignature)\n })\n resizeObserver.observe(canvas)\n setIsReady(true)\n }\n\n const animationFrame = window.requestAnimationFrame(() => {\n void initialize()\n })\n\n return () => {\n cancelled = true\n window.cancelAnimationFrame(animationFrame)\n resizeObserver?.disconnect()\n signaturePadRef.current?.off()\n signaturePadRef.current = null\n setIsReady(false)\n }\n }, [open, guideSize, initialValue])\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className="max-w-xl">\n <DialogHeader>\n <DialogTitle>Add signature</DialogTitle>\n <DialogDescription>\n Draw a signature to place it into the selected PDF field.\n </DialogDescription>\n </DialogHeader>\n <DialogPanel>\n <div className="rounded-xl border bg-white p-3 text-slate-950 shadow-xs dark:bg-white dark:text-slate-950">\n <div\n ref={canvasContainerRef}\n className="flex h-56 w-full items-center justify-center overflow-hidden rounded-lg bg-white p-2 dark:bg-white"\n >\n <div\n className={cn(\n "relative overflow-hidden rounded-[3px] border border-dashed border-blue-500/70 bg-white",\n isReady ? "cursor-crosshair" : "cursor-wait"\n )}\n style={{\n width: guideSize ? `${guideSize.width}px` : undefined,\n height: guideSize ? `${guideSize.height}px` : undefined,\n opacity: guideSize ? 1 : 0,\n backgroundColor: SIGNATURE_PAD_BACKGROUND_COLOR,\n }}\n >\n <canvas\n ref={canvasRef}\n className={cn(\n "absolute inset-0 size-full touch-none",\n !isReady && "pointer-events-none"\n )}\n style={{\n backgroundColor: SIGNATURE_PAD_BACKGROUND_COLOR,\n touchAction: "none",\n }}\n />\n </div>\n </div>\n </div>\n </DialogPanel>\n <DialogFooter className="sm:justify-between">\n <Button\n type="button"\n variant="outline"\n disabled={!isReady}\n onClick={() => {\n signaturePadRef.current?.clear()\n setHasSignature(false)\n }}\n >\n Clear\n </Button>\n <div className="flex flex-col-reverse gap-2 sm:flex-row">\n <Button\n type="button"\n variant="outline"\n onClick={() => onOpenChange(false)}\n >\n Cancel\n </Button>\n <Button\n type="button"\n disabled={!isReady || !hasSignature}\n onClick={() => {\n const canvas = canvasRef.current\n if (!canvas) return\n\n onConfirm(getSignatureDataUrl(canvas))\n onOpenChange(false)\n }}\n >\n Confirm\n </Button>\n </div>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\nfunction SignatureFieldOverlay({\n field,\n onOpen,\n}: {\n field: SignatureField\n onOpen: () => void\n}) {\n return (\n <button\n type="button"\n className={cn(\n "absolute z-20 overflow-hidden rounded-[3px] border border-blue-500/70 transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",\n field.imageDataUrl\n ? "bg-transparent shadow-none hover:bg-blue-500/5"\n : "bg-blue-500/10 hover:bg-blue-500/15"\n )}\n style={bboxToStyle(field.bbox)}\n onClick={onOpen}\n >\n {field.imageDataUrl ? (\n <img\n src={field.imageDataUrl}\n alt=""\n className="size-full object-fill"\n draggable={false}\n />\n ) : (\n <span className="flex size-full items-center justify-center gap-1.5 px-2 text-[11px] font-medium text-blue-700 dark:text-blue-300">\n <HugeiconsIcon icon={Pen01Icon} className="size-3.5" />\n Signature\n </span>\n )}\n </button>\n )\n}\n\nasync function downloadSignedPdf({\n file,\n field,\n}: {\n file: string\n field: SignatureField\n}) {\n const { PDFDocument } = await import("pdf-lib")\n const existingPdfBytes = await fetch(file).then((response) =>\n response.arrayBuffer()\n )\n const pdfDocument = await PDFDocument.load(existingPdfBytes)\n const page = pdfDocument.getPage(field.page - 1)\n\n if (field.imageDataUrl) {\n const signatureImage = await pdfDocument.embedPng(field.imageDataUrl)\n const { width: pageWidth, height: pageHeight } = page.getSize()\n const scaleX = pageWidth / PAGE_WIDTH\n const scaleY = pageHeight / PAGE_HEIGHT\n const fieldWidth = field.bbox.width * scaleX\n const fieldHeight = field.bbox.height * scaleY\n const fieldX = field.bbox.x * scaleX\n const fieldY = pageHeight - (field.bbox.y + field.bbox.height) * scaleY\n\n page.drawImage(signatureImage, {\n x: fieldX,\n y: fieldY,\n width: fieldWidth,\n height: fieldHeight,\n })\n }\n\n const bytes = await pdfDocument.save()\n const blob = new Blob([new Uint8Array(bytes)], { type: "application/pdf" })\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n anchor.href = url\n anchor.download = "signed-document.pdf"\n anchor.click()\n URL.revokeObjectURL(url)\n}\n\nfunction SignatureFieldsPanel({\n field,\n className,\n canExport,\n isDownloading,\n onSign,\n onClear,\n onDownload,\n}: {\n field: SignatureField\n className?: string\n canExport: boolean\n isDownloading: boolean\n onSign: () => void\n onClear: () => void\n onDownload: () => void\n}) {\n return (\n <aside className={cn("flex min-h-0 flex-col bg-background", className)}>\n <ScrollArea className="min-h-0 flex-1" scrollFade>\n <div className="space-y-4 p-4">\n <div className="space-y-1">\n <h3 className="text-sm font-medium">Signature fields</h3>\n <p className="text-xs text-muted-foreground">\n Review fields, collect signatures, and export a signed PDF.\n </p>\n </div>\n <div className="rounded-lg border bg-background p-3">\n <div className="flex items-start gap-3">\n <div className="grid size-9 shrink-0 place-items-center rounded-md bg-blue-500/10 text-blue-600 dark:text-blue-300">\n <HugeiconsIcon icon={FilePenIcon} className="size-4" />\n </div>\n <div className="min-w-0 flex-1">\n <div className="flex items-center justify-between gap-2">\n <div className="text-sm font-medium">{field.label}</div>\n <div\n className={cn(\n "rounded-full px-2 py-0.5 text-xs",\n field.imageDataUrl\n ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-300"\n : "bg-muted text-muted-foreground"\n )}\n >\n {field.imageDataUrl ? "Signed" : "Unsigned"}\n </div>\n </div>\n <div className="mt-2 text-xs text-muted-foreground">\n {Math.round(field.bbox.width)} x{" "}\n {Math.round(field.bbox.height)} on page {field.page}\n </div>\n <div className="mt-3 flex gap-2">\n <Button\n type="button"\n size="sm"\n variant={field.imageDataUrl ? "outline" : "default"}\n className="flex-1"\n onClick={onSign}\n >\n <HugeiconsIcon icon={Pen01Icon} className="size-4" />\n {field.imageDataUrl ? "Edit" : "Sign"}\n </Button>\n {field.imageDataUrl ? (\n <Button\n type="button"\n size="sm"\n variant="outline"\n onClick={onClear}\n >\n Clear\n </Button>\n ) : null}\n </div>\n </div>\n </div>\n </div>\n <Button\n type="button"\n className="w-full"\n disabled={!canExport || isDownloading}\n onClick={onDownload}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n {isDownloading ? "Exporting..." : "Export signed PDF"}\n </Button>\n </div>\n </ScrollArea>\n </aside>\n )\n}\n\nexport function ESignatureBlock({ file }: { file?: string }) {\n const [field, setField] = React.useState<SignatureField>(INITIAL_FIELD)\n const [dialogOpen, setDialogOpen] = React.useState(false)\n const [isDownloading, setIsDownloading] = React.useState(false)\n\n const handleDownload = React.useCallback(async () => {\n if (!file || !field.imageDataUrl) return\n\n setIsDownloading(true)\n try {\n await downloadSignedPdf({ file, field })\n } finally {\n setIsDownloading(false)\n }\n }, [field, file])\n\n return (\n <>\n <PdfBlockResizableShell\n autoSaveId="pdf-block-e-signature"\n left={\n <PDFViewer\n src={file}\n defaultZoom={DEFAULT_ZOOM}\n toolbarActions={\n <Button\n type="button"\n size="sm"\n variant="outline"\n disabled={!file || !field.imageDataUrl || isDownloading}\n onClick={handleDownload}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n Download\n </Button>\n }\n renderPageOverlay={({ pageNumber }) =>\n pageNumber === field.page ? (\n <SignatureFieldOverlay\n field={field}\n onOpen={() => setDialogOpen(true)}\n />\n ) : null\n }\n />\n }\n right={\n <SignatureFieldsPanel\n field={field}\n canExport={Boolean(file && field.imageDataUrl)}\n isDownloading={isDownloading}\n onSign={() => setDialogOpen(true)}\n onClear={() =>\n setField((previousField) => ({\n ...previousField,\n imageDataUrl: undefined,\n }))\n }\n onDownload={handleDownload}\n />\n }\n />\n <SignatureDialog\n open={dialogOpen}\n fieldBbox={field.bbox}\n initialValue={field.imageDataUrl}\n onOpenChange={setDialogOpen}\n onConfirm={(imageDataUrl) => {\n setField((previousField) => ({ ...previousField, imageDataUrl }))\n }}\n />\n </>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport type SignaturePad from "signature_pad"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogPanel,\n DialogTitle,\n} from "@/components/ui/dialog"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport { PdfBlockResizableShell } from "@/components/extend/pdf-block-resizable-shell"\nimport { PDFViewer } from "@/components/extend/pdf-viewer"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\ntype BoundingBox = {\n x: number\n y: number\n width: number\n height: number\n}\n\ntype SignatureField = {\n id: string\n label: string\n page: number\n bbox: BoundingBox\n imageDataUrl?: string\n}\n\nconst PAGE_WIDTH = 612\nconst PAGE_HEIGHT = 792\nconst DEFAULT_ZOOM = 1\nconst SIGNATURE_PAD_PADDING = 8\nconst SIGNATURE_PAD_BACKGROUND_COLOR = "#ffffff"\nconst SIGNATURE_PAD_PEN_COLOR = "#000000"\nconst DEFAULT_SIGNATURE_ASPECT_RATIO = 3\n\nconst INITIAL_FIELD: SignatureField = {\n id: "signature-1",\n label: "Signature",\n page: 1,\n bbox: { x: 300, y: 504, width: 250, height: 58 },\n}\n\nfunction bboxToStyle(bbox: BoundingBox): React.CSSProperties {\n return {\n left: `${(bbox.x / PAGE_WIDTH) * 100}%`,\n top: `${(bbox.y / PAGE_HEIGHT) * 100}%`,\n width: `${(bbox.width / PAGE_WIDTH) * 100}%`,\n height: `${(bbox.height / PAGE_HEIGHT) * 100}%`,\n }\n}\n\nfunction getSignatureAspectRatio(bbox?: BoundingBox): number {\n if (!bbox || bbox.width <= 0 || bbox.height <= 0) {\n return DEFAULT_SIGNATURE_ASPECT_RATIO\n }\n\n return bbox.width / bbox.height\n}\n\nfunction getSignatureGuideSize({\n containerWidth,\n containerHeight,\n aspectRatio,\n}: {\n containerWidth: number\n containerHeight: number\n aspectRatio: number\n}): { width: number; height: number } {\n const maxWidth = Math.max(containerWidth - SIGNATURE_PAD_PADDING * 2, 1)\n const maxHeight = Math.max(containerHeight - SIGNATURE_PAD_PADDING * 2, 1)\n\n if (maxWidth / maxHeight > aspectRatio) {\n const height = maxHeight\n return {\n width: height * aspectRatio,\n height,\n }\n }\n\n const width = maxWidth\n return {\n width,\n height: width / aspectRatio,\n }\n}\n\nfunction getSignatureDataUrl(canvas: HTMLCanvasElement): string {\n return canvas.toDataURL("image/png")\n}\n\nfunction SignatureDialog({\n open,\n fieldBbox,\n initialValue,\n onOpenChange,\n onConfirm,\n}: {\n open: boolean\n fieldBbox: BoundingBox\n initialValue?: string\n onOpenChange: (open: boolean) => void\n onConfirm: (value: string) => void\n}) {\n const canvasContainerRef = React.useRef<HTMLDivElement>(null)\n const canvasRef = React.useRef<HTMLCanvasElement>(null)\n const signaturePadRef = React.useRef<SignaturePad | null>(null)\n const [isReady, setIsReady] = React.useState(false)\n const [hasSignature, setHasSignature] = React.useState(false)\n const [guideSize, setGuideSize] = React.useState<{\n width: number\n height: number\n } | null>(null)\n const signatureAspectRatio = React.useMemo(\n () => getSignatureAspectRatio(fieldBbox),\n [fieldBbox]\n )\n\n React.useEffect(() => {\n if (!open) {\n setGuideSize(null)\n return\n }\n\n let frameId = 0\n let resizeObserver: ResizeObserver | null = null\n\n const updateGuideSize = (container?: HTMLDivElement | null) => {\n const currentContainer = container ?? canvasContainerRef.current\n if (\n !currentContainer ||\n currentContainer.clientWidth <= 0 ||\n currentContainer.clientHeight <= 0\n ) {\n return false\n }\n\n const nextSize = getSignatureGuideSize({\n containerWidth: currentContainer.clientWidth,\n containerHeight: currentContainer.clientHeight,\n aspectRatio: signatureAspectRatio,\n })\n\n setGuideSize((previousSize) => {\n if (\n previousSize &&\n Math.abs(previousSize.width - nextSize.width) < 0.5 &&\n Math.abs(previousSize.height - nextSize.height) < 0.5\n ) {\n return previousSize\n }\n\n return nextSize\n })\n\n return true\n }\n\n const connect = () => {\n const container = canvasContainerRef.current\n if (!updateGuideSize(container)) {\n frameId = window.requestAnimationFrame(connect)\n return\n }\n\n if (container) {\n resizeObserver = new ResizeObserver(() => {\n updateGuideSize(container)\n })\n resizeObserver.observe(container)\n }\n }\n\n connect()\n\n return () => {\n window.cancelAnimationFrame(frameId)\n resizeObserver?.disconnect()\n }\n }, [open, signatureAspectRatio])\n\n React.useEffect(() => {\n if (!open || !guideSize || guideSize.width <= 1 || guideSize.height <= 1) {\n signaturePadRef.current?.off()\n signaturePadRef.current = null\n setIsReady(false)\n if (!open) {\n setHasSignature(false)\n }\n return\n }\n\n let cancelled = false\n let resizeObserver: ResizeObserver | null = null\n\n const syncCanvasSize = (canvas: HTMLCanvasElement) => {\n const width = Math.max(canvas.offsetWidth, 1)\n const height = Math.max(canvas.offsetHeight, 1)\n const ratio = Math.max(window.devicePixelRatio || 1, 1)\n\n canvas.style.width = `${width}px`\n canvas.style.height = `${height}px`\n canvas.width = Math.floor(width * ratio)\n canvas.height = Math.floor(height * ratio)\n const context = canvas.getContext("2d")\n context?.setTransform(1, 0, 0, 1, 0, 0)\n context?.scale(ratio, ratio)\n\n return { width, height, ratio }\n }\n\n const initialize = async () => {\n const canvas = canvasRef.current\n if (!canvas) return\n\n const { default: SignaturePadConstructor } = await import("signature_pad")\n if (cancelled) return\n\n const signaturePad = new SignaturePadConstructor(canvas, {\n minWidth: 1,\n maxWidth: 2,\n penColor: SIGNATURE_PAD_PEN_COLOR,\n })\n\n signaturePadRef.current = signaturePad\n\n const loadSignature = async (dataUrl?: string) => {\n const size = syncCanvasSize(canvas)\n\n if (dataUrl) {\n await signaturePad.fromDataURL(dataUrl, size)\n setHasSignature(true)\n return\n }\n\n signaturePad.clear()\n setHasSignature(false)\n }\n\n await loadSignature(initialValue)\n if (cancelled) return\n\n signaturePad.addEventListener("endStroke", () => {\n setHasSignature(true)\n })\n\n resizeObserver = new ResizeObserver(() => {\n const currentCanvas = canvasRef.current\n const currentSignaturePad = signaturePadRef.current\n if (!currentCanvas || !currentSignaturePad) return\n\n const previousSignature = currentSignaturePad.isEmpty()\n ? undefined\n : currentSignaturePad.toDataURL("image/png")\n void loadSignature(previousSignature)\n })\n resizeObserver.observe(canvas)\n setIsReady(true)\n }\n\n const animationFrame = window.requestAnimationFrame(() => {\n void initialize()\n })\n\n return () => {\n cancelled = true\n window.cancelAnimationFrame(animationFrame)\n resizeObserver?.disconnect()\n signaturePadRef.current?.off()\n signaturePadRef.current = null\n setIsReady(false)\n }\n }, [open, guideSize, initialValue])\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className="max-w-xl">\n <DialogHeader>\n <DialogTitle>Add signature</DialogTitle>\n <DialogDescription>\n Draw a signature to place it into the selected PDF field.\n </DialogDescription>\n </DialogHeader>\n <DialogPanel>\n <div className="rounded-xl border bg-white p-3 text-slate-950 shadow-xs dark:bg-white dark:text-slate-950">\n <div\n ref={canvasContainerRef}\n className="flex h-56 w-full items-center justify-center overflow-hidden rounded-lg bg-white p-2 dark:bg-white"\n >\n <div\n className={cn(\n "relative overflow-hidden rounded-[3px] border border-dashed border-blue-500/70 bg-white",\n isReady ? "cursor-crosshair" : "cursor-wait"\n )}\n style={{\n width: guideSize ? `${guideSize.width}px` : undefined,\n height: guideSize ? `${guideSize.height}px` : undefined,\n opacity: guideSize ? 1 : 0,\n backgroundColor: SIGNATURE_PAD_BACKGROUND_COLOR,\n }}\n >\n <canvas\n ref={canvasRef}\n className={cn(\n "absolute inset-0 size-full touch-none",\n !isReady && "pointer-events-none"\n )}\n style={{\n backgroundColor: SIGNATURE_PAD_BACKGROUND_COLOR,\n touchAction: "none",\n }}\n />\n </div>\n </div>\n </div>\n </DialogPanel>\n <DialogFooter className="sm:justify-between">\n <Button\n type="button"\n variant="outline"\n disabled={!isReady}\n onClick={() => {\n signaturePadRef.current?.clear()\n setHasSignature(false)\n }}\n >\n Clear\n </Button>\n <div className="flex flex-col-reverse gap-2 sm:flex-row">\n <Button\n type="button"\n variant="outline"\n onClick={() => onOpenChange(false)}\n >\n Cancel\n </Button>\n <Button\n type="button"\n disabled={!isReady || !hasSignature}\n onClick={() => {\n const canvas = canvasRef.current\n if (!canvas) return\n\n onConfirm(getSignatureDataUrl(canvas))\n onOpenChange(false)\n }}\n >\n Confirm\n </Button>\n </div>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\nfunction SignatureFieldOverlay({\n field,\n onOpen,\n}: {\n field: SignatureField\n onOpen: () => void\n}) {\n return (\n <button\n type="button"\n className={cn(\n "absolute z-20 overflow-hidden rounded-[3px] border border-blue-500/70 transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",\n field.imageDataUrl\n ? "bg-transparent shadow-none hover:bg-blue-500/5"\n : "bg-blue-500/10 hover:bg-blue-500/15"\n )}\n style={bboxToStyle(field.bbox)}\n onClick={onOpen}\n >\n {field.imageDataUrl ? (\n <img\n src={field.imageDataUrl}\n alt=""\n className="size-full object-fill"\n draggable={false}\n />\n ) : (\n <span className="flex size-full items-center justify-center gap-1.5 px-2 text-[11px] font-medium text-blue-700 dark:text-blue-300">\n <IconPlaceholder\n lucide="Pen"\n tabler="IconPencil"\n hugeicons="Pen01Icon"\n phosphor="PenIcon"\n remixicon="RiPencilLine"\n className="size-3.5"\n />\n Signature\n </span>\n )}\n </button>\n )\n}\n\nasync function downloadSignedPdf({\n file,\n field,\n}: {\n file: string\n field: SignatureField\n}) {\n const { PDFDocument } = await import("pdf-lib")\n const existingPdfBytes = await fetch(file).then((response) =>\n response.arrayBuffer()\n )\n const pdfDocument = await PDFDocument.load(existingPdfBytes)\n const page = pdfDocument.getPage(field.page - 1)\n\n if (field.imageDataUrl) {\n const signatureImage = await pdfDocument.embedPng(field.imageDataUrl)\n const { width: pageWidth, height: pageHeight } = page.getSize()\n const scaleX = pageWidth / PAGE_WIDTH\n const scaleY = pageHeight / PAGE_HEIGHT\n const fieldWidth = field.bbox.width * scaleX\n const fieldHeight = field.bbox.height * scaleY\n const fieldX = field.bbox.x * scaleX\n const fieldY = pageHeight - (field.bbox.y + field.bbox.height) * scaleY\n\n page.drawImage(signatureImage, {\n x: fieldX,\n y: fieldY,\n width: fieldWidth,\n height: fieldHeight,\n })\n }\n\n const bytes = await pdfDocument.save()\n const blob = new Blob([new Uint8Array(bytes)], { type: "application/pdf" })\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n anchor.href = url\n anchor.download = "signed-document.pdf"\n anchor.click()\n URL.revokeObjectURL(url)\n}\n\nfunction SignatureFieldsPanel({\n field,\n className,\n canExport,\n isDownloading,\n onSign,\n onClear,\n onDownload,\n}: {\n field: SignatureField\n className?: string\n canExport: boolean\n isDownloading: boolean\n onSign: () => void\n onClear: () => void\n onDownload: () => void\n}) {\n return (\n <aside className={cn("flex min-h-0 flex-col bg-background", className)}>\n <ScrollArea className="min-h-0 flex-1" scrollFade>\n <div className="space-y-4 p-4">\n <div className="space-y-1">\n <h3 className="text-sm font-medium">Signature fields</h3>\n <p className="text-xs text-muted-foreground">\n Review fields, collect signatures, and export a signed PDF.\n </p>\n </div>\n <div className="rounded-lg border bg-background p-3">\n <div className="flex items-start gap-3">\n <div className="grid size-9 shrink-0 place-items-center rounded-md bg-blue-500/10 text-blue-600 dark:text-blue-300">\n <IconPlaceholder\n lucide="FilePen"\n tabler="IconFilePencil"\n hugeicons="FilePenIcon"\n phosphor="NotePencilIcon"\n remixicon="RiFileEditLine"\n className="size-4"\n />\n </div>\n <div className="min-w-0 flex-1">\n <div className="flex items-center justify-between gap-2">\n <div className="text-sm font-medium">{field.label}</div>\n <div\n className={cn(\n "rounded-full px-2 py-0.5 text-xs",\n field.imageDataUrl\n ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-300"\n : "bg-muted text-muted-foreground"\n )}\n >\n {field.imageDataUrl ? "Signed" : "Unsigned"}\n </div>\n </div>\n <div className="mt-2 text-xs text-muted-foreground">\n {Math.round(field.bbox.width)} x{" "}\n {Math.round(field.bbox.height)} on page {field.page}\n </div>\n <div className="mt-3 flex gap-2">\n <Button\n type="button"\n size="sm"\n variant={field.imageDataUrl ? "outline" : "default"}\n className="flex-1"\n onClick={onSign}\n >\n <IconPlaceholder\n lucide="Pen"\n tabler="IconPencil"\n hugeicons="Pen01Icon"\n phosphor="PenIcon"\n remixicon="RiPencilLine"\n className="size-4"\n />\n {field.imageDataUrl ? "Edit" : "Sign"}\n </Button>\n {field.imageDataUrl ? (\n <Button\n type="button"\n size="sm"\n variant="outline"\n onClick={onClear}\n >\n Clear\n </Button>\n ) : null}\n </div>\n </div>\n </div>\n </div>\n <Button\n type="button"\n className="w-full"\n disabled={!canExport || isDownloading}\n onClick={onDownload}\n >\n <IconPlaceholder\n lucide="Download"\n tabler="IconDownload"\n hugeicons="Download01Icon"\n phosphor="DownloadSimpleIcon"\n remixicon="RiDownload2Line"\n className="size-4"\n />\n {isDownloading ? "Exporting..." : "Export signed PDF"}\n </Button>\n </div>\n </ScrollArea>\n </aside>\n )\n}\n\nexport function ESignatureBlock({ file }: { file?: string }) {\n const [field, setField] = React.useState<SignatureField>(INITIAL_FIELD)\n const [dialogOpen, setDialogOpen] = React.useState(false)\n const [isDownloading, setIsDownloading] = React.useState(false)\n\n const handleDownload = React.useCallback(async () => {\n if (!file || !field.imageDataUrl) return\n\n setIsDownloading(true)\n try {\n await downloadSignedPdf({ file, field })\n } finally {\n setIsDownloading(false)\n }\n }, [field, file])\n\n return (\n <>\n <PdfBlockResizableShell\n autoSaveId="pdf-block-e-signature"\n left={\n <PDFViewer\n src={file}\n defaultZoom={DEFAULT_ZOOM}\n toolbarActions={\n <Button\n type="button"\n size="sm"\n variant="outline"\n disabled={!file || !field.imageDataUrl || isDownloading}\n onClick={handleDownload}\n >\n <IconPlaceholder\n lucide="Download"\n tabler="IconDownload"\n hugeicons="Download01Icon"\n phosphor="DownloadSimpleIcon"\n remixicon="RiDownload2Line"\n className="size-4"\n />\n Download\n </Button>\n }\n renderPageOverlay={({ pageNumber }) =>\n pageNumber === field.page ? (\n <SignatureFieldOverlay\n field={field}\n onOpen={() => setDialogOpen(true)}\n />\n ) : null\n }\n />\n }\n right={\n <SignatureFieldsPanel\n field={field}\n canExport={Boolean(file && field.imageDataUrl)}\n isDownloading={isDownloading}\n onSign={() => setDialogOpen(true)}\n onClear={() =>\n setField((previousField) => ({\n ...previousField,\n imageDataUrl: undefined,\n }))\n }\n onDownload={handleDownload}\n />\n }\n />\n <SignatureDialog\n open={dialogOpen}\n fieldBbox={field.bbox}\n initialValue={field.imageDataUrl}\n onOpenChange={setDialogOpen}\n onConfirm={(imageDataUrl) => {\n setField((previousField) => ({ ...previousField, imageDataUrl }))\n }}\n />\n </>\n )\n}\n'export function ESignatureSource() {return (diff --git a/apps/v4/components/extend/bounding-box-citations.tsx b/apps/v4/components/extend/bounding-box-citations.tsxindex db05cae..02e9109 100644--- a/apps/v4/components/extend/bounding-box-citations.tsx+++ b/apps/v4/components/extend/bounding-box-citations.tsx@@ -18,17 +18,6 @@ import {type TextCell,type Theme,} from "@glideapps/glide-data-grid"-import {- ArrowLeft01Icon,- CancelCircleIcon,- InputNumericIcon,- InputTextIcon,- SecondBracketIcon,- SourceCodeSquareIcon,- TextCheckIcon,- Undo02Icon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { Virtualizer as DiffsVirtualizer } from "@pierre/diffs"import {File,@@ -52,9 +41,75 @@ import {TooltipProvider,TooltipTrigger,} from "@/components/ui/tooltip"+import { IconPlaceholder } from "@/components/icon-placeholder"import "@glideapps/glide-data-grid/dist/index.css"+function InputNumericGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Hash"+ tabler="IconNumber123"+ hugeicons="InputNumericIcon"+ phosphor="NumpadIcon"+ remixicon="RiHashtag"+ {...props}+ />+ )+}++function InputTextGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="TextCursorInput"+ tabler="IconForms"+ hugeicons="InputTextIcon"+ phosphor="TextboxIcon"+ remixicon="RiInputField"+ {...props}+ />+ )+}++function SecondBracketGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Brackets"+ tabler="IconBrackets"+ hugeicons="SecondBracketIcon"+ phosphor="BracketsSquareIcon"+ remixicon="RiBracketsLine"+ {...props}+ />+ )+}++function SourceCodeSquareGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="SquareCode"+ tabler="IconSourceCode"+ hugeicons="SourceCodeSquareIcon"+ phosphor="CodeIcon"+ remixicon="RiCodeBlock"+ {...props}+ />+ )+}++function TextCheckGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="CaptionsIcon"+ tabler="IconTextCaption"+ hugeicons="TextCheckIcon"+ phosphor="TextTIcon"+ remixicon="RiTextWrap"+ {...props}+ />+ )+}+export type JsonPrimitive = string | number | boolean | nullexport type JsonValue = JsonPrimitive | JsonObject | JsonArrayexport type JsonObject = { [key: string]: JsonValue }@@ -924,11 +979,11 @@ function HumanReviewTextOverlayEditor({}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+ if (type === "number" || type === "integer") return InputNumericGlyph+ if (type === "boolean") return TextCheckGlyph+ if (type === "array") return SecondBracketGlyph+ if (type === "object") return SourceCodeSquareGlyph+ return InputTextGlyph}function HumanReviewValueInput({@@ -1682,7 +1737,14 @@ function HumanReviewArrayValueGrid({}aria-label="Back to parent array">- <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />+ <IconPlaceholder+ lucide="ChevronLeft"+ tabler="IconChevronLeft"+ hugeicons="ArrowLeft01Icon"+ phosphor="CaretLeftIcon"+ remixicon="RiArrowLeftSLine"+ className="size-3.5"+ /></Button><div className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">{activeNestedView.title}@@ -1850,7 +1912,9 @@ function HumanReviewFieldCardBase({}: HumanReviewFieldCardProps) {const isExpectedEditable = showExpected && !readOnlyconst modified = showExpected && !jsonValuesEqual(value, originalValue)- const Icon = getFieldIcon(field.schema.type)+ const fieldTypeIcon = React.createElement(getFieldIcon(field.schema.type), {+ className: "size-3.5",+ })const propertyEntries = Object.entries(field.schema.properties ?? {})const [syncedArrayNestedView, setSyncedArrayNestedView] =React.useState<SyncedArrayNestedView>(EMPTY_SYNCED_ARRAY_NESTED_VIEW)@@ -1938,7 +2002,14 @@ function HumanReviewFieldCardBase({onClick={onUndo}aria-label={`Undo ${field.key}`}>- <HugeiconsIcon icon={Undo02Icon} className="size-4" />+ <IconPlaceholder+ lucide="Undo2"+ tabler="IconArrowBackUp"+ hugeicons="Undo02Icon"+ phosphor="ArrowUUpLeftIcon"+ remixicon="RiArrowGoBackLine"+ className="size-4"+ /></Button></TooltipTrigger><TooltipContent>Revert changes</TooltipContent>@@ -1955,14 +2026,21 @@ function HumanReviewFieldCardBase({onClick={onSetNull}aria-label={`Set ${field.key} to null`}>- <HugeiconsIcon icon={CancelCircleIcon} className="size-4" />+ <IconPlaceholder+ lucide="CircleX"+ tabler="IconCircleX"+ hugeicons="CancelCircleIcon"+ phosphor="XCircleIcon"+ remixicon="RiCloseCircleLine"+ 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" />+ {fieldTypeIcon}{field.schema.type}</div></div>@@ -2286,11 +2364,25 @@ export function HumanReviewPanel({<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" />+ <IconPlaceholder+ lucide="CaptionsIcon"+ tabler="IconTextCaption"+ hugeicons="TextCheckIcon"+ phosphor="TextTIcon"+ remixicon="RiTextWrap"+ className="size-4"+ />Form</TabsTrigger><TabsTrigger value="json" className="h-7 sm:h-6">- <HugeiconsIcon icon={SourceCodeSquareIcon} className="size-4" />+ <IconPlaceholder+ lucide="SquareCode"+ tabler="IconSourceCode"+ hugeicons="SourceCodeSquareIcon"+ phosphor="CodeIcon"+ remixicon="RiCodeBlock"+ className="size-4"+ />JSON</TabsTrigger></TabsList>diff --git a/apps/v4/components/extend/csv-viewer.tsx b/apps/v4/components/extend/csv-viewer.tsxindex 1b12f0f..1bb3881 100644--- a/apps/v4/components/extend/csv-viewer.tsx+++ b/apps/v4/components/extend/csv-viewer.tsx@@ -18,17 +18,6 @@ import {import "@glideapps/glide-data-grid/dist/index.css"-import {- ArrowLeft01Icon,- ArrowRight01Icon,- Download01Icon,- MinusSignCircleIcon,- MoreHorizontalIcon,- PlusSignCircleIcon,- Search01Icon,- Upload01Icon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import Papa from "papaparse"import { cn } from "@/lib/utils"@@ -60,6 +49,7 @@ import {TooltipProvider,TooltipTrigger,} from "@/components/ui/tooltip"+import { IconPlaceholder } from "@/components/icon-placeholder"const ZOOM_OPTIONS = [0.75, 1, 1.25, 1.5, 2] as constconst CSV_SEARCH_BATCH_ROW_COUNT = 500@@ -287,19 +277,40 @@ function CsvFileActionsMenu({aria-label="Open CSV actions"disabled={isPending}>- <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />+ <IconPlaceholder+ lucide="Ellipsis"+ tabler="IconDots"+ hugeicons="MoreHorizontalIcon"+ phosphor="DotsThreeIcon"+ remixicon="RiMoreLine"+ className="size-4"+ /></Button></DropdownMenuTrigger><DropdownMenuContent align="end" className="w-40"><DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>- <HugeiconsIcon icon={Download01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Download"+ tabler="IconDownload"+ hugeicons="Download01Icon"+ phosphor="DownloadSimpleIcon"+ remixicon="RiDownload2Line"+ className="size-4"+ />Download</DropdownMenuItem><DropdownMenuItem disabled={isPending} onClick={onUploadClick}>{isPending ? (<Spinner className="size-4" />) : (- <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-4"+ />)}Upload</DropdownMenuItem>@@ -484,7 +495,14 @@ function CsvSearchPopover({aria-label="Search CSV"disabled={controlsDisabled}>- <HugeiconsIcon icon={Search01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Search"+ tabler="IconSearch"+ hugeicons="Search01Icon"+ phosphor="MagnifyingGlassIcon"+ remixicon="RiSearchLine"+ className="size-4"+ /></Button></PopoverTrigger></ToolbarTooltip>@@ -537,7 +555,14 @@ function CsvSearchPopover({disabled={isSearching || searchResults.length === 0}onClick={() => goToRelativeResult(-1)}>- <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />+ <IconPlaceholder+ lucide="ChevronLeft"+ tabler="IconChevronLeft"+ hugeicons="ArrowLeft01Icon"+ phosphor="CaretLeftIcon"+ remixicon="RiArrowLeftSLine"+ className="size-4"+ /></Button><Buttontype="button"@@ -547,7 +572,14 @@ function CsvSearchPopover({disabled={isSearching || searchResults.length === 0}onClick={() => goToRelativeResult(1)}>- <HugeiconsIcon icon={ArrowRight01Icon} className="size-4" />+ <IconPlaceholder+ lucide="ArrowRight"+ tabler="IconArrowRight"+ hugeicons="ArrowRight01Icon"+ phosphor="ArrowRightIcon"+ remixicon="RiArrowRightLine"+ className="size-4"+ /></Button></div></div>@@ -785,8 +817,12 @@ export function CsvViewer({ className, data, search = false }: CsvViewerProps) {disabled={zoom <= ZOOM_OPTIONS[0]}onClick={() => stepZoom(-1)}>- <HugeiconsIcon- icon={MinusSignCircleIcon}+ <IconPlaceholder+ lucide="CircleMinus"+ tabler="IconCircleMinus"+ hugeicons="MinusSignCircleIcon"+ phosphor="MinusCircleIcon"+ remixicon="RiIndeterminateCircleLine"className="size-4"/></Button>@@ -821,7 +857,14 @@ export function CsvViewer({ className, data, search = false }: CsvViewerProps) {disabled={zoom >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]}onClick={() => stepZoom(1)}>- <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />+ <IconPlaceholder+ lucide="CirclePlusIcon"+ tabler="IconCirclePlusFilled"+ hugeicons="PlusSignCircleIcon"+ phosphor="PlusCircleIcon"+ remixicon="RiAddCircleFill"+ className="size-4"+ /></Button></ToolbarTooltip></div>@@ -886,7 +929,14 @@ export function CsvViewer({ className, data, search = false }: CsvViewerProps) {loading={isPending}onClick={() => inputRef.current?.click()}>- <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-4"+ />Upload CSV</Button></div>diff --git a/apps/v4/components/extend/document-splits.tsx b/apps/v4/components/extend/document-splits.tsxindex 9289b62..06f8b2d 100644--- a/apps/v4/components/extend/document-splits.tsx+++ b/apps/v4/components/extend/document-splits.tsx@@ -22,17 +22,12 @@ import {verticalListSortingStrategy,} from "@dnd-kit/sortable"import { CSS } from "@dnd-kit/utilities"-import {- Add01Icon,- Delete02Icon,- DragDropVerticalIcon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"import { ScrollArea } from "@/components/ui/scroll-area"import { FileThumbnail } from "@/components/extend/file-thumbnail"+import { IconPlaceholder } from "@/components/icon-placeholder"export type DocumentSplitPageId = `page-${number}`export type DocumentSplit = {@@ -332,7 +327,14 @@ function SplitGroupCard({className="inline-flex size-7 shrink-0 cursor-grab items-center justify-center rounded-md text-muted-foreground hover:bg-muted active:cursor-grabbing"{...dragHandleProps}>- <HugeiconsIcon icon={DragDropVerticalIcon} className="size-4" />+ <IconPlaceholder+ lucide="GripVertical"+ tabler="IconGripVertical"+ hugeicons="DragDropVerticalIcon"+ phosphor="DotsSixVerticalIcon"+ remixicon="RiDraggable"+ className="size-4"+ /></button><div className="min-w-0"><div className="truncate text-sm font-medium">{group.title}</div>@@ -353,7 +355,14 @@ function SplitGroupCard({disabled={!canRemove}onClick={onRemove}>- <HugeiconsIcon icon={Delete02Icon} className="size-4" />+ <IconPlaceholder+ lucide="Trash2Icon"+ tabler="IconTrash"+ hugeicons="Delete02Icon"+ phosphor="TrashIcon"+ remixicon="RiDeleteBinLine"+ className="size-4"+ /></Button></div></div>@@ -657,7 +666,14 @@ export function DocumentSplits({])}>- <HugeiconsIcon icon={Add01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Plus"+ tabler="IconPlus"+ hugeicons="Add01Icon"+ phosphor="PlusIcon"+ remixicon="RiAddLine"+ className="size-4"+ />Add split</Button></div>diff --git a/apps/v4/components/extend/docx-editor.tsx b/apps/v4/components/extend/docx-editor.tsxindex 15cf1f8..9e35053 100644--- a/apps/v4/components/extend/docx-editor.tsx+++ b/apps/v4/components/extend/docx-editor.tsx@@ -20,51 +20,6 @@ import {type DocxEditorController,type ParagraphStyleDefinition,} from "@extend-ai/react-docx"-import {- ArrowExpandDiagonal01Icon,- ArrowExpandDiagonal02Icon,- BorderAll01Icon,- BorderBottom01Icon,- BorderHorizontalIcon,- BorderInnerIcon,- BorderLeft01Icon,- BorderNone01Icon,- BorderRight01Icon,- BorderTop01Icon,- BorderVerticalIcon,- ColumnsThreeCogIcon,- Comment01Icon,- Download01Icon,- EditOffIcon,- FileDiffIcon,- HighlighterIcon,- ImageAdd01Icon,- LeftToRightListBulletIcon,- LeftToRightListNumberIcon,- LineIcon,- Link02Icon,- MinusSignCircleIcon,- Moon02Icon,- PlusSignCircleIcon,- Redo02Icon,- SidebarLeftIcon,- Sun03Icon,- TableIcon,- TextAlignCenterIcon,- TextAlignJustifyLeftIcon,- TextAlignLeft01Icon,- TextAlignRight01Icon,- TextBoldIcon,- TextColorIcon,- TextItalicIcon,- TextStrikethroughIcon,- TextSubscriptIcon,- TextSuperscriptIcon,- TextUnderlineIcon,- Undo02Icon,- Upload01Icon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"@@ -104,6 +59,202 @@ import {createDocxTrackedChangeCardRenderer,} from "@/components/extend/docx-annotation-card"import { FileThumbnail } from "@/components/extend/file-thumbnail"+import { IconPlaceholder } from "@/components/icon-placeholder"++function ArrowExpandDiagonal01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="ArrowDownRight"+ tabler="IconArrowDownRight"+ hugeicons="ArrowExpandDiagonal01Icon"+ phosphor="ArrowDownRightIcon"+ remixicon="RiArrowRightDownLine"+ {...props}+ />+ )+}++function ArrowExpandDiagonal02Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="ArrowUpRight"+ tabler="IconArrowUpRight"+ hugeicons="ArrowExpandDiagonal02Icon"+ phosphor="ArrowUpRightIcon"+ remixicon="RiArrowRightUpLine"+ {...props}+ />+ )+}++function BorderAll01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Grid2x2"+ tabler="IconBorderAll"+ hugeicons="BorderAll01Icon"+ phosphor="GridFourIcon"+ remixicon="RiGridLine"+ {...props}+ />+ )+}++function BorderBottom01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="PanelBottom"+ tabler="IconBorderBottom"+ hugeicons="BorderBottom01Icon"+ phosphor="SquareHalfBottomIcon"+ remixicon="RiLayoutBottomLine"+ {...props}+ />+ )+}++function BorderHorizontalGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="SeparatorHorizontal"+ tabler="IconBorderHorizontal"+ hugeicons="BorderHorizontalIcon"+ phosphor="MinusIcon"+ remixicon="RiSeparator"+ {...props}+ />+ )+}++function BorderInnerGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="SquarePlus"+ tabler="IconBorderInner"+ hugeicons="BorderInnerIcon"+ phosphor="PlusSquareIcon"+ remixicon="RiAddBoxLine"+ {...props}+ />+ )+}++function BorderLeft01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="PanelLeft"+ tabler="IconBorderLeft"+ hugeicons="BorderLeft01Icon"+ phosphor="SquareHalfIcon"+ remixicon="RiLayoutLeftLine"+ {...props}+ />+ )+}++function BorderNone01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="SquareDashed"+ tabler="IconBorderNone"+ hugeicons="BorderNone01Icon"+ phosphor="SelectionIcon"+ remixicon="RiCheckboxBlankLine"+ {...props}+ />+ )+}++function BorderRight01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="PanelRight"+ tabler="IconBorderRight"+ hugeicons="BorderRight01Icon"+ phosphor="SquareHalfIcon"+ remixicon="RiLayoutRightLine"+ {...props}+ />+ )+}++function BorderTop01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="PanelTop"+ tabler="IconBorderTop"+ hugeicons="BorderTop01Icon"+ phosphor="AlignTopSimpleIcon"+ remixicon="RiLayoutTopLine"+ {...props}+ />+ )+}++function BorderVerticalGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="SeparatorVertical"+ tabler="IconBorderVertical"+ hugeicons="BorderVerticalIcon"+ phosphor="LineVerticalIcon"+ remixicon="RiLayoutColumnLine"+ {...props}+ />+ )+}++function LineGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Minus"+ tabler="IconMinus"+ hugeicons="LineIcon"+ phosphor="MinusIcon"+ remixicon="RiSubtractLine"+ {...props}+ />+ )+}++function Moon02Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Moon"+ tabler="IconMoon"+ hugeicons="Moon02Icon"+ phosphor="MoonIcon"+ remixicon="RiMoonLine"+ {...props}+ />+ )+}++function Sun03Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Sun"+ tabler="IconSun"+ hugeicons="Sun03Icon"+ phosphor="SunIcon"+ remixicon="RiSunLine"+ {...props}+ />+ )+}++function TextColorGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Baseline"+ tabler="IconTextColor"+ hugeicons="TextColorIcon"+ phosphor="TextAaIcon"+ remixicon="RiFontColor"+ {...props}+ />+ )+}const DOCX_MIME_TYPE ="application/vnd.openxmlformats-officedocument.wordprocessingml.document"@@ -239,29 +390,29 @@ const BORDER_CONTROL_OPTIONS: BorderControlOption[] = [function borderControlOptionIcon(optionId: DocxBorderPreset) {switch (optionId) {case "bottom":- return BorderBottom01Icon+ return BorderBottom01Glyphcase "top":- return BorderTop01Icon+ return BorderTop01Glyphcase "left":- return BorderLeft01Icon+ return BorderLeft01Glyphcase "right":- return BorderRight01Icon+ return BorderRight01Glyphcase "none":- return BorderNone01Icon+ return BorderNone01Glyphcase "inside":- return BorderInnerIcon+ return BorderInnerGlyphcase "inside-horizontal":- return BorderHorizontalIcon+ return BorderHorizontalGlyphcase "inside-vertical":- return BorderVerticalIcon+ return BorderVerticalGlyphcase "diagonal-down":- return ArrowExpandDiagonal01Icon+ return ArrowExpandDiagonal01Glyphcase "diagonal-up":- return ArrowExpandDiagonal02Icon+ return ArrowExpandDiagonal02Glyphcase "horizontal-line":- return LineIcon+ return LineGlyphdefault:- return BorderAll01Icon+ return BorderAll01Glyph}}@@ -791,10 +942,13 @@ function DocxEditorToolbar({activeBorderControlOptions.length === 1? activeBorderControlOptions[0].label: "Borders"- const borderTriggerIcon = borderControlOptionIcon(- activeBorderControlOptions.length === 1- ? activeBorderControlOptions[0].id- : "all"+ const borderTriggerIcon = React.createElement(+ borderControlOptionIcon(+ activeBorderControlOptions.length === 1+ ? activeBorderControlOptions[0].id+ : "all"+ ),+ { className: "size-4" })const canEdit = !controlsDisabled && !isReadOnlyconst canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]@@ -853,7 +1007,14 @@ function DocxEditorToolbar({disabled={controlsDisabled}onClick={onToggleSidebar}>- <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />+ <IconPlaceholder+ lucide="PanelLeft"+ tabler="IconLayoutSidebar"+ hugeicons="SidebarLeftIcon"+ phosphor="SidebarIcon"+ remixicon="RiLayoutLeftLine"+ className="size-4"+ /></ToolbarIconButton><div className="min-w-28 text-sm whitespace-nowrap text-primary">Page {pageCount ? activePage : 1} of {pageCount || "-"}@@ -874,10 +1035,11 @@ function DocxEditorToolbar({onIsDarkChange(nextIsDark)}}>- <HugeiconsIcon- icon={documentTheme === "dark" ? Sun03Icon : Moon02Icon}- className="size-4"- />+ {documentTheme === "dark" ? (+ <Sun03Glyph className="size-4" />+ ) : (+ <Moon02Glyph className="size-4" />+ )}</ToolbarIconButton><Separatororientation="vertical"@@ -891,7 +1053,14 @@ function DocxEditorToolbar({disabled={controlsDisabled}onClick={() => setShowTrackedChanges(!showTrackedChanges)}>- <HugeiconsIcon icon={FileDiffIcon} className="size-4" />+ <IconPlaceholder+ lucide="FileDiff"+ tabler="IconFileDiff"+ hugeicons="FileDiffIcon"+ phosphor="GitDiffIcon"+ remixicon="RiFileHistoryLine"+ className="size-4"+ /></ToolbarIconButton><ToolbarIconButtonlabel="Show comments"@@ -899,7 +1068,14 @@ function DocxEditorToolbar({disabled={controlsDisabled}onClick={() => setShowComments(!showComments)}>- <HugeiconsIcon icon={Comment01Icon} className="size-4" />+ <IconPlaceholder+ lucide="MessageSquare"+ tabler="IconMessage"+ hugeicons="Comment01Icon"+ phosphor="ChatIcon"+ remixicon="RiChat1Line"+ className="size-4"+ /></ToolbarIconButton><ToolbarIconButtonlabel={isReadOnly ? "Switch to edit mode" : "Switch to read-only"}@@ -907,7 +1083,14 @@ function DocxEditorToolbar({disabled={controlsDisabled}onClick={() => onIsReadOnlyChange(!isReadOnly)}>- <HugeiconsIcon icon={EditOffIcon} className="size-4" />+ <IconPlaceholder+ lucide="PencilOff"+ tabler="IconPencilOff"+ hugeicons="EditOffIcon"+ phosphor="PencilSlashIcon"+ remixicon="RiLockLine"+ className="size-4"+ /></ToolbarIconButton><Separator orientation="vertical" className="mx-1 h-4 self-center" /><ToolbarIconButton@@ -918,7 +1101,14 @@ function DocxEditorToolbar({{editor.isImporting ? (<Spinner className="size-4" />) : (- <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-4"+ />)}</ToolbarIconButton><ToolbarIconButton@@ -926,7 +1116,14 @@ function DocxEditorToolbar({disabled={controlsDisabled || editor.isImporting}onClick={editor.exportDocx}>- <HugeiconsIcon icon={Download01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Download"+ tabler="IconDownload"+ hugeicons="Download01Icon"+ phosphor="DownloadSimpleIcon"+ remixicon="RiDownload2Line"+ className="size-4"+ /></ToolbarIconButton></div>@@ -937,14 +1134,28 @@ function DocxEditorToolbar({disabled={!editor.canUndo || isReadOnly}onClick={editor.undo}>- <HugeiconsIcon icon={Undo02Icon} className="size-4" />+ <IconPlaceholder+ lucide="Undo2"+ tabler="IconArrowBackUp"+ hugeicons="Undo02Icon"+ phosphor="ArrowUUpLeftIcon"+ remixicon="RiArrowGoBackLine"+ className="size-4"+ /></ToolbarIconButton><ToolbarIconButtonlabel="Redo"disabled={!editor.canRedo || isReadOnly}onClick={editor.redo}>- <HugeiconsIcon icon={Redo02Icon} className="size-4" />+ <IconPlaceholder+ lucide="Redo2"+ tabler="IconArrowForwardUp"+ hugeicons="Redo02Icon"+ phosphor="ArrowUUpRightIcon"+ remixicon="RiArrowGoForwardLine"+ className="size-4"+ /></ToolbarIconButton></div>@@ -1162,12 +1373,26 @@ function DocxEditorToolbar({><ToolbarTooltip label="Bold"><ToggleGroupItem aria-label="Bold" size="sm" value="bold">- <HugeiconsIcon icon={TextBoldIcon} className="size-4" />+ <IconPlaceholder+ lucide="Bold"+ tabler="IconBold"+ hugeicons="TextBoldIcon"+ phosphor="TextBIcon"+ remixicon="RiBold"+ className="size-4"+ /></ToggleGroupItem></ToolbarTooltip><ToolbarTooltip label="Italic"><ToggleGroupItem aria-label="Italic" size="sm" value="italic">- <HugeiconsIcon icon={TextItalicIcon} className="size-4" />+ <IconPlaceholder+ lucide="Italic"+ tabler="IconItalic"+ hugeicons="TextItalicIcon"+ phosphor="TextItalicIcon"+ remixicon="RiItalic"+ className="size-4"+ /></ToggleGroupItem></ToolbarTooltip><ToolbarTooltip label="Underline">@@ -1176,7 +1401,14 @@ function DocxEditorToolbar({size="sm"value="underline">- <HugeiconsIcon icon={TextUnderlineIcon} className="size-4" />+ <IconPlaceholder+ lucide="Underline"+ tabler="IconUnderline"+ hugeicons="TextUnderlineIcon"+ phosphor="TextUnderlineIcon"+ remixicon="RiUnderline"+ className="size-4"+ /></ToggleGroupItem></ToolbarTooltip><ToolbarTooltip label="Strikethrough">@@ -1185,8 +1417,12 @@ function DocxEditorToolbar({size="sm"value="strike">- <HugeiconsIcon- icon={TextStrikethroughIcon}+ <IconPlaceholder+ lucide="Strikethrough"+ tabler="IconStrikethrough"+ hugeicons="TextStrikethroughIcon"+ phosphor="TextStrikethroughIcon"+ remixicon="RiStrikethrough"className="size-4"/></ToggleGroupItem>@@ -1197,7 +1433,14 @@ function DocxEditorToolbar({size="sm"value="superscript">- <HugeiconsIcon icon={TextSuperscriptIcon} className="size-4" />+ <IconPlaceholder+ lucide="Superscript"+ tabler="IconSuperscript"+ hugeicons="TextSuperscriptIcon"+ phosphor="TextSuperscriptIcon"+ remixicon="RiSuperscript"+ className="size-4"+ /></ToggleGroupItem></ToolbarTooltip><ToolbarTooltip label="Subscript">@@ -1206,7 +1449,14 @@ function DocxEditorToolbar({size="sm"value="subscript">- <HugeiconsIcon icon={TextSubscriptIcon} className="size-4" />+ <IconPlaceholder+ lucide="Subscript"+ tabler="IconSubscript"+ hugeicons="TextSubscriptIcon"+ phosphor="TextSubscriptIcon"+ remixicon="RiSubscript"+ className="size-4"+ /></ToggleGroupItem></ToolbarTooltip></ToggleGroup>@@ -1216,7 +1466,7 @@ function DocxEditorToolbar({<div className="flex shrink-0 items-center gap-1"><ColorPickerlabel="Text color"- icon={TextColorIcon}+ icon={TextColorGlyph}color={textColorValue}disabled={!canEdit}onTriggerMouseDown={preserveTextSelection}@@ -1235,7 +1485,14 @@ function DocxEditorToolbar({aria-label="Highlight color"className="relative">- <HugeiconsIcon icon={HighlighterIcon} className="size-4" />+ <IconPlaceholder+ lucide="Highlighter"+ tabler="IconHighlight"+ hugeicons="HighlighterIcon"+ phosphor="HighlighterIcon"+ remixicon="RiMarkPenLine"+ className="size-4"+ /><spanclassName="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"style={{ backgroundColor: highlightColor }}@@ -1272,7 +1529,14 @@ function DocxEditorToolbar({onPointerDown={preserveTextSelection}onClick={onOpenLinkEditor}>- <HugeiconsIcon icon={Link02Icon} className="size-4" />+ <IconPlaceholder+ lucide="Link"+ tabler="IconLink"+ hugeicons="Link02Icon"+ phosphor="LinkIcon"+ remixicon="RiLink"+ className="size-4"+ /></ToolbarIconButton></div>@@ -1290,7 +1554,14 @@ function DocxEditorToolbar({onPointerDown={preserveTextSelection}onClick={() => editor.setAlignment("left")}>- <HugeiconsIcon icon={TextAlignLeft01Icon} className="size-4" />+ <IconPlaceholder+ lucide="AlignLeft"+ tabler="IconAlignLeft"+ hugeicons="TextAlignLeft01Icon"+ phosphor="TextAlignLeftIcon"+ remixicon="RiAlignLeft"+ className="size-4"+ /></ToolbarIconButton><ToolbarIconButtonlabel="Align center"@@ -1300,7 +1571,14 @@ function DocxEditorToolbar({onPointerDown={preserveTextSelection}onClick={() => editor.setAlignment("center")}>- <HugeiconsIcon icon={TextAlignCenterIcon} className="size-4" />+ <IconPlaceholder+ lucide="AlignCenter"+ tabler="IconAlignCenter"+ hugeicons="TextAlignCenterIcon"+ phosphor="TextAlignCenterIcon"+ remixicon="RiAlignCenter"+ className="size-4"+ /></ToolbarIconButton><ToolbarIconButtonlabel="Align right"@@ -1310,7 +1588,14 @@ function DocxEditorToolbar({onPointerDown={preserveTextSelection}onClick={() => editor.setAlignment("right")}>- <HugeiconsIcon icon={TextAlignRight01Icon} className="size-4" />+ <IconPlaceholder+ lucide="AlignRight"+ tabler="IconAlignRight"+ hugeicons="TextAlignRight01Icon"+ phosphor="TextAlignRightIcon"+ remixicon="RiAlignRight"+ className="size-4"+ /></ToolbarIconButton><ToolbarIconButtonlabel="Justify"@@ -1320,8 +1605,12 @@ function DocxEditorToolbar({onPointerDown={preserveTextSelection}onClick={() => editor.setAlignment("justify")}>- <HugeiconsIcon- icon={TextAlignJustifyLeftIcon}+ <IconPlaceholder+ lucide="AlignJustify"+ tabler="IconAlignJustified"+ hugeicons="TextAlignJustifyLeftIcon"+ phosphor="TextAlignJustifyIcon"+ remixicon="RiAlignJustify"className="size-4"/></ToolbarIconButton>@@ -1338,8 +1627,12 @@ function DocxEditorToolbar({onPointerDown={preserveTextSelection}onClick={() => editor.toggleList("unordered")}>- <HugeiconsIcon- icon={LeftToRightListBulletIcon}+ <IconPlaceholder+ lucide="Columns3Icon"+ tabler="IconLayoutColumns"+ hugeicons="LeftToRightListBulletIcon"+ phosphor="ColumnsIcon"+ remixicon="RiLayoutColumnLine"className="size-4"/></ToolbarIconButton>@@ -1351,8 +1644,12 @@ function DocxEditorToolbar({onPointerDown={preserveTextSelection}onClick={() => editor.toggleList("ordered")}>- <HugeiconsIcon- icon={LeftToRightListNumberIcon}+ <IconPlaceholder+ lucide="ListOrdered"+ tabler="IconListNumbers"+ hugeicons="LeftToRightListNumberIcon"+ phosphor="ListNumbersIcon"+ remixicon="RiListOrdered"className="size-4"/></ToolbarIconButton>@@ -1369,7 +1666,7 @@ function DocxEditorToolbar({disabled={!canEdit}className="h-7 gap-1 px-2 shadow-none">- <HugeiconsIcon icon={borderTriggerIcon} className="size-4" />+ {borderTriggerIcon}{borderTriggerLabel}</Button></DropdownMenuTrigger>@@ -1391,10 +1688,7 @@ function DocxEditorToolbar({}}}>- <HugeiconsIcon- icon={BorderOptionIcon}- className="size-4 text-muted-foreground"- />+ <BorderOptionIcon className="size-4 text-muted-foreground" />{option.label}</DropdownMenuCheckboxItem></React.Fragment>@@ -1411,18 +1705,39 @@ function DocxEditorToolbar({disabled={!canEdit}onClick={onImageUploadClick}>- <HugeiconsIcon icon={ImageAdd01Icon} className="size-4" />+ <IconPlaceholder+ lucide="ImagePlus"+ tabler="IconPhotoPlus"+ hugeicons="ImageAdd01Icon"+ phosphor="ImageIcon"+ remixicon="RiImageAddLine"+ className="size-4"+ /></ToolbarIconButton><ToolbarIconButtonlabel="Insert table"disabled={!canEdit}onClick={editor.insertTable}>- <HugeiconsIcon icon={TableIcon} className="size-4" />+ <IconPlaceholder+ lucide="TableIcon"+ tabler="IconTable"+ hugeicons="TableIcon"+ phosphor="TableIcon"+ remixicon="RiTableLine"+ className="size-4"+ /></ToolbarIconButton><ToolbarTooltip label="Section columns"><div className="flex h-7 shrink-0 items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground">- <HugeiconsIcon icon={ColumnsThreeCogIcon} className="size-4" />+ <IconPlaceholder+ lucide="Columns3Cog"+ tabler="IconColumns3"+ hugeicons="ColumnsThreeCogIcon"+ phosphor="ColumnsIcon"+ remixicon="RiLayoutColumnLine"+ className="size-4"+ />{activeColumns ? `${activeColumns.count} cols` : "1 col"}</div></ToolbarTooltip>@@ -1440,7 +1755,14 @@ function DocxEditorToolbar({)}>- <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />+ <IconPlaceholder+ lucide="CircleMinus"+ tabler="IconCircleMinus"+ hugeicons="MinusSignCircleIcon"+ phosphor="MinusCircleIcon"+ remixicon="RiIndeterminateCircleLine"+ className="size-4"+ /></ToolbarIconButton><Selectvalue={zoomScale.toString()}@@ -1476,7 +1798,14 @@ function DocxEditorToolbar({)}>- <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />+ <IconPlaceholder+ lucide="CirclePlusIcon"+ tabler="IconCirclePlusFilled"+ hugeicons="PlusSignCircleIcon"+ phosphor="PlusCircleIcon"+ remixicon="RiAddCircleFill"+ className="size-4"+ /></ToolbarIconButton></div></div>@@ -1981,7 +2310,14 @@ function DocxEditorContent({className="mt-4"onClick={() => fileInputRef.current?.click()}>- <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-4"+ />Upload DOCX</Button></div>diff --git a/apps/v4/components/extend/docx-viewer.tsx b/apps/v4/components/extend/docx-viewer.tsxindex 81582ab..4d3d977 100644--- a/apps/v4/components/extend/docx-viewer.tsx+++ b/apps/v4/components/extend/docx-viewer.tsx@@ -12,18 +12,6 @@ import {type DocxEditorController,type DocxPageThumbnailItem,} from "@extend-ai/react-docx"-import {- Comment01Icon,- Download01Icon,- FileDiffIcon,- MinusSignCircleIcon,- Moon02Icon,- MoreHorizontalIcon,- PlusSignCircleIcon,- SidebarLeftIcon,- Upload01Icon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { useVirtualizer } from "@tanstack/react-virtual"import { cn } from "@/lib/utils"@@ -63,6 +51,7 @@ import {createDocxTrackedChangeCardRenderer,} from "@/components/extend/docx-annotation-card"import { FileThumbnail } from "@/components/extend/file-thumbnail"+import { IconPlaceholder } from "@/components/icon-placeholder"const DOCX_MIME_TYPE ="application/vnd.openxmlformats-officedocument.wordprocessingml.document"@@ -364,7 +353,14 @@ function DocxFileActionsMenu({size="icon-sm"aria-label="Open DOCX actions">- <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />+ <IconPlaceholder+ lucide="Ellipsis"+ tabler="IconDots"+ hugeicons="MoreHorizontalIcon"+ phosphor="DotsThreeIcon"+ remixicon="RiMoreLine"+ className="size-4"+ /></Button></DropdownMenuTrigger><DropdownMenuContent align="end" className="w-52">@@ -377,7 +373,14 @@ function DocxFileActionsMenu({onCheckedChange={(checked) => onIsDarkChange(checked === true)}><span className="flex min-w-0 items-center gap-2">- <HugeiconsIcon icon={Moon02Icon} className="size-4" />+ <IconPlaceholder+ lucide="Moon"+ tabler="IconMoon"+ hugeicons="Moon02Icon"+ phosphor="MoonIcon"+ remixicon="RiMoonLine"+ className="size-4"+ />Dark mode</span></DropdownMenuCheckboxItem>@@ -391,7 +394,14 @@ function DocxFileActionsMenu({onCheckedChange={(checked) => onShowCommentsChange(checked === true)}><span className="flex min-w-0 items-center gap-2">- <HugeiconsIcon icon={Comment01Icon} className="size-4" />+ <IconPlaceholder+ lucide="MessageSquare"+ tabler="IconMessage"+ hugeicons="Comment01Icon"+ phosphor="ChatIcon"+ remixicon="RiChat1Line"+ className="size-4"+ />Comments</span></DropdownMenuCheckboxItem>@@ -404,7 +414,14 @@ function DocxFileActionsMenu({}><span className="flex min-w-0 items-center gap-2">- <HugeiconsIcon icon={FileDiffIcon} className="size-4" />+ <IconPlaceholder+ lucide="FileDiff"+ tabler="IconFileDiff"+ hugeicons="FileDiffIcon"+ phosphor="GitDiffIcon"+ remixicon="RiFileHistoryLine"+ className="size-4"+ />Edits</span></DropdownMenuCheckboxItem>@@ -414,14 +431,28 @@ function DocxFileActionsMenu({{isPreparingDownload ? (<Spinner className="size-4" />) : (- <HugeiconsIcon icon={Download01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Download"+ tabler="IconDownload"+ hugeicons="Download01Icon"+ phosphor="DownloadSimpleIcon"+ remixicon="RiDownload2Line"+ className="size-4"+ />)}Download</DropdownMenuItem>) : null}{showUploadButton ? (<DropdownMenuItem onClick={onUploadClick}>- <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-4"+ />Upload</DropdownMenuItem>) : null}@@ -580,7 +611,14 @@ function DocxToolbar({disabled={controlsDisabled}onClick={onToggleSidebar}>- <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />+ <IconPlaceholder+ lucide="PanelLeft"+ tabler="IconLayoutSidebar"+ hugeicons="SidebarLeftIcon"+ phosphor="SidebarIcon"+ remixicon="RiLayoutLeftLine"+ className="size-4"+ /></Button></ToolbarTooltip><DocxPageNumberControl@@ -605,7 +643,14 @@ function DocxToolbar({)}>- <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />+ <IconPlaceholder+ lucide="CircleMinus"+ tabler="IconCircleMinus"+ hugeicons="MinusSignCircleIcon"+ phosphor="MinusCircleIcon"+ remixicon="RiIndeterminateCircleLine"+ className="size-4"+ /></Button></ToolbarTooltip><Select@@ -642,7 +687,14 @@ function DocxToolbar({)}>- <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />+ <IconPlaceholder+ lucide="CirclePlusIcon"+ tabler="IconCirclePlusFilled"+ hugeicons="PlusSignCircleIcon"+ phosphor="PlusCircleIcon"+ remixicon="RiAddCircleFill"+ className="size-4"+ /></Button></ToolbarTooltip></div>@@ -1518,7 +1570,14 @@ function DocxViewerContent({className="mt-4"onClick={() => fileInputRef.current?.click()}>- <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-4"+ />Upload Word document</Button></div>diff --git a/apps/v4/components/extend/file-system.tsx b/apps/v4/components/extend/file-system.tsxindex e2238ab..4e1b6fa 100644--- a/apps/v4/components/extend/file-system.tsx+++ b/apps/v4/components/extend/file-system.tsx@@ -1,24 +1,6 @@"use client"import * as React from "react"-import {- ArrowDown01Icon,- ArrowLeft01Icon,- ArrowRight01Icon,- ArrowUp01Icon,- ArrowUpDownIcon,- Calendar03Icon,- Cancel01Icon,- File01Icon,- FilterIcon,- GalleryThumbnailsIcon,- GridViewIcon,- LayoutThreeColumnIcon,- LeftToRightListBulletIcon,- Search01Icon,- Tick02Icon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import {createFileTreeIconResolver,getBuiltInSpriteSheet,@@ -74,6 +56,111 @@ import {import { Spinner } from "@/components/ui/spinner"import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"import { FileThumbnail } from "@/components/extend/file-thumbnail"+import { IconPlaceholder } from "@/components/icon-placeholder"++function ArrowDown01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="ChevronDown"+ tabler="IconChevronDown"+ hugeicons="ArrowDown01Icon"+ phosphor="CaretDownIcon"+ remixicon="RiArrowDownSLine"+ {...props}+ />+ )+}++function ArrowUp01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="ChevronUp"+ tabler="IconChevronUp"+ hugeicons="ArrowUp01Icon"+ phosphor="CaretUpIcon"+ remixicon="RiArrowUpSLine"+ {...props}+ />+ )+}++function Calendar03Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Calendar"+ tabler="IconCalendar"+ hugeicons="Calendar03Icon"+ phosphor="CalendarIcon"+ remixicon="RiCalendarLine"+ {...props}+ />+ )+}++function File01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="FileArchiveIcon"+ tabler="IconFileZip"+ hugeicons="File01Icon"+ phosphor="FileZipIcon"+ remixicon="RiFileZipLine"+ {...props}+ />+ )+}++function GalleryThumbnailsGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="GalleryThumbnails"+ tabler="IconLayoutBottombar"+ hugeicons="GalleryThumbnailsIcon"+ phosphor="ImagesIcon"+ remixicon="RiGalleryView"+ {...props}+ />+ )+}++function GridViewGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="LayoutGrid"+ tabler="IconLayoutGrid"+ hugeicons="GridViewIcon"+ phosphor="SquaresFourIcon"+ remixicon="RiLayoutGridLine"+ {...props}+ />+ )+}++function LayoutThreeColumnGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Columns3"+ tabler="IconColumns3"+ hugeicons="LayoutThreeColumnIcon"+ phosphor="ColumnsIcon"+ remixicon="RiLayoutColumnLine"+ {...props}+ />+ )+}++function LeftToRightListBulletGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Columns3Icon"+ tabler="IconLayoutColumns"+ hugeicons="LeftToRightListBulletIcon"+ phosphor="ColumnsIcon"+ remixicon="RiLayoutColumnLine"+ {...props}+ />+ )+}const LazyPDFViewer = React.lazy(() =>import("@/components/extend/pdf-viewer").then((mod) => ({@@ -1297,7 +1384,14 @@ function FileVisual({onDoubleClick={(event) => event.stopPropagation()}className="flex size-6 items-center justify-center rounded-md bg-background/80 text-foreground shadow-xs backdrop-blur-sm transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40">- <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />+ <IconPlaceholder+ lucide="ChevronLeft"+ tabler="IconChevronLeft"+ hugeicons="ArrowLeft01Icon"+ phosphor="CaretLeftIcon"+ remixicon="RiArrowLeftSLine"+ className="size-3.5"+ /></button><span className="rounded-md bg-background/80 px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground tabular-nums shadow-xs backdrop-blur-sm">{clampedPageIndex + 1}/{totalPages}@@ -1314,7 +1408,14 @@ function FileVisual({onDoubleClick={(event) => event.stopPropagation()}className="flex size-6 items-center justify-center rounded-md bg-background/80 text-foreground shadow-xs backdrop-blur-sm transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40">- <HugeiconsIcon icon={ArrowRight01Icon} className="size-3.5" />+ <IconPlaceholder+ lucide="ArrowRight"+ tabler="IconArrowRight"+ hugeicons="ArrowRight01Icon"+ phosphor="ArrowRightIcon"+ remixicon="RiArrowRightLine"+ className="size-3.5"+ /></button></div></div>@@ -1322,14 +1423,14 @@ function FileVisual({}const VIEW_OPTIONS: Array<{- icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]+ icon: React.ComponentType<React.ComponentProps<"svg">>label: stringvalue: FileSystemView}> = [- { icon: GridViewIcon, label: "Grid", value: "icons" },- { icon: LeftToRightListBulletIcon, label: "List", value: "list" },- { icon: LayoutThreeColumnIcon, label: "Columns", value: "columns" },- { icon: GalleryThumbnailsIcon, label: "Gallery", value: "gallery" },+ { icon: GridViewGlyph, label: "Grid", value: "icons" },+ { icon: LeftToRightListBulletGlyph, label: "List", value: "list" },+ { icon: LayoutThreeColumnGlyph, label: "Columns", value: "columns" },+ { icon: GalleryThumbnailsGlyph, label: "Gallery", value: "gallery" },]export function FileSystem({@@ -2044,7 +2145,14 @@ export function FileSystem({aria-label="Close preview"render={<Button type="button" variant="ghost" size="icon-sm" />}>- <HugeiconsIcon icon={Cancel01Icon} className="size-4" />+ <IconPlaceholder+ lucide="X"+ tabler="IconX"+ hugeicons="Cancel01Icon"+ phosphor="XIcon"+ remixicon="RiCloseLine"+ className="size-4"+ /></DialogClose>)@@ -2077,7 +2185,14 @@ export function FileSystem({onClick={goBack}className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40">- <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4.5" />+ <IconPlaceholder+ lucide="ChevronLeft"+ tabler="IconChevronLeft"+ hugeicons="ArrowLeft01Icon"+ phosphor="CaretLeftIcon"+ remixicon="RiArrowLeftSLine"+ className="size-4.5"+ /></button><buttontype="button"@@ -2087,7 +2202,14 @@ export function FileSystem({onClick={goForward}className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40">- <HugeiconsIcon icon={ArrowRight01Icon} className="size-4.5" />+ <IconPlaceholder+ lucide="ArrowRight"+ tabler="IconArrowRight"+ hugeicons="ArrowRight01Icon"+ phosphor="ArrowRightIcon"+ remixicon="RiArrowRightLine"+ className="size-4.5"+ /></button>{headerLayout !== "minimal" ? (<span className="ml-1.5 truncate text-sm font-semibold">@@ -2109,10 +2231,7 @@ export function FileSystem({><SelectValue>{activeViewOption ? (- <HugeiconsIcon- icon={activeViewOption.icon}- className="size-4"- />+ <activeViewOption.icon className="size-4" />) : null}</SelectValue></SelectTrigger>@@ -2120,7 +2239,7 @@ export function FileSystem({{VIEW_OPTIONS.map((option) => (<SelectItem key={option.value} value={option.value}><span className="flex items-center gap-2">- <HugeiconsIcon icon={option.icon} className="size-4" />+ <option.icon className="size-4" />{option.label}</span></SelectItem>@@ -2142,7 +2261,7 @@ export function FileSystem({title={option.label}className="h-7 grow-0 px-2.5 sm:h-7">- <HugeiconsIcon icon={option.icon} className="size-4" />+ <option.icon className="size-4" /></TabsTrigger>))}</TabsList>@@ -2386,8 +2505,12 @@ function FileSystemSearchField({isInline && "max-w-56")}>- <HugeiconsIcon- icon={Search01Icon}+ <IconPlaceholder+ lucide="Search"+ tabler="IconSearch"+ hugeicons="Search01Icon"+ phosphor="MagnifyingGlassIcon"+ remixicon="RiSearchLine"className="pointer-events-none absolute left-2 size-3.5 text-muted-foreground"/><input@@ -2421,7 +2544,14 @@ function FileSystemSearchField({}}className="absolute right-1 flex size-5 items-center justify-center rounded-sm text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring">- <HugeiconsIcon icon={Cancel01Icon} className="size-3" />+ <IconPlaceholder+ lucide="X"+ tabler="IconX"+ hugeicons="Cancel01Icon"+ phosphor="XIcon"+ remixicon="RiCloseLine"+ className="size-3"+ /></button>) : null}</div>@@ -2446,7 +2576,14 @@ function FileSystemSearchField({/>}>- <HugeiconsIcon icon={Search01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Search"+ tabler="IconSearch"+ hugeicons="Search01Icon"+ phosphor="MagnifyingGlassIcon"+ remixicon="RiSearchLine"+ className="size-4"+ />{value ? (<span className="absolute top-1 right-1 size-1.5 rounded-full bg-primary" />) : null}@@ -2486,7 +2623,14 @@ function FileSystemSortSelect({><SelectValue><span className="flex items-center gap-1.5">- <HugeiconsIcon icon={ArrowUpDownIcon} className="size-4" />+ <IconPlaceholder+ lucide="ArrowUpDown"+ tabler="IconArrowsUpDown"+ hugeicons="ArrowUpDownIcon"+ phosphor="ArrowsDownUpIcon"+ remixicon="RiArrowUpDownLine"+ className="size-4"+ />{layout === "full" && showLabel ? activeOption?.triggerLabel : null}</span></SelectValue>@@ -2564,8 +2708,12 @@ function FileSystemFileTypeCommand({keywords={[option.mime]}onSelect={() => onToggle(option.mime, !isChecked)}>- <HugeiconsIcon- icon={Tick02Icon}+ <IconPlaceholder+ lucide="Check"+ tabler="IconCheck"+ hugeicons="Tick02Icon"+ phosphor="CheckIcon"+ remixicon="RiCheckLine"className={cn("size-4 text-foreground",!isChecked && "opacity-0"@@ -2620,7 +2768,14 @@ function FileSystemFilterMenu({/>}>- <HugeiconsIcon icon={FilterIcon} className="size-4" />+ <IconPlaceholder+ lucide="Filter"+ tabler="IconFilter"+ hugeicons="FilterIcon"+ phosphor="FunnelIcon"+ remixicon="RiFilterLine"+ className="size-4"+ />{filters.length > 0 ? (<span className="absolute top-1 right-1 size-1.5 rounded-full bg-primary" />) : null}@@ -2628,8 +2783,12 @@ function FileSystemFilterMenu({<DropdownMenuContent align="end" className="min-w-44"><DropdownMenuSub><DropdownMenuSubTrigger>- <HugeiconsIcon- icon={File01Icon}+ <IconPlaceholder+ lucide="FileArchiveIcon"+ tabler="IconFileZip"+ hugeicons="File01Icon"+ phosphor="FileZipIcon"+ remixicon="RiFileZipLine"className="size-4 text-muted-foreground"/>File type@@ -2645,8 +2804,12 @@ function FileSystemFilterMenu({{(["dateModified", "dateCreated"] as const).map((type) => (<DropdownMenuSub key={type}><DropdownMenuSubTrigger>- <HugeiconsIcon- icon={Calendar03Icon}+ <IconPlaceholder+ lucide="Calendar"+ tabler="IconCalendar"+ hugeicons="Calendar03Icon"+ phosphor="CalendarIcon"+ remixicon="RiCalendarLine"className="size-4 text-muted-foreground"/>{FILTER_TYPE_LABELS[type]}@@ -2720,10 +2883,11 @@ function FileSystemFilterPill({"rounded-l-md border-l text-primary")}>- <HugeiconsIcon- icon={filter.type === "fileType" ? File01Icon : Calendar03Icon}- className="size-3"- />+ {filter.type === "fileType" ? (+ <File01Glyph className="size-3" />+ ) : (+ <Calendar03Glyph className="size-3" />+ )}{FILTER_TYPE_LABELS[filter.type]}</span><DropdownMenu>@@ -2816,7 +2980,14 @@ function FileSystemFilterPill({"rounded-r-md px-1 text-muted-foreground hover:text-foreground")}>- <HugeiconsIcon icon={Cancel01Icon} className="size-3" />+ <IconPlaceholder+ lucide="X"+ tabler="IconX"+ hugeicons="Cancel01Icon"+ phosphor="XIcon"+ remixicon="RiCloseLine"+ className="size-3"+ /></button></div>)@@ -2943,7 +3114,14 @@ function FileSystemRangeCalendar({}className="absolute top-0 left-0 flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring">- <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />+ <IconPlaceholder+ lucide="ChevronLeft"+ tabler="IconChevronLeft"+ hugeicons="ArrowLeft01Icon"+ phosphor="CaretLeftIcon"+ remixicon="RiArrowLeftSLine"+ className="size-4"+ /></button><buttontype="button"@@ -2956,7 +3134,14 @@ function FileSystemRangeCalendar({}className="absolute top-0 right-0 flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring">- <HugeiconsIcon icon={ArrowRight01Icon} className="size-4" />+ <IconPlaceholder+ lucide="ArrowRight"+ tabler="IconArrowRight"+ hugeicons="ArrowRight01Icon"+ phosphor="ArrowRightIcon"+ remixicon="RiArrowRightLine"+ className="size-4"+ /></button><div className="grid grid-cols-1 gap-4 sm:grid-cols-2">{months.map((month, monthIndex) => {@@ -3076,8 +3261,12 @@ function FileSystemDateRangeDialog({<div className="flex flex-1 flex-col gap-1.5"><span className="text-xs font-medium">{label}</span><div className="relative flex items-center">- <HugeiconsIcon- icon={Calendar03Icon}+ <IconPlaceholder+ lucide="Calendar"+ tabler="IconCalendar"+ hugeicons="Calendar03Icon"+ phosphor="CalendarIcon"+ remixicon="RiCalendarLine"className="pointer-events-none absolute left-2.5 size-3.5 text-muted-foreground"/><Input@@ -3687,10 +3876,11 @@ function FileSystemListColumnHeader({>{label}{isActive ? (- <HugeiconsIcon- icon={sort.direction === "asc" ? ArrowUp01Icon : ArrowDown01Icon}- className="size-3 shrink-0"- />+ sort.direction === "asc" ? (+ <ArrowUp01Glyph className="size-3 shrink-0" />+ ) : (+ <ArrowDown01Glyph className="size-3 shrink-0" />+ )) : null}</button>)@@ -4696,8 +4886,12 @@ const FileSystemColumn = React.memo(function FileSystemColumn({<span className="min-w-0 flex-1 truncate">{entry.name}</span>{entry.kind === "folder" &&folderHasChildren(index, entry) ? (- <HugeiconsIcon- icon={ArrowRight01Icon}+ <IconPlaceholder+ lucide="ArrowRight"+ tabler="IconArrowRight"+ hugeicons="ArrowRight01Icon"+ phosphor="ArrowRightIcon"+ remixicon="RiArrowRightLine"className={cn("size-3.5 shrink-0",!isSelected && "text-muted-foreground/60"diff --git a/apps/v4/components/extend/file-upload.tsx b/apps/v4/components/extend/file-upload.tsxindex 4aa2265..8d5688e 100644--- a/apps/v4/components/extend/file-upload.tsx+++ b/apps/v4/components/extend/file-upload.tsx@@ -1,18 +1,51 @@"use client"import * as React from "react"-import {- FileImageIcon,- FileSpreadsheetIcon,- FileUploadIcon,- Upload01Icon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { BorderBeam } from "border-beam"import { cn } from "@/lib/utils"import { Card } from "@/components/ui/card"import { FileThumbnail } from "@/components/extend/file-thumbnail"+import { IconPlaceholder } from "@/components/icon-placeholder"++function FileImageGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="FileImage"+ tabler="IconPhoto"+ hugeicons="FileImageIcon"+ phosphor="FileImageIcon"+ remixicon="RiFileImageLine"+ {...props}+ />+ )+}++function FileSpreadsheetGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="FileSpreadsheet"+ tabler="IconFileSpreadsheet"+ hugeicons="FileSpreadsheetIcon"+ phosphor="FileXlsIcon"+ remixicon="RiFileExcel2Line"+ {...props}+ />+ )+}++function FileUploadGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="FileUp"+ tabler="IconFileUpload"+ hugeicons="FileUploadIcon"+ phosphor="FileArrowUpIcon"+ remixicon="RiFileUploadLine"+ {...props}+ />+ )+}type FileUploadItem = {id: string@@ -24,7 +57,7 @@ type FileUploadItem = {type AcceptedFileType = {label: string- icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]+ icon: React.ComponentType<React.ComponentProps<"svg">>}type FileUploadProps = {@@ -44,9 +77,9 @@ type FileUploadProps = {}const ACCEPTED_FILE_TYPES: AcceptedFileType[] = [- { label: "Image", icon: FileImageIcon },- { label: "PDF", icon: FileUploadIcon },- { label: "Sheet", icon: FileSpreadsheetIcon },+ { label: "Image", icon: FileImageGlyph },+ { label: "PDF", icon: FileUploadGlyph },+ { label: "Sheet", icon: FileSpreadsheetGlyph },]const DEFAULT_ACCEPT = [".pdf",@@ -149,7 +182,7 @@ function UploadIconCluster({: ICON_TRANSFORMS[index]?.idle,}}>- <HugeiconsIcon icon={item.icon} className="size-5" />+ <item.icon className="size-5" /></Card>))}</div>@@ -263,7 +296,14 @@ export function FileUpload({) : null}</div><div className="inline-flex items-center gap-2 rounded-full border bg-background px-3 py-1 text-xs text-muted-foreground">- <HugeiconsIcon icon={Upload01Icon} className="size-3.5" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-3.5"+ /><span>{isDragging ? draggingLabel : browseLabel}</span></div><inputdiff --git a/apps/v4/components/extend/layout-blocks.tsx b/apps/v4/components/extend/layout-blocks.tsxindex 37adf5a..a1fbbbe 100644--- a/apps/v4/components/extend/layout-blocks.tsx+++ b/apps/v4/components/extend/layout-blocks.tsx@@ -1,17 +1,6 @@"use client"import * as React from "react"-import {- AlignBoxBottomCenterIcon,- Heading01Icon,- ImageCompositionIcon,- LeftToRightListBulletIcon,- ParagraphIcon,- Table01Icon,- TextCenterlineCenterTopIcon,- TextNumberSignIcon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { useVirtualizer } from "@tanstack/react-virtual"import ReactMarkdown from "react-markdown"import rehypeRaw from "rehype-raw"@@ -20,6 +9,111 @@ import remarkGfm from "remark-gfm"import { cn } from "@/lib/utils"import { ScrollArea } from "@/components/ui/scroll-area"+import { IconPlaceholder } from "@/components/icon-placeholder"++function AlignBoxBottomCenterGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="AlignVerticalJustifyEnd"+ tabler="IconAlignBoxBottomCenter"+ hugeicons="AlignBoxBottomCenterIcon"+ phosphor="AlignBottomIcon"+ remixicon="RiAlignBottom"+ {...props}+ />+ )+}++function Heading01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Heading1"+ tabler="IconH1"+ hugeicons="Heading01Icon"+ phosphor="TextHOneIcon"+ remixicon="RiH1"+ {...props}+ />+ )+}++function ImageCompositionGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Image"+ tabler="IconPhoto"+ hugeicons="ImageCompositionIcon"+ phosphor="ImageSquareIcon"+ remixicon="RiImageLine"+ {...props}+ />+ )+}++function LeftToRightListBulletGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Columns3Icon"+ tabler="IconLayoutColumns"+ hugeicons="LeftToRightListBulletIcon"+ phosphor="ColumnsIcon"+ remixicon="RiLayoutColumnLine"+ {...props}+ />+ )+}++function ParagraphGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Pilcrow"+ tabler="IconPilcrow"+ hugeicons="ParagraphIcon"+ phosphor="ParagraphIcon"+ remixicon="RiParagraph"+ {...props}+ />+ )+}++function Table01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Table"+ tabler="IconTable"+ hugeicons="Table01Icon"+ phosphor="TableIcon"+ remixicon="RiTableLine"+ {...props}+ />+ )+}++function TextCenterlineCenterTopGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="PanelTop"+ tabler="IconLayoutNavbar"+ hugeicons="TextCenterlineCenterTopIcon"+ phosphor="AlignTopSimpleIcon"+ remixicon="RiLayoutTopLine"+ {...props}+ />+ )+}++function TextNumberSignGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Hash"+ tabler="IconHash"+ hugeicons="TextNumberSignIcon"+ phosphor="HashIcon"+ remixicon="RiHashtag"+ {...props}+ />+ )+}export type Point = {x: number@@ -7947,7 +8041,7 @@ const BLOCK_STYLES: Record<OcrBlockType,{label: string- icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]+ icon: React.ComponentType<React.ComponentProps<"svg">>overlay: stringmutedOverlay: stringring: string@@ -7956,7 +8050,7 @@ const BLOCK_STYLES: Record<> = {heading: {label: "Heading",- icon: Heading01Icon,+ icon: Heading01Glyph,overlay: "border-violet-500/70 bg-violet-500/10",mutedOverlay: "border-violet-500/35 bg-violet-500/5",ring: "border-violet-500/60 bg-violet-500/5 text-violet-600",@@ -7965,7 +8059,7 @@ const BLOCK_STYLES: Record<},paragraph: {label: "Paragraph",- icon: ParagraphIcon,+ icon: ParagraphGlyph,overlay: "border-blue-500/70 bg-blue-500/10",mutedOverlay: "border-blue-500/35 bg-blue-500/5",ring: "border-blue-500/60 bg-blue-500/5 text-blue-600",@@ -7973,7 +8067,7 @@ const BLOCK_STYLES: Record<},list: {label: "List",- icon: LeftToRightListBulletIcon,+ icon: LeftToRightListBulletGlyph,overlay: "border-emerald-500/70 bg-emerald-500/10",mutedOverlay: "border-emerald-500/35 bg-emerald-500/5",ring: "border-emerald-500/60 bg-emerald-500/5 text-emerald-600",@@ -7982,7 +8076,7 @@ const BLOCK_STYLES: Record<},table: {label: "Table",- icon: Table01Icon,+ icon: Table01Glyph,overlay: "border-amber-500/70 bg-amber-500/10",mutedOverlay: "border-amber-500/35 bg-amber-500/5",ring: "border-amber-500/60 bg-amber-500/5 text-amber-700",@@ -7991,7 +8085,7 @@ const BLOCK_STYLES: Record<},figure: {label: "Figure",- icon: ImageCompositionIcon,+ icon: ImageCompositionGlyph,overlay: "border-rose-500/70 bg-rose-500/10",mutedOverlay: "border-rose-500/35 bg-rose-500/5",ring: "border-rose-500/60 bg-rose-500/5 text-rose-600",@@ -7999,7 +8093,7 @@ const BLOCK_STYLES: Record<},header: {label: "Header",- icon: TextCenterlineCenterTopIcon,+ icon: TextCenterlineCenterTopGlyph,overlay: "border-cyan-500/70 bg-cyan-500/10",mutedOverlay: "border-cyan-500/35 bg-cyan-500/5",ring: "border-cyan-500/60 bg-cyan-500/5 text-cyan-700",@@ -8007,7 +8101,7 @@ const BLOCK_STYLES: Record<},footer: {label: "Footer",- icon: AlignBoxBottomCenterIcon,+ icon: AlignBoxBottomCenterGlyph,overlay: "border-slate-500/70 bg-slate-500/10",mutedOverlay: "border-slate-500/35 bg-slate-500/5",ring: "border-slate-500/60 bg-slate-500/5 text-slate-700",@@ -8016,7 +8110,7 @@ const BLOCK_STYLES: Record<},page_number: {label: "Page number",- icon: TextNumberSignIcon,+ icon: TextNumberSignGlyph,overlay: "border-zinc-500/70 bg-zinc-500/10",mutedOverlay: "border-zinc-500/35 bg-zinc-500/5",ring: "border-zinc-500/60 bg-zinc-500/5 text-zinc-700",@@ -8270,7 +8364,7 @@ const OcrBlockButton = React.memo(function OcrBlockButton({style.badge)}>- <HugeiconsIcon icon={style.icon} className="size-3.5" />+ <style.icon className="size-3.5" />{style.label}</div><div className="truncate text-xs text-muted-foreground">diff --git a/apps/v4/components/extend/pdf-viewer.tsx b/apps/v4/components/extend/pdf-viewer.tsxindex 1b8c2f2..2ed5aa6 100644--- a/apps/v4/components/extend/pdf-viewer.tsx+++ b/apps/v4/components/extend/pdf-viewer.tsx@@ -58,19 +58,6 @@ import {ViewportPluginPackage,} from "@embedpdf/plugin-viewport/react"import { useZoom, ZoomPluginPackage } from "@embedpdf/plugin-zoom/react"-import {- ArrowLeft01Icon,- ArrowRight01Icon,- Download01Icon,- MinusSignCircleIcon,- MoreHorizontalIcon,- PlusSignCircleIcon,- RotateClockwiseIcon,- Search01Icon,- SidebarLeftIcon,- Upload01Icon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { flushSync } from "react-dom"import { loadSharedPdfEngine } from "@/lib/pdf-thumbnail-utils"@@ -110,6 +97,7 @@ import {useElementWidth,useInlineThumbnailSidebar,} from "@/components/extend/document-viewer-sidebar"+import { IconPlaceholder } from "@/components/icon-placeholder"export type PDFViewerPageOverlayProps = {pageNumber: number@@ -530,7 +518,14 @@ function PDFViewerFallbackShell({aria-label="Search text"disabled>- <HugeiconsIcon icon={Search01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Search"+ tabler="IconSearch"+ hugeicons="Search01Icon"+ phosphor="MagnifyingGlassIcon"+ remixicon="RiSearchLine"+ className="size-4"+ /></Button></ToolbarTooltip>}@@ -635,7 +630,14 @@ function PDFViewerFileActionsMenu({size="icon-sm"aria-label="Open PDF actions">- <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />+ <IconPlaceholder+ lucide="Ellipsis"+ tabler="IconDots"+ hugeicons="MoreHorizontalIcon"+ phosphor="DotsThreeIcon"+ remixicon="RiMoreLine"+ className="size-4"+ /></Button></DropdownMenuTrigger><DropdownMenuContent align="end" className="w-40">@@ -644,14 +646,28 @@ function PDFViewerFileActionsMenu({{isPreparingDownload ? (<Spinner className="size-4" />) : (- <HugeiconsIcon icon={Download01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Download"+ tabler="IconDownload"+ hugeicons="Download01Icon"+ phosphor="DownloadSimpleIcon"+ remixicon="RiDownload2Line"+ className="size-4"+ />)}Download</DropdownMenuItem>) : null}{showUpload && onUploadFile ? (<DropdownMenuItem onClick={() => inputRef.current?.click()}>- <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-4"+ />Upload</DropdownMenuItem>) : null}@@ -914,7 +930,14 @@ function PDFViewerSearchControl({aria-label="Search text"disabled={controlsDisabled}>- <HugeiconsIcon icon={Search01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Search"+ tabler="IconSearch"+ hugeicons="Search01Icon"+ phosphor="MagnifyingGlassIcon"+ remixicon="RiSearchLine"+ className="size-4"+ /></Button></PopoverTrigger></ToolbarTooltip>@@ -961,7 +984,14 @@ function PDFViewerSearchControl({disabled={isSearching || state.total === 0}onClick={() => navigate(-1)}>- <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />+ <IconPlaceholder+ lucide="ChevronLeft"+ tabler="IconChevronLeft"+ hugeicons="ArrowLeft01Icon"+ phosphor="CaretLeftIcon"+ remixicon="RiArrowLeftSLine"+ className="size-4"+ /></Button><Buttontype="button"@@ -971,7 +1001,14 @@ function PDFViewerSearchControl({disabled={isSearching || state.total === 0}onClick={() => navigate(1)}>- <HugeiconsIcon icon={ArrowRight01Icon} className="size-4" />+ <IconPlaceholder+ lucide="ArrowRight"+ tabler="IconArrowRight"+ hugeicons="ArrowRight01Icon"+ phosphor="ArrowRightIcon"+ remixicon="RiArrowRightLine"+ className="size-4"+ /></Button></div></div>@@ -1041,7 +1078,14 @@ function PDFViewerToolbar({disabled={controlsDisabled}onClick={onToggleSidebar}>- <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />+ <IconPlaceholder+ lucide="PanelLeft"+ tabler="IconLayoutSidebar"+ hugeicons="SidebarLeftIcon"+ phosphor="SidebarIcon"+ remixicon="RiLayoutLeftLine"+ className="size-4"+ /></Button></ToolbarTooltip></TooltipProvider>@@ -1066,8 +1110,12 @@ function PDFViewerToolbar({disabled={controlsDisabled}onClick={() => onRotate(-1)}>- <HugeiconsIcon- icon={RotateClockwiseIcon}+ <IconPlaceholder+ lucide="RotateCw"+ tabler="IconRotateClockwise"+ hugeicons="RotateClockwiseIcon"+ phosphor="ArrowClockwiseIcon"+ remixicon="RiClockwiseLine"className="size-4"/></Button>@@ -1081,8 +1129,12 @@ function PDFViewerToolbar({disabled={controlsDisabled}onClick={() => onRotate(1)}>- <HugeiconsIcon- icon={RotateClockwiseIcon}+ <IconPlaceholder+ lucide="RotateCw"+ tabler="IconRotateClockwise"+ hugeicons="RotateClockwiseIcon"+ phosphor="ArrowClockwiseIcon"+ remixicon="RiClockwiseLine"className="size-4 -scale-x-100"/></Button>@@ -1112,7 +1164,14 @@ function PDFViewerToolbar({onZoomChange(nextZoom ?? ZOOM_OPTIONS[0])}}>- <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />+ <IconPlaceholder+ lucide="CircleMinus"+ tabler="IconCircleMinus"+ hugeicons="MinusSignCircleIcon"+ phosphor="MinusCircleIcon"+ remixicon="RiIndeterminateCircleLine"+ className="size-4"+ /></Button></ToolbarTooltip><Select@@ -1154,7 +1213,14 @@ function PDFViewerToolbar({)}}>- <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />+ <IconPlaceholder+ lucide="CirclePlusIcon"+ tabler="IconCirclePlusFilled"+ hugeicons="PlusSignCircleIcon"+ phosphor="PlusCircleIcon"+ remixicon="RiAddCircleFill"+ className="size-4"+ /></Button></ToolbarTooltip></div>diff --git a/apps/v4/components/extend/pptx-viewer.tsx b/apps/v4/components/extend/pptx-viewer.tsxindex a5760df..6f93003 100644--- a/apps/v4/components/extend/pptx-viewer.tsx+++ b/apps/v4/components/extend/pptx-viewer.tsx@@ -14,17 +14,6 @@ import {import "@extend-ai/react-pptx/styles.css"-import {- ArrowLeft01Icon,- ArrowRight01Icon,- Download01Icon,- MinusSignCircleIcon,- MoreHorizontalIcon,- PlusSignCircleIcon,- SidebarLeftIcon,- Upload01Icon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { useVirtualizer } from "@tanstack/react-virtual"import { cn } from "@/lib/utils"@@ -58,6 +47,7 @@ import {useInlineThumbnailSidebar,} from "@/components/extend/document-viewer-sidebar"import { FileThumbnail } from "@/components/extend/file-thumbnail"+import { IconPlaceholder } from "@/components/icon-placeholder"const PPTX_MIME_TYPE ="application/vnd.openxmlformats-officedocument.presentationml.presentation"@@ -248,7 +238,14 @@ function PptxFileActionsMenu({size="icon-sm"aria-label="Open PowerPoint actions">- <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />+ <IconPlaceholder+ lucide="Ellipsis"+ tabler="IconDots"+ hugeicons="MoreHorizontalIcon"+ phosphor="DotsThreeIcon"+ remixicon="RiMoreLine"+ className="size-4"+ /></Button></DropdownMenuTrigger><DropdownMenuContent align="end" className="w-44">@@ -257,14 +254,28 @@ function PptxFileActionsMenu({{isPreparingDownload ? (<Spinner className="size-4" />) : (- <HugeiconsIcon icon={Download01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Download"+ tabler="IconDownload"+ hugeicons="Download01Icon"+ phosphor="DownloadSimpleIcon"+ remixicon="RiDownload2Line"+ className="size-4"+ />)}Download</DropdownMenuItem>) : null}{showUploadButton ? (<DropdownMenuItem disabled={controlsDisabled} onClick={onUploadClick}>- <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-4"+ />Upload</DropdownMenuItem>) : null}@@ -407,7 +418,14 @@ function PptxToolbar({disabled={controlsDisabled}onClick={onToggleSidebar}>- <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />+ <IconPlaceholder+ lucide="PanelLeft"+ tabler="IconLayoutSidebar"+ hugeicons="SidebarLeftIcon"+ phosphor="SidebarIcon"+ remixicon="RiLayoutLeftLine"+ className="size-4"+ /></Button></ToolbarTooltip><Separator orientation="vertical" className="mx-1 h-4 self-center" />@@ -420,7 +438,14 @@ function PptxToolbar({disabled={!canGoPrevious}onClick={() => onSlideChange(activeSlideIndex - 1)}>- <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />+ <IconPlaceholder+ lucide="ChevronLeft"+ tabler="IconChevronLeft"+ hugeicons="ArrowLeft01Icon"+ phosphor="CaretLeftIcon"+ remixicon="RiArrowLeftSLine"+ className="size-4"+ /></Button></ToolbarTooltip><PptxSlideNumberControl@@ -438,7 +463,14 @@ function PptxToolbar({disabled={!canGoNext}onClick={() => onSlideChange(activeSlideIndex + 1)}>- <HugeiconsIcon icon={ArrowRight01Icon} className="size-4" />+ <IconPlaceholder+ lucide="ArrowRight"+ tabler="IconArrowRight"+ hugeicons="ArrowRight01Icon"+ phosphor="ArrowRightIcon"+ remixicon="RiArrowRightLine"+ className="size-4"+ /></Button></ToolbarTooltip></div>@@ -455,7 +487,14 @@ function PptxToolbar({setZoom((currentZoom) => getNextZoom(currentZoom, -1))}>- <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />+ <IconPlaceholder+ lucide="CircleMinus"+ tabler="IconCircleMinus"+ hugeicons="MinusSignCircleIcon"+ phosphor="MinusCircleIcon"+ remixicon="RiIndeterminateCircleLine"+ className="size-4"+ /></Button></ToolbarTooltip><Select@@ -490,7 +529,14 @@ function PptxToolbar({setZoom((currentZoom) => getNextZoom(currentZoom, 1))}>- <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />+ <IconPlaceholder+ lucide="CirclePlusIcon"+ tabler="IconCirclePlusFilled"+ hugeicons="PlusSignCircleIcon"+ phosphor="PlusCircleIcon"+ remixicon="RiAddCircleFill"+ className="size-4"+ /></Button></ToolbarTooltip></div>@@ -1254,7 +1300,14 @@ export function PptxViewerPreview({className="mt-4"onClick={() => fileInputRef.current?.click()}>- <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-4"+ />Upload PowerPoint</Button></div>diff --git a/apps/v4/components/extend/schema-builder.tsx b/apps/v4/components/extend/schema-builder.tsxindex e5805ad..ca65978 100644--- a/apps/v4/components/extend/schema-builder.tsx+++ b/apps/v4/components/extend/schema-builder.tsx@@ -28,20 +28,6 @@ import {verticalListSortingStrategy,} from "@dnd-kit/sortable"import { CSS } from "@dnd-kit/utilities"-import {- Add01Icon,- CancelCircleIcon,- ChevronDown,- DragDropVerticalIcon,- InputNumericIcon,- InputTextIcon,- LeftToRightListBulletIcon,- SecondBracketIcon,- SourceCodeSquareIcon,- TableIcon,- TextCheckIcon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { Virtualizer as DiffsVirtualizer } from "@pierre/diffs"import {File,@@ -74,6 +60,98 @@ import {} from "@/components/ui/dropdown-menu"import { ScrollArea } from "@/components/ui/scroll-area"import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"+import { IconPlaceholder } from "@/components/icon-placeholder"++function CancelCircleGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="CircleX"+ tabler="IconCircleX"+ hugeicons="CancelCircleIcon"+ phosphor="XCircleIcon"+ remixicon="RiCloseCircleLine"+ {...props}+ />+ )+}++function InputNumericGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Hash"+ tabler="IconNumber123"+ hugeicons="InputNumericIcon"+ phosphor="NumpadIcon"+ remixicon="RiHashtag"+ {...props}+ />+ )+}++function InputTextGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="TextCursorInput"+ tabler="IconForms"+ hugeicons="InputTextIcon"+ phosphor="TextboxIcon"+ remixicon="RiInputField"+ {...props}+ />+ )+}++function LeftToRightListBulletGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Columns3Icon"+ tabler="IconLayoutColumns"+ hugeicons="LeftToRightListBulletIcon"+ phosphor="ColumnsIcon"+ remixicon="RiLayoutColumnLine"+ {...props}+ />+ )+}++function SecondBracketGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Brackets"+ tabler="IconBrackets"+ hugeicons="SecondBracketIcon"+ phosphor="BracketsSquareIcon"+ remixicon="RiBracketsLine"+ {...props}+ />+ )+}++function SourceCodeSquareGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="SquareCode"+ tabler="IconSourceCode"+ hugeicons="SourceCodeSquareIcon"+ phosphor="CodeIcon"+ remixicon="RiCodeBlock"+ {...props}+ />+ )+}++function TextCheckGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="CaptionsIcon"+ tabler="IconTextCaption"+ hugeicons="TextCheckIcon"+ phosphor="TextTIcon"+ remixicon="RiTextWrap"+ {...props}+ />+ )+}export type SchemaBuilderScalarType =| "string"@@ -245,69 +323,69 @@ type SchemaBuilderTypeStyleKey =const TYPE_STYLES: Record<SchemaBuilderTypeStyleKey,{- icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]+ icon: React.ComponentType<React.ComponentProps<"svg">>badge: string}> = {string: {- icon: InputTextIcon,+ icon: InputTextGlyph,badge: "bg-blue-50 text-blue-600 dark:bg-blue-300/10 dark:text-blue-300",},number: {- icon: InputNumericIcon,+ icon: InputNumericGlyph,badge:"bg-emerald-50 text-emerald-600 dark:bg-emerald-300/10 dark:text-emerald-300",},integer: {- icon: InputNumericIcon,+ icon: InputNumericGlyph,badge: "bg-teal-50 text-teal-600 dark:bg-teal-300/10 dark:text-teal-300",},boolean: {- icon: TextCheckIcon,+ icon: TextCheckGlyph,badge:"bg-amber-50 text-amber-600 dark:bg-amber-300/10 dark:text-amber-300",},null: {- icon: CancelCircleIcon,+ icon: CancelCircleGlyph,badge: "bg-zinc-50 text-zinc-600 dark:bg-zinc-300/10 dark:text-zinc-300",},object: {- icon: SourceCodeSquareIcon,+ icon: SourceCodeSquareGlyph,badge:"bg-violet-50 text-violet-600 dark:bg-violet-300/10 dark:text-violet-300",},array: {- icon: SecondBracketIcon,+ icon: SecondBracketGlyph,badge: "bg-cyan-50 text-cyan-600 dark:bg-cyan-300/10 dark:text-cyan-300",},enum: {- icon: LeftToRightListBulletIcon,+ icon: LeftToRightListBulletGlyph,badge: "bg-rose-50 text-rose-600 dark:bg-rose-300/10 dark:text-rose-300",},"array-string": {- icon: SecondBracketIcon,+ icon: SecondBracketGlyph,badge: "bg-blue-50 text-blue-600 dark:bg-blue-300/10 dark:text-blue-300",},"array-number": {- icon: SecondBracketIcon,+ icon: SecondBracketGlyph,badge:"bg-emerald-50 text-emerald-600 dark:bg-emerald-300/10 dark:text-emerald-300",},"array-integer": {- icon: SecondBracketIcon,+ icon: SecondBracketGlyph,badge: "bg-teal-50 text-teal-600 dark:bg-teal-300/10 dark:text-teal-300",},"array-boolean": {- icon: SecondBracketIcon,+ icon: SecondBracketGlyph,badge:"bg-amber-50 text-amber-600 dark:bg-amber-300/10 dark:text-amber-300",},"array-enum": {- icon: LeftToRightListBulletIcon,+ icon: LeftToRightListBulletGlyph,badge: "bg-rose-50 text-rose-600 dark:bg-rose-300/10 dark:text-rose-300",},"array-object": {- icon: SecondBracketIcon,+ icon: SecondBracketGlyph,badge:"bg-violet-50 text-violet-600 dark:bg-violet-300/10 dark:text-violet-300",},@@ -1166,7 +1244,7 @@ function SchemaTypeBadge({className)}>- <HugeiconsIcon icon={style.icon} className="size-3.5" />+ <style.icon className="size-3.5" /><span className="truncate">{TYPE_LABELS[type]}</span></span>)@@ -1462,7 +1540,14 @@ function EnumEditor({className="flex h-9 w-full items-center justify-center gap-2 text-sm text-muted-foreground transition-colors outline-none hover:bg-muted/55 hover:text-foreground focus-visible:bg-muted/55 focus-visible:text-foreground"onClick={() => onChange([...values, createEnumValue()])}>- <HugeiconsIcon icon={Add01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Plus"+ tabler="IconPlus"+ hugeicons="Add01Icon"+ phosphor="PlusIcon"+ remixicon="RiAddLine"+ className="size-4"+ />Add enum value</button></td>@@ -1522,7 +1607,14 @@ const SortableEnumRow = React.memo(function SortableEnumRow({{...attributes}{...listeners}>- <HugeiconsIcon icon={DragDropVerticalIcon} className="size-3.5" />+ <IconPlaceholder+ lucide="GripVertical"+ tabler="IconGripVertical"+ hugeicons="DragDropVerticalIcon"+ phosphor="DotsSixVerticalIcon"+ remixicon="RiDraggable"+ className="size-3.5"+ /></button><div className="min-w-0"><InlineTextInput@@ -1756,7 +1848,14 @@ function SchemaBuilderTable({className="flex h-9 w-full items-center justify-center gap-2 text-sm text-muted-foreground transition-colors outline-none hover:bg-muted/55 hover:text-foreground focus-visible:bg-muted/55 focus-visible:text-foreground"onClick={addProperty}>- <HugeiconsIcon icon={Add01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Plus"+ tabler="IconPlus"+ hugeicons="Add01Icon"+ phosphor="PlusIcon"+ remixicon="RiAddLine"+ className="size-4"+ />Add property</button></td>@@ -1833,7 +1932,14 @@ const SortablePropertyRows = React.memo(function SortablePropertyRows({{...attributes}{...listeners}>- <HugeiconsIcon icon={DragDropVerticalIcon} className="size-3.5" />+ <IconPlaceholder+ lucide="GripVertical"+ tabler="IconGripVertical"+ hugeicons="DragDropVerticalIcon"+ phosphor="DotsSixVerticalIcon"+ remixicon="RiDraggable"+ className="size-3.5"+ /></button><div className="min-w-0"><InlineTextInput@@ -1880,8 +1986,12 @@ const SortablePropertyRows = React.memo(function SortablePropertyRows({className="flex h-full min-w-0 flex-1 items-center gap-2 px-3 text-left text-xs font-medium text-muted-foreground transition-colors outline-none group-hover/collapsible-trigger-row:text-foreground focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"type="button">- <HugeiconsIcon- icon={ChevronDown}+ <IconPlaceholder+ lucide="ChevronDown"+ tabler="IconChevronDown"+ hugeicons="ChevronDown"+ phosphor="CaretDownIcon"+ remixicon="RiArrowDownSLine"className={cn("size-3.5 shrink-0 transition-transform duration-200",!isNestedEditorOpen && "-rotate-90"@@ -1985,8 +2095,12 @@ function SchemaPropertyDragOverlay({{hasNestedEditor ? (<div className="border-t bg-muted/20"><div className="flex h-8 items-center gap-2 px-3 text-xs font-medium text-muted-foreground">- <HugeiconsIcon- icon={ChevronDown}+ <IconPlaceholder+ lucide="ChevronDown"+ tabler="IconChevronDown"+ hugeicons="ChevronDown"+ phosphor="CaretDownIcon"+ remixicon="RiArrowDownSLine"className={cn("size-3.5 shrink-0",!isNestedEditorOpen && "-rotate-90"@@ -2127,8 +2241,12 @@ function SchemaPropertiesPreview({{hasNestedEditor ? (<div className="border-t bg-muted/20"><div className="flex h-7 items-center gap-2 px-3 text-xs font-medium text-muted-foreground">- <HugeiconsIcon- icon={ChevronDown}+ <IconPlaceholder+ lucide="ChevronDown"+ tabler="IconChevronDown"+ hugeicons="ChevronDown"+ phosphor="CaretDownIcon"+ remixicon="RiArrowDownSLine"className={cn("size-3.5 shrink-0",!isNestedEditorOpen && "-rotate-90"@@ -2506,11 +2624,25 @@ export function SchemaBuilderPanel({<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={TableIcon} className="size-4" />+ <IconPlaceholder+ lucide="TableIcon"+ tabler="IconTable"+ hugeicons="TableIcon"+ phosphor="TableIcon"+ remixicon="RiTableLine"+ className="size-4"+ />Form</TabsTrigger><TabsTrigger value="json" className="h-7 sm:h-6">- <HugeiconsIcon icon={SourceCodeSquareIcon} className="size-4" />+ <IconPlaceholder+ lucide="SquareCode"+ tabler="IconSourceCode"+ hugeicons="SourceCodeSquareIcon"+ phosphor="CodeIcon"+ remixicon="RiCodeBlock"+ className="size-4"+ />JSON</TabsTrigger></TabsList>diff --git a/apps/v4/components/extend/xlsx-editor.tsx b/apps/v4/components/extend/xlsx-editor.tsxindex 99ccd26..d66d963 100644--- a/apps/v4/components/extend/xlsx-editor.tsx+++ b/apps/v4/components/extend/xlsx-editor.tsx@@ -16,49 +16,6 @@ import {type XlsxSheetData,type XlsxTableHeaderMenuRenderProps,} from "@extend-ai/react-xlsx"-import {- Add01Icon,- AlignBoxBottomCenterIcon,- AlignBoxMiddleCenterIcon,- AlignBoxTopCenterIcon,- BorderAll01Icon,- BorderBottom01Icon,- BorderLeft01Icon,- BorderNone01Icon,- BorderRight01Icon,- BorderTop01Icon,- Calendar03Icon,- CellsIcon,- ChevronDownIcon,- Delete02Icon,- DollarCircleIcon,- Download01Icon,- DropletOffIcon,- Grid2X2XIcon,- MinusSignCircleIcon,- Moon02Icon,- MoreHorizontalIcon,- PaintBucketIcon,- PathfinderMergeIcon,- PercentIcon,- PlusSignCircleIcon,- Redo02Icon,- Sun03Icon,- TableRowsSplitIcon,- TextAlignCenterIcon,- TextAlignLeft01Icon,- TextAlignRight01Icon,- TextBoldIcon,- TextColorIcon,- TextItalicIcon,- TextNumberSignIcon,- TextStrikethroughIcon,- TextUnderlineIcon,- TextWrapIcon,- Undo02Icon,- Upload01Icon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"@@ -97,6 +54,202 @@ import {WorkbookSheetTabs,WorkbookTableHeaderMenu,} from "@/components/extend/xlsx-viewer"+import { IconPlaceholder } from "@/components/icon-placeholder"++function BorderAll01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Grid2x2"+ tabler="IconBorderAll"+ hugeicons="BorderAll01Icon"+ phosphor="GridFourIcon"+ remixicon="RiGridLine"+ {...props}+ />+ )+}++function BorderBottom01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="PanelBottom"+ tabler="IconBorderBottom"+ hugeicons="BorderBottom01Icon"+ phosphor="SquareHalfBottomIcon"+ remixicon="RiLayoutBottomLine"+ {...props}+ />+ )+}++function BorderLeft01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="PanelLeft"+ tabler="IconBorderLeft"+ hugeicons="BorderLeft01Icon"+ phosphor="SquareHalfIcon"+ remixicon="RiLayoutLeftLine"+ {...props}+ />+ )+}++function BorderNone01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="SquareDashed"+ tabler="IconBorderNone"+ hugeicons="BorderNone01Icon"+ phosphor="SelectionIcon"+ remixicon="RiCheckboxBlankLine"+ {...props}+ />+ )+}++function BorderRight01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="PanelRight"+ tabler="IconBorderRight"+ hugeicons="BorderRight01Icon"+ phosphor="SquareHalfIcon"+ remixicon="RiLayoutRightLine"+ {...props}+ />+ )+}++function BorderTop01Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="PanelTop"+ tabler="IconBorderTop"+ hugeicons="BorderTop01Icon"+ phosphor="AlignTopSimpleIcon"+ remixicon="RiLayoutTopLine"+ {...props}+ />+ )+}++function Calendar03Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Calendar"+ tabler="IconCalendar"+ hugeicons="Calendar03Icon"+ phosphor="CalendarIcon"+ remixicon="RiCalendarLine"+ {...props}+ />+ )+}++function DollarCircleGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="CircleDollarSign"+ tabler="IconCurrencyDollar"+ hugeicons="DollarCircleIcon"+ phosphor="CurrencyCircleDollarIcon"+ remixicon="RiMoneyDollarCircleLine"+ {...props}+ />+ )+}++function Moon02Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Moon"+ tabler="IconMoon"+ hugeicons="Moon02Icon"+ phosphor="MoonIcon"+ remixicon="RiMoonLine"+ {...props}+ />+ )+}++function PaintBucketGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="PaintBucket"+ tabler="IconPaint"+ hugeicons="PaintBucketIcon"+ phosphor="PaintBucketIcon"+ remixicon="RiPaintFill"+ {...props}+ />+ )+}++function PercentGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Percent"+ tabler="IconPercentage"+ hugeicons="PercentIcon"+ phosphor="PercentIcon"+ remixicon="RiPercentLine"+ {...props}+ />+ )+}++function Sun03Glyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Sun"+ tabler="IconSun"+ hugeicons="Sun03Icon"+ phosphor="SunIcon"+ remixicon="RiSunLine"+ {...props}+ />+ )+}++function TextColorGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Baseline"+ tabler="IconTextColor"+ hugeicons="TextColorIcon"+ phosphor="TextAaIcon"+ remixicon="RiFontColor"+ {...props}+ />+ )+}++function TextNumberSignGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="Hash"+ tabler="IconHash"+ hugeicons="TextNumberSignIcon"+ phosphor="HashIcon"+ remixicon="RiHashtag"+ {...props}+ />+ )+}++function TextWrapGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="WrapText"+ tabler="IconTextWrap"+ hugeicons="TextWrapIcon"+ phosphor="ArrowElbowDownLeftIcon"+ remixicon="RiTextWrap"+ {...props}+ />+ )+}const XLSX_LOADING_INDICATOR_DELAY_MS = 300const XLSX_EDITOR_READ_ONLY_THRESHOLD_BYTES = 5 * 1024 * 1024@@ -130,7 +283,7 @@ type UploadedWorkbook = {type NumberFormatOption = {formatString?: stringformatType: NonNullable<XlsxCellStyleInput["numberFormat"]>["formatType"]- icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]+ icon: React.ComponentType<React.ComponentProps<"svg">>id?: numberlabel: stringvalue: string@@ -138,7 +291,7 @@ type NumberFormatOption = {type BorderOption = {action: XlsxBorderAction- icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]+ icon: React.ComponentType<React.ComponentProps<"svg">>label: string}@@ -175,35 +328,35 @@ type XlsxWorksheetWithMergeRegions = {const NUMBER_FORMAT_OPTIONS: NumberFormatOption[] = [{formatType: "general",- icon: TextNumberSignIcon,+ icon: TextNumberSignGlyph,label: "General",value: "General",},{formatString: "0.00",formatType: "custom",- icon: TextNumberSignIcon,+ icon: TextNumberSignGlyph,label: "Number",value: "Number",},{formatString: "$#,##0.00",formatType: "custom",- icon: DollarCircleIcon,+ icon: DollarCircleGlyph,label: "Currency",value: "Currency",},{formatString: "0.00%",formatType: "custom",- icon: PercentIcon,+ icon: PercentGlyph,label: "Percent",value: "Percent",},{formatString: "m/d/yyyy",formatType: "custom",- icon: Calendar03Icon,+ icon: Calendar03Glyph,label: "Date",value: "Date",},@@ -409,7 +562,7 @@ function getNumberFormatLabel(value: string) {function getNumberFormatIcon(value: string) {return (NUMBER_FORMAT_OPTIONS.find((option) => option.value === value)?.icon ??- TextNumberSignIcon+ TextNumberSignGlyph)}@@ -588,37 +741,37 @@ function createBorderOptions(): BorderOption[] {return [{action: "bottom",- icon: BorderBottom01Icon,+ icon: BorderBottom01Glyph,label: "Bottom border",},{action: "left",- icon: BorderLeft01Icon,+ icon: BorderLeft01Glyph,label: "Left border",},{action: "top",- icon: BorderTop01Icon,+ icon: BorderTop01Glyph,label: "Top border",},{action: "right",- icon: BorderRight01Icon,+ icon: BorderRight01Glyph,label: "Right border",},{action: "all",- icon: BorderAll01Icon,+ icon: BorderAll01Glyph,label: "All borders",},{action: "outside",- icon: BorderAll01Icon,+ icon: BorderAll01Glyph,label: "Outside border",},{action: "none",- icon: BorderNone01Icon,+ icon: BorderNone01Glyph,label: "No border",},]@@ -721,12 +874,13 @@ function StyleDropdownItem({onClick,}: {children: React.ReactNode- icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]+ icon: React.ComponentType<React.ComponentProps<"svg">>onClick: () => void}) {+ const IconComponent = iconreturn (<DropdownMenuItem onClick={onClick}>- <HugeiconsIcon icon={icon} className="size-4" />+ <IconComponent className="size-4" />{children}</DropdownMenuItem>)@@ -773,7 +927,14 @@ function MergeCellsMenu({disabled={disabled || !canMerge}onClick={onMergeAndCenter}>- <HugeiconsIcon icon={PathfinderMergeIcon} className="size-4" />+ <IconPlaceholder+ lucide="TableCellsMerge"+ tabler="IconArrowMerge"+ hugeicons="PathfinderMergeIcon"+ phosphor="ArrowsMergeIcon"+ remixicon="RiMergeCellsVertical"+ className="size-4"+ /><span className="hidden text-xs font-medium lg:inline">Merge & Center</span>@@ -789,8 +950,12 @@ function MergeCellsMenu({data-pressed={isMerged ? "" : undefined}disabled={disabled}>- <HugeiconsIcon- icon={ChevronDownIcon}+ <IconPlaceholder+ lucide="ChevronDown"+ tabler="IconChevronDown"+ hugeicons="ChevronDownIcon"+ phosphor="CaretDownIcon"+ remixicon="RiArrowDownSLine"className="size-3.5 opacity-100"/></Button>@@ -801,20 +966,48 @@ function MergeCellsMenu({className={cn("w-56", XLSX_DROPDOWN_Z_INDEX_CLASS)}><DropdownMenuItem disabled={!canMerge} onClick={onMergeAndCenter}>- <HugeiconsIcon icon={PathfinderMergeIcon} className="size-4" />+ <IconPlaceholder+ lucide="TableCellsMerge"+ tabler="IconArrowMerge"+ hugeicons="PathfinderMergeIcon"+ phosphor="ArrowsMergeIcon"+ remixicon="RiMergeCellsVertical"+ className="size-4"+ />Merge & Center</DropdownMenuItem><DropdownMenuItem disabled={!canMergeAcross} onClick={onMergeAcross}>- <HugeiconsIcon icon={TableRowsSplitIcon} className="size-4" />+ <IconPlaceholder+ lucide="TableRowsSplit"+ tabler="IconArrowsSplit"+ hugeicons="TableRowsSplitIcon"+ phosphor="ArrowsSplitIcon"+ remixicon="RiSplitCellsVertical"+ className="size-4"+ />Merge Across</DropdownMenuItem><DropdownMenuItem disabled={!canMerge} onClick={onMergeCells}>- <HugeiconsIcon icon={CellsIcon} className="size-4" />+ <IconPlaceholder+ lucide="Grid3x3"+ tabler="IconGrid4x4"+ hugeicons="CellsIcon"+ phosphor="GridNineIcon"+ remixicon="RiMergeCellsHorizontal"+ className="size-4"+ />Merge Cells</DropdownMenuItem><DropdownMenuSeparator /><DropdownMenuItem disabled={!canUnmerge} onClick={onUnmergeCells}>- <HugeiconsIcon icon={Grid2X2XIcon} className="size-4" />+ <IconPlaceholder+ lucide="Grid2x2X"+ tabler="IconTableMinus"+ hugeicons="Grid2X2XIcon"+ phosphor="SelectionSlashIcon"+ remixicon="RiSplitCellsHorizontal"+ className="size-4"+ />Unmerge Cells</DropdownMenuItem></DropdownMenuContent>@@ -835,7 +1028,9 @@ function NumberFormatSelect({(option) => option.value === value)const currentLabel = getNumberFormatLabel(value)- const CurrentIcon = getNumberFormatIcon(value)+ const currentIcon = React.createElement(getNumberFormatIcon(value), {+ className: "size-4",+ })return (<Select@@ -854,7 +1049,7 @@ function NumberFormatSelect({)}aria-label="Number format">- <HugeiconsIcon icon={CurrentIcon} className="size-4" />+ {currentIcon}<SelectValue placeholder="General" /></SelectTrigger><SelectContent@@ -865,7 +1060,7 @@ function NumberFormatSelect({{NUMBER_FORMAT_OPTIONS.map((option) => (<SelectItem key={option.value} value={option.value}><span className="flex min-w-0 items-center gap-2">- <HugeiconsIcon icon={option.icon} className="size-4" />+ <option.icon className="size-4" /><span className="truncate">{option.label}</span></span></SelectItem>@@ -873,7 +1068,7 @@ function NumberFormatSelect({{!hasMatchingOption && value !== GENERAL_NUMBER_FORMAT_VALUE ? (<SelectItem value={value}><span className="flex min-w-0 items-center gap-2">- <HugeiconsIcon icon={CurrentIcon} className="size-4" />+ {currentIcon}<span className="truncate">{currentLabel}</span></span></SelectItem>@@ -920,7 +1115,14 @@ function BorderMenu({aria-label="Cell borders"className="relative">- <HugeiconsIcon icon={BorderAll01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Grid2x2"+ tabler="IconBorderAll"+ hugeicons="BorderAll01Icon"+ phosphor="GridFourIcon"+ remixicon="RiGridLine"+ className="size-4"+ /><spanclassName="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"style={{ backgroundColor: borderColor }}@@ -955,8 +1157,12 @@ function BorderMenu({<DropdownMenuSeparator /><DropdownMenuSub><DropdownMenuSubTrigger>- <HugeiconsIcon- icon={TextColorIcon}+ <IconPlaceholder+ lucide="Baseline"+ tabler="IconTextColor"+ hugeicons="TextColorIcon"+ phosphor="TextAaIcon"+ remixicon="RiFontColor"className="size-4 text-muted-foreground"/>Border color@@ -999,7 +1205,14 @@ function AlignmentMoreMenu({disabled={disabled}aria-label="More alignment">- <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />+ <IconPlaceholder+ lucide="Ellipsis"+ tabler="IconDots"+ hugeicons="MoreHorizontalIcon"+ phosphor="DotsThreeIcon"+ remixicon="RiMoreLine"+ className="size-4"+ /></Button></DropdownMenuTrigger><DropdownMenuContent@@ -1007,19 +1220,19 @@ function AlignmentMoreMenu({className={cn("w-48", XLSX_DROPDOWN_Z_INDEX_CLASS)}><StyleDropdownItem- icon={TextWrapIcon}+ icon={TextWrapGlyph}onClick={() => onApplyStyle({ alignment: { wrapText: false } })}>Do not wrap</StyleDropdownItem><StyleDropdownItem- icon={TextWrapIcon}+ icon={TextWrapGlyph}onClick={() => onApplyStyle({ alignment: { shrinkToFit: true } })}>Shrink to fit</StyleDropdownItem><StyleDropdownItem- icon={TextWrapIcon}+ icon={TextWrapGlyph}onClick={() => onApplyStyle({ alignment: { shrinkToFit: false } })}>Do not shrink@@ -1047,7 +1260,14 @@ function EditorFileActionsMenu({size="icon-sm"aria-label="Open workbook actions">- <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />+ <IconPlaceholder+ lucide="Ellipsis"+ tabler="IconDots"+ hugeicons="MoreHorizontalIcon"+ phosphor="DotsThreeIcon"+ remixicon="RiMoreLine"+ className="size-4"+ /></Button></DropdownMenuTrigger><DropdownMenuContent@@ -1055,11 +1275,25 @@ function EditorFileActionsMenu({className={cn("w-40", XLSX_DROPDOWN_Z_INDEX_CLASS)}><DropdownMenuItem disabled={!canExport} onClick={exportXlsx}>- <HugeiconsIcon icon={Download01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Download"+ tabler="IconDownload"+ hugeicons="Download01Icon"+ phosphor="DownloadSimpleIcon"+ remixicon="RiDownload2Line"+ className="size-4"+ />Download</DropdownMenuItem><DropdownMenuItem onClick={onUploadClick}>- <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-4"+ />Upload</DropdownMenuItem></DropdownMenuContent>@@ -1577,10 +1811,11 @@ function EditorToolbar({}onClick={() => onIsDarkChange(!isDark)}>- <HugeiconsIcon- icon={isDark ? Sun03Icon : Moon02Icon}- className="size-4"- />+ {isDark ? (+ <Sun03Glyph className="size-4" />+ ) : (+ <Moon02Glyph className="size-4" />+ )}</Button></ToolbarTooltip><Separator@@ -1609,7 +1844,14 @@ function EditorToolbar({disabled={!canUndo || readOnly}onClick={undo}>- <HugeiconsIcon icon={Undo02Icon} className="size-4" />+ <IconPlaceholder+ lucide="Undo2"+ tabler="IconArrowBackUp"+ hugeicons="Undo02Icon"+ phosphor="ArrowUUpLeftIcon"+ remixicon="RiArrowGoBackLine"+ className="size-4"+ /></Button></ToolbarTooltip><ToolbarTooltip label="Redo">@@ -1621,7 +1863,14 @@ function EditorToolbar({disabled={!canRedo || readOnly}onClick={redo}>- <HugeiconsIcon icon={Redo02Icon} className="size-4" />+ <IconPlaceholder+ lucide="Redo2"+ tabler="IconArrowForwardUp"+ hugeicons="Redo02Icon"+ phosphor="ArrowUUpRightIcon"+ remixicon="RiArrowGoForwardLine"+ className="size-4"+ /></Button></ToolbarTooltip></div>@@ -1709,12 +1958,26 @@ function EditorToolbar({><ToolbarTooltip label="Bold"><ToggleGroupItem aria-label="Bold" size="sm" value="bold">- <HugeiconsIcon icon={TextBoldIcon} className="size-4" />+ <IconPlaceholder+ lucide="Bold"+ tabler="IconBold"+ hugeicons="TextBoldIcon"+ phosphor="TextBIcon"+ remixicon="RiBold"+ className="size-4"+ /></ToggleGroupItem></ToolbarTooltip><ToolbarTooltip label="Italic"><ToggleGroupItem aria-label="Italic" size="sm" value="italic">- <HugeiconsIcon icon={TextItalicIcon} className="size-4" />+ <IconPlaceholder+ lucide="Italic"+ tabler="IconItalic"+ hugeicons="TextItalicIcon"+ phosphor="TextItalicIcon"+ remixicon="RiItalic"+ className="size-4"+ /></ToggleGroupItem></ToolbarTooltip><ToolbarTooltip label="Underline">@@ -1723,7 +1986,14 @@ function EditorToolbar({size="sm"value="underline">- <HugeiconsIcon icon={TextUnderlineIcon} className="size-4" />+ <IconPlaceholder+ lucide="Underline"+ tabler="IconUnderline"+ hugeicons="TextUnderlineIcon"+ phosphor="TextUnderlineIcon"+ remixicon="RiUnderline"+ className="size-4"+ /></ToggleGroupItem></ToolbarTooltip><ToolbarTooltip label="Strikethrough">@@ -1732,8 +2002,12 @@ function EditorToolbar({size="sm"value="strikethrough">- <HugeiconsIcon- icon={TextStrikethroughIcon}+ <IconPlaceholder+ lucide="Strikethrough"+ tabler="IconStrikethrough"+ hugeicons="TextStrikethroughIcon"+ phosphor="TextStrikethroughIcon"+ remixicon="RiStrikethrough"className="size-4"/></ToggleGroupItem>@@ -1743,7 +2017,7 @@ function EditorToolbar({<div className="flex shrink-0 items-center gap-1"><ColorPickerlabel="Text color"- icon={TextColorIcon}+ icon={TextColorGlyph}color={textColor}disabled={!canStyleSelection}onChange={(color) => {@@ -1754,7 +2028,7 @@ function EditorToolbar({/><ColorPickerlabel="Fill color"- icon={PaintBucketIcon}+ icon={PaintBucketGlyph}color={fillColor}disabled={!canStyleSelection}onChange={(color) => {@@ -1773,7 +2047,14 @@ function EditorToolbar({disabled={!canStyleSelection}onClick={() => applyStyle({ fill: { fillType: "none" } })}>- <HugeiconsIcon icon={DropletOffIcon} className="size-4" />+ <IconPlaceholder+ lucide="DropletOff"+ tabler="IconDropletOff"+ hugeicons="DropletOffIcon"+ phosphor="DropSlashIcon"+ remixicon="RiDropLine"+ className="size-4"+ /></ToolbarIconButton></div><ToolbarSeparator />@@ -1791,8 +2072,12 @@ function EditorToolbar({value="left"onClick={() => applyHorizontalAlignment("left")}>- <HugeiconsIcon- icon={TextAlignLeft01Icon}+ <IconPlaceholder+ lucide="AlignLeft"+ tabler="IconAlignLeft"+ hugeicons="TextAlignLeft01Icon"+ phosphor="TextAlignLeftIcon"+ remixicon="RiAlignLeft"className="size-4"/></ToggleGroupItem>@@ -1804,8 +2089,12 @@ function EditorToolbar({value="center"onClick={() => applyHorizontalAlignment("center")}>- <HugeiconsIcon- icon={TextAlignCenterIcon}+ <IconPlaceholder+ lucide="AlignCenter"+ tabler="IconAlignCenter"+ hugeicons="TextAlignCenterIcon"+ phosphor="TextAlignCenterIcon"+ remixicon="RiAlignCenter"className="size-4"/></ToggleGroupItem>@@ -1817,8 +2106,12 @@ function EditorToolbar({value="right"onClick={() => applyHorizontalAlignment("right")}>- <HugeiconsIcon- icon={TextAlignRight01Icon}+ <IconPlaceholder+ lucide="AlignRight"+ tabler="IconAlignRight"+ hugeicons="TextAlignRight01Icon"+ phosphor="TextAlignRightIcon"+ remixicon="RiAlignRight"className="size-4"/></ToggleGroupItem>@@ -1837,8 +2130,12 @@ function EditorToolbar({value="top"onClick={() => applyVerticalAlignment("top")}>- <HugeiconsIcon- icon={AlignBoxTopCenterIcon}+ <IconPlaceholder+ lucide="AlignVerticalJustifyStart"+ tabler="IconAlignBoxTopCenter"+ hugeicons="AlignBoxTopCenterIcon"+ phosphor="AlignTopIcon"+ remixicon="RiAlignTop"className="size-4"/></ToggleGroupItem>@@ -1850,8 +2147,12 @@ function EditorToolbar({value="center"onClick={() => applyVerticalAlignment("center")}>- <HugeiconsIcon- icon={AlignBoxMiddleCenterIcon}+ <IconPlaceholder+ lucide="AlignVerticalJustifyCenter"+ tabler="IconAlignBoxCenterMiddle"+ hugeicons="AlignBoxMiddleCenterIcon"+ phosphor="AlignCenterVerticalIcon"+ remixicon="RiAlignVertically"className="size-4"/></ToggleGroupItem>@@ -1863,8 +2164,12 @@ function EditorToolbar({value="bottom"onClick={() => applyVerticalAlignment("bottom")}>- <HugeiconsIcon- icon={AlignBoxBottomCenterIcon}+ <IconPlaceholder+ lucide="AlignVerticalJustifyEnd"+ tabler="IconAlignBoxBottomCenter"+ hugeicons="AlignBoxBottomCenterIcon"+ phosphor="AlignBottomIcon"+ remixicon="RiAlignBottom"className="size-4"/></ToggleGroupItem>@@ -1875,7 +2180,14 @@ function EditorToolbar({disabled={!canStyleSelection}onClick={() => applyStyle({ alignment: { wrapText: true } })}>- <HugeiconsIcon icon={TextWrapIcon} className="size-4" />+ <IconPlaceholder+ lucide="WrapText"+ tabler="IconTextWrap"+ hugeicons="TextWrapIcon"+ phosphor="ArrowElbowDownLeftIcon"+ remixicon="RiTextWrap"+ className="size-4"+ /></ToolbarIconButton><AlignmentMoreMenudisabled={!canStyleSelection}@@ -1921,7 +2233,14 @@ function EditorToolbar({disabled={!hasWorkbook || readOnly}onClick={() => addSheet()}>- <HugeiconsIcon icon={Add01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Plus"+ tabler="IconPlus"+ hugeicons="Add01Icon"+ phosphor="PlusIcon"+ remixicon="RiAddLine"+ className="size-4"+ /></Button></ToolbarTooltip><ToolbarTooltip label="Remove active sheet">@@ -1933,7 +2252,14 @@ function EditorToolbar({disabled={sheets.length <= 1 || readOnly}onClick={removeActiveSheet}>- <HugeiconsIcon icon={Delete02Icon} className="size-4" />+ <IconPlaceholder+ lucide="Trash2Icon"+ tabler="IconTrash"+ hugeicons="Delete02Icon"+ phosphor="TrashIcon"+ remixicon="RiDeleteBinLine"+ className="size-4"+ /></Button></ToolbarTooltip><Select@@ -1977,7 +2303,14 @@ function EditorToolbar({aria-label="Zoom out"onClick={zoomOut}>- <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />+ <IconPlaceholder+ lucide="CircleMinus"+ tabler="IconCircleMinus"+ hugeicons="MinusSignCircleIcon"+ phosphor="MinusCircleIcon"+ remixicon="RiIndeterminateCircleLine"+ className="size-4"+ /></Button></ToolbarTooltip><Select@@ -2017,7 +2350,14 @@ function EditorToolbar({aria-label="Zoom in"onClick={zoomIn}>- <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />+ <IconPlaceholder+ lucide="CirclePlusIcon"+ tabler="IconCirclePlusFilled"+ hugeicons="PlusSignCircleIcon"+ phosphor="PlusCircleIcon"+ remixicon="RiAddCircleFill"+ className="size-4"+ /></Button></ToolbarTooltip></div>@@ -2292,7 +2632,14 @@ function XlsxEditorContent({className="mt-4"onClick={() => fileInputRef.current?.click()}>- <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-4"+ />Upload XLSX</Button></div>@@ -2327,7 +2674,14 @@ function XlsxEditorContent({className="mt-4"onClick={() => fileInputRef.current?.click()}>- <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-4"+ />Upload XLSX</Button></div>diff --git a/apps/v4/components/extend/xlsx-viewer.tsx b/apps/v4/components/extend/xlsx-viewer.tsxindex e41d23d..7973826 100644--- a/apps/v4/components/extend/xlsx-viewer.tsx+++ b/apps/v4/components/extend/xlsx-viewer.tsx@@ -14,18 +14,6 @@ import {type XlsxTableHeaderMenuRenderProps,type XlsxViewerController,} from "@extend-ai/react-xlsx"-import {- ArrowLeft01Icon,- ArrowRight01Icon,- Download01Icon,- MinusSignCircleIcon,- Moon02Icon,- MoreHorizontalIcon,- PlusSignCircleIcon,- Search01Icon,- Upload01Icon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { createPortal } from "react-dom"import { cn } from "@/lib/utils"@@ -63,6 +51,7 @@ import {TooltipProvider,TooltipTrigger,} from "@/components/ui/tooltip"+import { IconPlaceholder } from "@/components/icon-placeholder"const XLSX_LOADING_INDICATOR_DELAY_MS = 300const XLSX_DROPDOWN_Z_INDEX_CLASS = "z-40"@@ -497,7 +486,14 @@ function WorkbookFileActionsMenu({size="icon-sm"aria-label="Open workbook actions">- <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />+ <IconPlaceholder+ lucide="Ellipsis"+ tabler="IconDots"+ hugeicons="MoreHorizontalIcon"+ phosphor="DotsThreeIcon"+ remixicon="RiMoreLine"+ className="size-4"+ /></Button></DropdownMenuTrigger><DropdownMenuContent@@ -512,7 +508,14 @@ function WorkbookFileActionsMenu({onCheckedChange={(checked) => onIsDarkChange?.(checked === true)}><span className="flex min-w-0 items-center gap-2">- <HugeiconsIcon icon={Moon02Icon} className="size-4" />+ <IconPlaceholder+ lucide="Moon"+ tabler="IconMoon"+ hugeicons="Moon02Icon"+ phosphor="MoonIcon"+ remixicon="RiMoonLine"+ className="size-4"+ />Dark mode</span></DropdownMenuCheckboxItem>@@ -521,13 +524,27 @@ function WorkbookFileActionsMenu({) : null}{showDownloadButton && onDownload ? (<DropdownMenuItem onClick={onDownload}>- <HugeiconsIcon icon={Download01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Download"+ tabler="IconDownload"+ hugeicons="Download01Icon"+ phosphor="DownloadSimpleIcon"+ remixicon="RiDownload2Line"+ className="size-4"+ />Download</DropdownMenuItem>) : null}{showUploadButton ? (<DropdownMenuItem onClick={onUploadClick}>- <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-4"+ />Upload</DropdownMenuItem>) : null}@@ -573,7 +590,14 @@ export function WorkbookTableHeaderMenu({{triggerIcon ? (triggerIcon) : (- <HugeiconsIcon icon={MoreHorizontalIcon} className="size-3.5" />+ <IconPlaceholder+ lucide="Ellipsis"+ tabler="IconDots"+ hugeicons="MoreHorizontalIcon"+ phosphor="DotsThreeIcon"+ remixicon="RiMoreLine"+ className="size-3.5"+ />)}</Button></DropdownMenuTrigger>@@ -765,7 +789,14 @@ function WorkbookSearchPopover({aria-label="Search workbook"disabled={controlsDisabled}>- <HugeiconsIcon icon={Search01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Search"+ tabler="IconSearch"+ hugeicons="Search01Icon"+ phosphor="MagnifyingGlassIcon"+ remixicon="RiSearchLine"+ className="size-4"+ /></Button></PopoverTrigger></ToolbarTooltip>@@ -817,7 +848,14 @@ function WorkbookSearchPopover({disabled={isSearching || searchResults.length === 0}onClick={() => goToRelativeResult(-1)}>- <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />+ <IconPlaceholder+ lucide="ChevronLeft"+ tabler="IconChevronLeft"+ hugeicons="ArrowLeft01Icon"+ phosphor="CaretLeftIcon"+ remixicon="RiArrowLeftSLine"+ className="size-4"+ /></Button><Buttontype="button"@@ -827,7 +865,14 @@ function WorkbookSearchPopover({disabled={isSearching || searchResults.length === 0}onClick={() => goToRelativeResult(1)}>- <HugeiconsIcon icon={ArrowRight01Icon} className="size-4" />+ <IconPlaceholder+ lucide="ArrowRight"+ tabler="IconArrowRight"+ hugeicons="ArrowRight01Icon"+ phosphor="ArrowRightIcon"+ remixicon="RiArrowRightLine"+ className="size-4"+ /></Button></div></div>@@ -892,7 +937,14 @@ function WorkbookToolbar({aria-label="Zoom out"onClick={zoomOut}>- <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />+ <IconPlaceholder+ lucide="CircleMinus"+ tabler="IconCircleMinus"+ hugeicons="MinusSignCircleIcon"+ phosphor="MinusCircleIcon"+ remixicon="RiIndeterminateCircleLine"+ className="size-4"+ /></Button></ToolbarTooltip><Select@@ -928,7 +980,14 @@ function WorkbookToolbar({aria-label="Zoom in"onClick={zoomIn}>- <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />+ <IconPlaceholder+ lucide="CirclePlusIcon"+ tabler="IconCirclePlusFilled"+ hugeicons="PlusSignCircleIcon"+ phosphor="PlusCircleIcon"+ remixicon="RiAddCircleFill"+ className="size-4"+ /></Button></ToolbarTooltip></div>@@ -1581,7 +1640,14 @@ function XlsxViewerContent({className="mt-4"onClick={() => fileInputRef.current?.click()}>- <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-4"+ />Upload XLSX</Button></div>@@ -1621,7 +1687,14 @@ function XlsxViewerContent({className="mt-4"onClick={() => fileInputRef.current?.click()}>- <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Upload"+ tabler="IconUpload"+ hugeicons="Upload01Icon"+ phosphor="UploadSimpleIcon"+ remixicon="RiUpload2Line"+ className="size-4"+ />Upload XLSX</Button></div>diff --git a/apps/v4/components/file-upload-docs.tsx b/apps/v4/components/file-upload-docs.tsxindex 55895ee..5d3f77a 100644--- a/apps/v4/components/file-upload-docs.tsx+++ b/apps/v4/components/file-upload-docs.tsx@@ -372,7 +372,7 @@ export function FileUploadExample() {}`const fileUploadUsageCode =- '"use client"\n\nimport * as React from "react"\nimport {\n FileImageIcon,\n FileSpreadsheetIcon,\n FileUploadIcon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { BorderBeam } from "border-beam"\n\nimport { cn } from "@/lib/utils"\nimport { Card } from "@/components/ui/card"\nimport { FileThumbnail } from "@/components/extend/file-thumbnail"\n\ntype FileUploadItem = {\n id: string\n name: string\n type: string\n size: number\n url: string\n}\n\ntype AcceptedFileType = {\n label: string\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n}\n\ntype FileUploadProps = {\n accept?: string\n acceptedFileTypes?: AcceptedFileType[]\n borderBeamTheme?: React.ComponentProps<typeof BorderBeam>["theme"]\n browseLabel?: string\n className?: string\n description?: string\n draggingLabel?: string\n multiple?: boolean\n showBorderBeam?: boolean\n showFileList?: boolean\n title?: string\n onFilesAccepted?: (files: File[]) => void\n onFilesChange?: (files: FileUploadItem[]) => void\n}\n\nconst ACCEPTED_FILE_TYPES: AcceptedFileType[] = [\n { label: "Image", icon: FileImageIcon },\n { label: "PDF", icon: FileUploadIcon },\n { label: "Sheet", icon: FileSpreadsheetIcon },\n]\nconst DEFAULT_ACCEPT = [\n ".pdf",\n ".doc",\n ".docx",\n ".xlsx",\n ".csv",\n ".png",\n ".jpg",\n ".jpeg",\n "application/pdf",\n "application/msword",\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document",\n "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",\n "text/csv",\n "image/png",\n "image/jpeg",\n].join(",")\nconst ICON_TRANSFORMS = [\n {\n idle: "translate(-78%, -50%) rotate(-8deg)",\n active: "translate(-114%, -50%) rotate(-12deg) scale(1.08)",\n },\n {\n idle: "translate(-50%, -50%) rotate(0deg)",\n active: "translate(-50%, -50%) rotate(0deg) scale(1.18)",\n },\n {\n idle: "translate(-22%, -50%) rotate(8deg)",\n active: "translate(14%, -50%) rotate(12deg) scale(1.08)",\n },\n]\n\nfunction formatBytes(bytes: number) {\n if (bytes === 0) return "0 B"\n\n const units = ["B", "KB", "MB", "GB"]\n const index = Math.min(\n Math.floor(Math.log(bytes) / Math.log(1024)),\n units.length - 1\n )\n\n return `${(bytes / 1024 ** index).toFixed(index === 0 ? 0 : 1)} ${\n units[index]\n }`\n}\n\nfunction matchesAccept(file: File, accept?: string) {\n if (!accept) return true\n\n return accept.split(",").some((rawToken) => {\n const token = rawToken.trim().toLowerCase()\n\n if (!token) return false\n if (token.startsWith(".")) return file.name.toLowerCase().endsWith(token)\n if (token.endsWith("/*")) {\n return file.type.toLowerCase().startsWith(token.slice(0, -1))\n }\n\n return file.type.toLowerCase() === token\n })\n}\n\nfunction toUploadItems(files: FileList | File[]): FileUploadItem[] {\n return Array.from(files).map((file) => ({\n id: `${file.name}-${file.size}-${file.lastModified}`,\n name: file.name,\n type: file.type || "Unknown type",\n size: file.size,\n url: URL.createObjectURL(file),\n }))\n}\n\nfunction UploadIconCluster({\n acceptedFileTypes,\n isDragging,\n}: {\n acceptedFileTypes: AcceptedFileType[]\n isDragging: boolean\n}) {\n const singleIcon = acceptedFileTypes.length === 1\n\n return (\n <div className="relative h-14 w-36">\n {acceptedFileTypes.map((item, index) => (\n <Card\n key={item.label}\n className={cn(\n "absolute top-1/2 left-1/2 grid size-12 place-items-center rounded-xl bg-background text-muted-foreground transition-[transform,color,background-color] duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] before:rounded-[calc(var(--radius-xl)-1px)]",\n "motion-reduce:transition-none",\n index === 1 && "z-10",\n isDragging &&\n "bg-popover text-foreground shadow-md shadow-black/10 not-dark:bg-clip-border dark:shadow-black/25"\n )}\n style={{\n transform: singleIcon\n ? `translate(-50%, -50%) scale(${isDragging ? 1.14 : 1})`\n : isDragging\n ? ICON_TRANSFORMS[index]?.active\n : ICON_TRANSFORMS[index]?.idle,\n }}\n >\n <HugeiconsIcon icon={item.icon} className="size-5" />\n </Card>\n ))}\n </div>\n )\n}\n\nexport function FileUpload({\n accept = DEFAULT_ACCEPT,\n acceptedFileTypes = ACCEPTED_FILE_TYPES,\n borderBeamTheme = "light",\n browseLabel = "Browse files",\n className,\n description = "PDF, DOC/DOCX, XLSX, CSV, PNG, or JPG",\n draggingLabel = "Drop to add",\n multiple = true,\n showBorderBeam = true,\n showFileList = true,\n title = "Click to upload or drop files",\n onFilesAccepted,\n onFilesChange,\n}: FileUploadProps) {\n const dragDepthRef = React.useRef(0)\n const inputRef = React.useRef<HTMLInputElement>(null)\n const [isDragging, setIsDragging] = React.useState(false)\n const [files, setFiles] = React.useState<FileUploadItem[]>([])\n const [rejectionMessage, setRejectionMessage] = React.useState<string | null>(\n null\n )\n\n const commitFiles = React.useCallback(\n (nextFiles: FileList | File[]) => {\n const acceptedFiles = Array.from(nextFiles)\n .filter((file) => matchesAccept(file, accept))\n .slice(0, multiple ? undefined : 1)\n\n if (acceptedFiles.length === 0) {\n setRejectionMessage("This file type is not supported here.")\n return\n }\n\n setRejectionMessage(null)\n onFilesAccepted?.(acceptedFiles)\n\n const items = toUploadItems(acceptedFiles)\n setFiles((previousFiles) => {\n previousFiles.forEach((file) => URL.revokeObjectURL(file.url))\n return items\n })\n onFilesChange?.(items)\n },\n [accept, multiple, onFilesAccepted, onFilesChange]\n )\n\n React.useEffect(() => {\n return () => {\n files.forEach((file) => URL.revokeObjectURL(file.url))\n }\n }, [files])\n\n const openFileDialog = React.useCallback(() => {\n inputRef.current?.click()\n }, [])\n\n const dropzone = (\n <div\n role="button"\n tabIndex={0}\n className={cn(\n "relative flex min-h-64 cursor-pointer flex-col items-center justify-center gap-5 overflow-hidden rounded-[1.125rem] border border-dashed bg-background px-6 py-10 text-center transition-[border-color,background-color] duration-200 ease-out",\n "motion-reduce:transition-none",\n isDragging\n ? "border-foreground/40 bg-accent/35"\n : "border-foreground/20 hover:border-foreground/35 hover:bg-muted/35 dark:border-foreground/25 dark:hover:border-foreground/40"\n )}\n onClick={openFileDialog}\n onDragEnter={(event) => {\n event.preventDefault()\n dragDepthRef.current += 1\n setIsDragging(true)\n }}\n onDragLeave={(event) => {\n event.preventDefault()\n dragDepthRef.current = Math.max(0, dragDepthRef.current - 1)\n if (dragDepthRef.current === 0) setIsDragging(false)\n }}\n onDragOver={(event) => event.preventDefault()}\n onDrop={(event) => {\n event.preventDefault()\n dragDepthRef.current = 0\n setIsDragging(false)\n if (event.dataTransfer.files.length > 0) {\n commitFiles(event.dataTransfer.files)\n }\n }}\n onKeyDown={(event) => {\n if (event.key === "Enter" || event.key === " ") {\n event.preventDefault()\n openFileDialog()\n }\n }}\n >\n <UploadIconCluster\n acceptedFileTypes={acceptedFileTypes}\n isDragging={isDragging}\n />\n <div className="space-y-1">\n <div className="text-sm font-medium">{title}</div>\n <div className="text-xs text-muted-foreground">{description}</div>\n {rejectionMessage ? (\n <div className="text-xs text-destructive">{rejectionMessage}</div>\n ) : null}\n </div>\n <div className="inline-flex items-center gap-2 rounded-full border bg-background px-3 py-1 text-xs text-muted-foreground">\n <HugeiconsIcon icon={Upload01Icon} className="size-3.5" />\n <span>{isDragging ? draggingLabel : browseLabel}</span>\n </div>\n <input\n ref={inputRef}\n type="file"\n accept={accept}\n multiple={multiple}\n className="hidden"\n onChange={(event) => {\n if (event.target.files) {\n commitFiles(event.target.files)\n event.currentTarget.value = ""\n }\n }}\n />\n </div>\n )\n\n return (\n <div className={cn("space-y-3", className)}>\n {showBorderBeam ? (\n <BorderBeam\n active={isDragging}\n borderRadius={18}\n brightness={2.4}\n className="rounded-[1.125rem]"\n colorVariant="ocean"\n duration={2.4}\n size="md"\n strength={1}\n theme={borderBeamTheme}\n >\n {dropzone}\n </BorderBeam>\n ) : (\n dropzone\n )}\n {showFileList && files.length > 0 ? (\n <div className="rounded-xl border bg-background">\n {files.map((file) => (\n <div\n key={file.id}\n className="flex items-center gap-3 border-b px-3 py-2.5 last:border-b-0"\n >\n <FileThumbnail\n file={{\n name: file.name,\n type: file.type,\n }}\n previewImageUrl={\n file.type.startsWith("image/") ? file.url : null\n }\n className="size-10 shrink-0 rounded-lg"\n />\n <div className="min-w-0 flex-1">\n <div className="truncate text-sm font-medium">{file.name}</div>\n <div className="truncate text-xs text-muted-foreground">\n {file.type} - {formatBytes(file.size)}\n </div>\n </div>\n <div className="rounded-full bg-muted px-2 py-1 text-xs text-muted-foreground">\n Ready\n </div>\n </div>\n ))}\n </div>\n ) : null}\n </div>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport { BorderBeam } from "border-beam"\n\nimport { cn } from "@/lib/utils"\nimport { Card } from "@/components/ui/card"\nimport { FileThumbnail } from "@/components/extend/file-thumbnail"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nfunction FileImageGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="FileImage"\n tabler="IconPhoto"\n hugeicons="FileImageIcon"\n phosphor="FileImageIcon"\n remixicon="RiFileImageLine"\n {...props}\n />\n )\n}\n\nfunction FileSpreadsheetGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="FileSpreadsheet"\n tabler="IconFileSpreadsheet"\n hugeicons="FileSpreadsheetIcon"\n phosphor="FileXlsIcon"\n remixicon="RiFileExcel2Line"\n {...props}\n />\n )\n}\n\nfunction FileUploadGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="FileUp"\n tabler="IconFileUpload"\n hugeicons="FileUploadIcon"\n phosphor="FileArrowUpIcon"\n remixicon="RiFileUploadLine"\n {...props}\n />\n )\n}\n\ntype FileUploadItem = {\n id: string\n name: string\n type: string\n size: number\n url: string\n}\n\ntype AcceptedFileType = {\n label: string\n icon: React.ComponentType<React.ComponentProps<"svg">>\n}\n\ntype FileUploadProps = {\n accept?: string\n acceptedFileTypes?: AcceptedFileType[]\n borderBeamTheme?: React.ComponentProps<typeof BorderBeam>["theme"]\n browseLabel?: string\n className?: string\n description?: string\n draggingLabel?: string\n multiple?: boolean\n showBorderBeam?: boolean\n showFileList?: boolean\n title?: string\n onFilesAccepted?: (files: File[]) => void\n onFilesChange?: (files: FileUploadItem[]) => void\n}\n\nconst ACCEPTED_FILE_TYPES: AcceptedFileType[] = [\n { label: "Image", icon: FileImageGlyph },\n { label: "PDF", icon: FileUploadGlyph },\n { label: "Sheet", icon: FileSpreadsheetGlyph },\n]\nconst DEFAULT_ACCEPT = [\n ".pdf",\n ".doc",\n ".docx",\n ".xlsx",\n ".csv",\n ".png",\n ".jpg",\n ".jpeg",\n "application/pdf",\n "application/msword",\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document",\n "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",\n "text/csv",\n "image/png",\n "image/jpeg",\n].join(",")\nconst ICON_TRANSFORMS = [\n {\n idle: "translate(-78%, -50%) rotate(-8deg)",\n active: "translate(-114%, -50%) rotate(-12deg) scale(1.08)",\n },\n {\n idle: "translate(-50%, -50%) rotate(0deg)",\n active: "translate(-50%, -50%) rotate(0deg) scale(1.18)",\n },\n {\n idle: "translate(-22%, -50%) rotate(8deg)",\n active: "translate(14%, -50%) rotate(12deg) scale(1.08)",\n },\n]\n\nfunction formatBytes(bytes: number) {\n if (bytes === 0) return "0 B"\n\n const units = ["B", "KB", "MB", "GB"]\n const index = Math.min(\n Math.floor(Math.log(bytes) / Math.log(1024)),\n units.length - 1\n )\n\n return `${(bytes / 1024 ** index).toFixed(index === 0 ? 0 : 1)} ${\n units[index]\n }`\n}\n\nfunction matchesAccept(file: File, accept?: string) {\n if (!accept) return true\n\n return accept.split(",").some((rawToken) => {\n const token = rawToken.trim().toLowerCase()\n\n if (!token) return false\n if (token.startsWith(".")) return file.name.toLowerCase().endsWith(token)\n if (token.endsWith("/*")) {\n return file.type.toLowerCase().startsWith(token.slice(0, -1))\n }\n\n return file.type.toLowerCase() === token\n })\n}\n\nfunction toUploadItems(files: FileList | File[]): FileUploadItem[] {\n return Array.from(files).map((file) => ({\n id: `${file.name}-${file.size}-${file.lastModified}`,\n name: file.name,\n type: file.type || "Unknown type",\n size: file.size,\n url: URL.createObjectURL(file),\n }))\n}\n\nfunction UploadIconCluster({\n acceptedFileTypes,\n isDragging,\n}: {\n acceptedFileTypes: AcceptedFileType[]\n isDragging: boolean\n}) {\n const singleIcon = acceptedFileTypes.length === 1\n\n return (\n <div className="relative h-14 w-36">\n {acceptedFileTypes.map((item, index) => (\n <Card\n key={item.label}\n className={cn(\n "absolute top-1/2 left-1/2 grid size-12 place-items-center rounded-xl bg-background text-muted-foreground transition-[transform,color,background-color] duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] before:rounded-[calc(var(--radius-xl)-1px)]",\n "motion-reduce:transition-none",\n index === 1 && "z-10",\n isDragging &&\n "bg-popover text-foreground shadow-md shadow-black/10 not-dark:bg-clip-border dark:shadow-black/25"\n )}\n style={{\n transform: singleIcon\n ? `translate(-50%, -50%) scale(${isDragging ? 1.14 : 1})`\n : isDragging\n ? ICON_TRANSFORMS[index]?.active\n : ICON_TRANSFORMS[index]?.idle,\n }}\n >\n <item.icon className="size-5" />\n </Card>\n ))}\n </div>\n )\n}\n\nexport function FileUpload({\n accept = DEFAULT_ACCEPT,\n acceptedFileTypes = ACCEPTED_FILE_TYPES,\n borderBeamTheme = "light",\n browseLabel = "Browse files",\n className,\n description = "PDF, DOC/DOCX, XLSX, CSV, PNG, or JPG",\n draggingLabel = "Drop to add",\n multiple = true,\n showBorderBeam = true,\n showFileList = true,\n title = "Click to upload or drop files",\n onFilesAccepted,\n onFilesChange,\n}: FileUploadProps) {\n const dragDepthRef = React.useRef(0)\n const inputRef = React.useRef<HTMLInputElement>(null)\n const [isDragging, setIsDragging] = React.useState(false)\n const [files, setFiles] = React.useState<FileUploadItem[]>([])\n const [rejectionMessage, setRejectionMessage] = React.useState<string | null>(\n null\n )\n\n const commitFiles = React.useCallback(\n (nextFiles: FileList | File[]) => {\n const acceptedFiles = Array.from(nextFiles)\n .filter((file) => matchesAccept(file, accept))\n .slice(0, multiple ? undefined : 1)\n\n if (acceptedFiles.length === 0) {\n setRejectionMessage("This file type is not supported here.")\n return\n }\n\n setRejectionMessage(null)\n onFilesAccepted?.(acceptedFiles)\n\n const items = toUploadItems(acceptedFiles)\n setFiles((previousFiles) => {\n previousFiles.forEach((file) => URL.revokeObjectURL(file.url))\n return items\n })\n onFilesChange?.(items)\n },\n [accept, multiple, onFilesAccepted, onFilesChange]\n )\n\n React.useEffect(() => {\n return () => {\n files.forEach((file) => URL.revokeObjectURL(file.url))\n }\n }, [files])\n\n const openFileDialog = React.useCallback(() => {\n inputRef.current?.click()\n }, [])\n\n const dropzone = (\n <div\n role="button"\n tabIndex={0}\n className={cn(\n "relative flex min-h-64 cursor-pointer flex-col items-center justify-center gap-5 overflow-hidden rounded-[1.125rem] border border-dashed bg-background px-6 py-10 text-center transition-[border-color,background-color] duration-200 ease-out",\n "motion-reduce:transition-none",\n isDragging\n ? "border-foreground/40 bg-accent/35"\n : "border-foreground/20 hover:border-foreground/35 hover:bg-muted/35 dark:border-foreground/25 dark:hover:border-foreground/40"\n )}\n onClick={openFileDialog}\n onDragEnter={(event) => {\n event.preventDefault()\n dragDepthRef.current += 1\n setIsDragging(true)\n }}\n onDragLeave={(event) => {\n event.preventDefault()\n dragDepthRef.current = Math.max(0, dragDepthRef.current - 1)\n if (dragDepthRef.current === 0) setIsDragging(false)\n }}\n onDragOver={(event) => event.preventDefault()}\n onDrop={(event) => {\n event.preventDefault()\n dragDepthRef.current = 0\n setIsDragging(false)\n if (event.dataTransfer.files.length > 0) {\n commitFiles(event.dataTransfer.files)\n }\n }}\n onKeyDown={(event) => {\n if (event.key === "Enter" || event.key === " ") {\n event.preventDefault()\n openFileDialog()\n }\n }}\n >\n <UploadIconCluster\n acceptedFileTypes={acceptedFileTypes}\n isDragging={isDragging}\n />\n <div className="space-y-1">\n <div className="text-sm font-medium">{title}</div>\n <div className="text-xs text-muted-foreground">{description}</div>\n {rejectionMessage ? (\n <div className="text-xs text-destructive">{rejectionMessage}</div>\n ) : null}\n </div>\n <div className="inline-flex items-center gap-2 rounded-full border bg-background px-3 py-1 text-xs text-muted-foreground">\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-3.5"\n />\n <span>{isDragging ? draggingLabel : browseLabel}</span>\n </div>\n <input\n ref={inputRef}\n type="file"\n accept={accept}\n multiple={multiple}\n className="hidden"\n onChange={(event) => {\n if (event.target.files) {\n commitFiles(event.target.files)\n event.currentTarget.value = ""\n }\n }}\n />\n </div>\n )\n\n return (\n <div className={cn("space-y-3", className)}>\n {showBorderBeam ? (\n <BorderBeam\n active={isDragging}\n borderRadius={18}\n brightness={2.4}\n className="rounded-[1.125rem]"\n colorVariant="ocean"\n duration={2.4}\n size="md"\n strength={1}\n theme={borderBeamTheme}\n >\n {dropzone}\n </BorderBeam>\n ) : (\n dropzone\n )}\n {showFileList && files.length > 0 ? (\n <div className="rounded-xl border bg-background">\n {files.map((file) => (\n <div\n key={file.id}\n className="flex items-center gap-3 border-b px-3 py-2.5 last:border-b-0"\n >\n <FileThumbnail\n file={{\n name: file.name,\n type: file.type,\n }}\n previewImageUrl={\n file.type.startsWith("image/") ? file.url : null\n }\n className="size-10 shrink-0 rounded-lg"\n />\n <div className="min-w-0 flex-1">\n <div className="truncate text-sm font-medium">{file.name}</div>\n <div className="truncate text-xs text-muted-foreground">\n {file.type} - {formatBytes(file.size)}\n </div>\n </div>\n <div className="rounded-full bg-muted px-2 py-1 text-xs text-muted-foreground">\n Ready\n </div>\n </div>\n ))}\n </div>\n ) : null}\n </div>\n )\n}\n'export function FileUploadSource() {return (diff --git a/apps/v4/components/icon-placeholder.tsx b/apps/v4/components/icon-placeholder.tsxnew file mode 100644index 0000000..a2494ec--- /dev/null+++ b/apps/v4/components/icon-placeholder.tsx@@ -0,0 +1,238 @@+import type React from "react"+import {+ Add01Icon,+ Alert01Icon,+ AlignBoxBottomCenterIcon,+ AlignBoxMiddleCenterIcon,+ AlignBoxTopCenterIcon,+ ArrowDown01Icon,+ ArrowExpandDiagonal01Icon,+ ArrowExpandDiagonal02Icon,+ ArrowLeft01Icon,+ ArrowRight01Icon,+ ArrowUp01Icon,+ ArrowUpDownIcon,+ BorderAll01Icon,+ BorderBottom01Icon,+ BorderHorizontalIcon,+ BorderInnerIcon,+ BorderLeft01Icon,+ BorderNone01Icon,+ BorderRight01Icon,+ BorderTop01Icon,+ BorderVerticalIcon,+ Calendar03Icon,+ Cancel01Icon,+ CancelCircleIcon,+ CellsIcon,+ CheckIcon,+ CheckmarkCircle01Icon,+ ChevronDown,+ ChevronDownIcon,+ ChevronUp,+ ColumnsThreeCogIcon,+ Comment01Icon,+ Delete02Icon,+ DollarCircleIcon,+ Download01Icon,+ DragDropVerticalIcon,+ DropletOffIcon,+ EditOffIcon,+ File01Icon,+ FileDiffIcon,+ FileImageIcon,+ FilePenIcon,+ FileSpreadsheetIcon,+ FileUploadIcon,+ FilterIcon,+ GalleryThumbnailsIcon,+ Grid2X2XIcon,+ GridViewIcon,+ Heading01Icon,+ HighlighterIcon,+ ImageAdd01Icon,+ ImageCompositionIcon,+ InformationCircleIcon,+ InputNumericIcon,+ InputTextIcon,+ LayoutThreeColumnIcon,+ LeftToRightListBulletIcon,+ LeftToRightListNumberIcon,+ LineIcon,+ Link02Icon,+ Loading03Icon,+ MinusSignCircleIcon,+ Moon02Icon,+ MoreHorizontalIcon,+ PaintBucketIcon,+ ParagraphIcon,+ PathfinderMergeIcon,+ Pen01Icon,+ PercentIcon,+ PlusSignCircleIcon,+ Redo02Icon,+ RotateClockwiseIcon,+ Search01Icon,+ SecondBracketIcon,+ SidebarLeftIcon,+ SourceCodeSquareIcon,+ Sun03Icon,+ Table01Icon,+ TableIcon,+ TableRowsSplitIcon,+ TextAlignCenterIcon,+ TextAlignJustifyLeftIcon,+ TextAlignLeft01Icon,+ TextAlignRight01Icon,+ TextBoldIcon,+ TextCenterlineCenterTopIcon,+ TextCheckIcon,+ TextColorIcon,+ TextItalicIcon,+ TextNumberSignIcon,+ TextStrikethroughIcon,+ TextSubscriptIcon,+ TextSuperscriptIcon,+ TextUnderlineIcon,+ TextWrapIcon,+ Tick02Icon,+ Undo02Icon,+ Upload01Icon,+} from "@hugeicons/core-free-icons"+import { HugeiconsIcon } from "@hugeicons/react"++// The registry source files reference icons through <IconPlaceholder /> with a+// per-library icon name for every icon library the shadcn CLI supports. At+// install time the CLI replaces the placeholder with the consumer's configured+// `iconLibrary` from components.json and strips this import. This component is+// only ever rendered on this docs site, which uses hugeicons.+//+// When a registry component starts using a new icon, add its hugeicons name+// here — the `hugeicons` prop is typed against this registry, so a missing+// entry is a type error.+const hugeicons = {+ Add01Icon,+ Alert01Icon,+ AlignBoxBottomCenterIcon,+ AlignBoxMiddleCenterIcon,+ AlignBoxTopCenterIcon,+ ArrowDown01Icon,+ ArrowExpandDiagonal01Icon,+ ArrowExpandDiagonal02Icon,+ ArrowLeft01Icon,+ ArrowRight01Icon,+ ArrowUp01Icon,+ ArrowUpDownIcon,+ BorderAll01Icon,+ BorderBottom01Icon,+ BorderHorizontalIcon,+ BorderInnerIcon,+ BorderLeft01Icon,+ BorderNone01Icon,+ BorderRight01Icon,+ BorderTop01Icon,+ BorderVerticalIcon,+ Calendar03Icon,+ Cancel01Icon,+ CancelCircleIcon,+ CellsIcon,+ CheckIcon,+ CheckmarkCircle01Icon,+ ChevronDown,+ ChevronDownIcon,+ ChevronUp,+ ColumnsThreeCogIcon,+ Comment01Icon,+ Delete02Icon,+ DollarCircleIcon,+ Download01Icon,+ DragDropVerticalIcon,+ DropletOffIcon,+ EditOffIcon,+ File01Icon,+ FileDiffIcon,+ FileImageIcon,+ FilePenIcon,+ FileSpreadsheetIcon,+ FileUploadIcon,+ FilterIcon,+ GalleryThumbnailsIcon,+ Grid2X2XIcon,+ GridViewIcon,+ Heading01Icon,+ HighlighterIcon,+ ImageAdd01Icon,+ ImageCompositionIcon,+ InformationCircleIcon,+ InputNumericIcon,+ InputTextIcon,+ LayoutThreeColumnIcon,+ LeftToRightListBulletIcon,+ LeftToRightListNumberIcon,+ LineIcon,+ Link02Icon,+ Loading03Icon,+ MinusSignCircleIcon,+ Moon02Icon,+ MoreHorizontalIcon,+ PaintBucketIcon,+ ParagraphIcon,+ PathfinderMergeIcon,+ Pen01Icon,+ PercentIcon,+ PlusSignCircleIcon,+ Redo02Icon,+ RotateClockwiseIcon,+ Search01Icon,+ SecondBracketIcon,+ SidebarLeftIcon,+ SourceCodeSquareIcon,+ Sun03Icon,+ Table01Icon,+ TableIcon,+ TableRowsSplitIcon,+ TextAlignCenterIcon,+ TextAlignJustifyLeftIcon,+ TextAlignLeft01Icon,+ TextAlignRight01Icon,+ TextBoldIcon,+ TextCenterlineCenterTopIcon,+ TextCheckIcon,+ TextColorIcon,+ TextItalicIcon,+ TextNumberSignIcon,+ TextStrikethroughIcon,+ TextSubscriptIcon,+ TextSuperscriptIcon,+ TextUnderlineIcon,+ TextWrapIcon,+ Tick02Icon,+ Undo02Icon,+ Upload01Icon,+}++export type IconPlaceholderProps = {+ lucide: string+ tabler: string+ hugeicons: keyof typeof hugeicons+ phosphor: string+ remixicon: string+} & React.ComponentProps<"svg">++export function IconPlaceholder(props: IconPlaceholderProps) {+ const {+ lucide: _lucide,+ tabler: _tabler,+ hugeicons: hugeiconsName,+ phosphor: _phosphor,+ remixicon: _remixicon,+ ...rest+ } = props++ return (+ <HugeiconsIcon+ icon={hugeicons[hugeiconsName]}+ {...(rest as Omit<React.ComponentProps<typeof HugeiconsIcon>, "icon">)}+ />+ )+}diff --git a/apps/v4/components/layout-blocks-docs.tsx b/apps/v4/components/layout-blocks-docs.tsxindex 6d40d9b..4521a8b 100644--- a/apps/v4/components/layout-blocks-docs.tsx+++ b/apps/v4/components/layout-blocks-docs.tsx@@ -8681,7 +8681,7 @@ export function OcrBlocksExample() {}`const ocrBlocksSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n AlignBoxBottomCenterIcon,\n Heading01Icon,\n ImageCompositionIcon,\n LeftToRightListBulletIcon,\n ParagraphIcon,\n Table01Icon,\n TextCenterlineCenterTopIcon,\n TextNumberSignIcon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { useVirtualizer } from "@tanstack/react-virtual"\nimport ReactMarkdown from "react-markdown"\nimport rehypeRaw from "rehype-raw"\nimport rehypeSanitize, { defaultSchema } from "rehype-sanitize"\nimport remarkGfm from "remark-gfm"\n\nimport { cn } from "@/lib/utils"\nimport { ScrollArea } from "@/components/ui/scroll-area"\n\nexport type Point = {\n x: number\n y: number\n}\n\nexport type BoundingBox = {\n left: number\n top: number\n right: number\n bottom: number\n}\n\nexport type OcrBlockType =\n | "heading"\n | "paragraph"\n | "list"\n | "table"\n | "figure"\n | "header"\n | "footer"\n | "page_number"\n\nexport type ParsedOcrBlock = {\n id: string\n type: string\n content: string\n metadata: {\n page: {\n number: number\n width: number\n height: number\n }\n layoutClass?: string\n minOcrConfidence?: number\n avgOcrConfidence?: number\n }\n polygon?: Point[]\n boundingBox?: BoundingBox\n}\n\nexport type ParsedOcrOutput = {\n chunks: {\n blocks: ParsedOcrBlock[]\n }[]\n}\n\nexport type OcrBlock = {\n id: string\n type: OcrBlockType\n text: string\n page: number\n pageWidth: number\n pageHeight: number\n confidence: number\n polygon?: Point[]\n boundingBox?: BoundingBox\n}\n\nexport type HighlightArea = {\n left: number\n top: number\n width: number\n height: number\n}\n\nexport const PDF_URL = "/samples/attention.pdf"\nconst OCR_BLOCK_ROW_MIN_ESTIMATE = 92\nconst OCR_BLOCK_ROW_VERTICAL_CHROME = 62\nconst OCR_BLOCK_LINE_HEIGHT = 20\nconst OCR_BLOCK_ESTIMATED_CHARS_PER_LINE = 42\nconst OCR_BLOCK_ROW_GAP = 8\nconst OCR_BLOCK_LIST_PADDING = 12\nconst OCR_MARKDOWN_SCHEMA = {\n ...defaultSchema,\n attributes: {\n ...defaultSchema.attributes,\n figure: [...(defaultSchema.attributes?.figure ?? []), "type"],\n },\n tagNames: [\n ...(defaultSchema.tagNames ?? []),\n "caption",\n "figcaption",\n "figure",\n ],\n}\nconst OCR_MARKDOWN_REHYPE_PLUGINS: NonNullable<\n React.ComponentProps<typeof ReactMarkdown>["rehypePlugins"]\n> = [rehypeRaw, [rehypeSanitize, OCR_MARKDOWN_SCHEMA]]\nconst OCR_MARKDOWN_REMARK_PLUGINS: NonNullable<\n React.ComponentProps<typeof ReactMarkdown>["remarkPlugins"]\n> = [remarkGfm]\nconst OCR_MARKDOWN_FIGURE_CAPTION_PATTERN = /<\\/?caption>/gi\n\nfunction getEstimatedOcrBlockRowHeight(block: OcrBlock) {\n const plainText = block.text\n .replace(OCR_MARKDOWN_FIGURE_CAPTION_PATTERN, "")\n .replace(/<[^>]*>/g, "")\n .replace(/\\s+/g, " ")\n .trim()\n const explicitLineCount = block.text.split(/\\n+/).filter(Boolean).length\n const wrappedLineCount = Math.max(\n explicitLineCount,\n Math.ceil(plainText.length / OCR_BLOCK_ESTIMATED_CHARS_PER_LINE)\n )\n const contentHeight = Math.max(1, wrappedLineCount) * OCR_BLOCK_LINE_HEIGHT\n const typeExtraHeight =\n block.type === "figure" ? 44 : block.type === "table" ? 28 : 0\n\n return Math.max(\n OCR_BLOCK_ROW_MIN_ESTIMATE,\n OCR_BLOCK_ROW_VERTICAL_CHROME +\n contentHeight +\n typeExtraHeight +\n OCR_BLOCK_ROW_GAP\n )\n}\n\nexport const ATTENTION_OCR_OUTPUT = {\n chunks: [\n {\n blocks: [\n {\n id: "block_1_IKDP4i",\n type: "header",\n content: "arXiv:1706.03762v7 [cs.CL] 2 Aug 2023",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Header",\n minOcrConfidence: 0.959,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 36.16179897837395,\n y: 447.38040863840206,\n },\n {\n x: 75.85163708150822,\n y: 447.38040863840206,\n },\n {\n x: 75.85163708150822,\n y: 1155.1796566956025,\n },\n {\n x: 36.16179897837395,\n y: 1155.1796566956025,\n },\n ],\n boundingBox: {\n left: 36.16179897837395,\n top: 447.38040863840206,\n right: 75.85163708150822,\n bottom: 1155.1796566956025,\n },\n },\n {\n id: "block_1_rtNdsr",\n type: "header",\n content:\n "Provided proper attribution is provided, Google hereby grants permission to reproduce the tables and figures in this paper solely for use in journalistic or scholarly works.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Header",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 258.50183528705236,\n y: 151.7837261257315,\n },\n {\n x: 1016.8830982960054,\n y: 151.7837261257315,\n },\n {\n x: 1016.8830982960054,\n y: 233.84929126366637,\n },\n {\n x: 258.50183528705236,\n y: 233.84929126366637,\n },\n ],\n boundingBox: {\n left: 258.50183528705236,\n top: 151.7837261257315,\n right: 1016.8830982960054,\n bottom: 233.84929126366637,\n },\n },\n {\n id: "block_1_eo9AoV",\n type: "heading",\n content: "# Attention Is All You Need",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 440.0215455215343,\n y: 312.01490975860366,\n },\n {\n x: 831.4373211268961,\n y: 312.01490975860366,\n },\n {\n x: 831.4373211268961,\n y: 339.0022611402928,\n },\n {\n x: 440.0215455215343,\n y: 339.0022611402928,\n },\n ],\n boundingBox: {\n left: 440.0215455215343,\n top: 312.01490975860366,\n right: 831.4373211268961,\n bottom: 339.0022611402928,\n },\n },\n {\n id: "block_1_Kdt5Cu",\n type: "text",\n content: "Ashish Vaswani* Google Brain [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.977,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 242.9606625633518,\n y: 490.4495616712068,\n },\n {\n x: 449.64758323056856,\n y: 490.4495616712068,\n },\n {\n x: 449.64758323056856,\n y: 555.9028907431696,\n },\n {\n x: 242.9606625633518,\n y: 555.9028907431696,\n },\n ],\n boundingBox: {\n left: 242.9606625633518,\n top: 490.4495616712068,\n right: 449.64758323056856,\n bottom: 555.9028907431696,\n },\n },\n {\n id: "block_1_6Xv6uR",\n type: "text",\n content: "Llion Jones* Google Research [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.927,\n avgOcrConfidence: 0.982,\n },\n polygon: [\n {\n x: 264.3723327748097,\n y: 594.5307239733245,\n },\n {\n x: 438.3605845653227,\n y: 594.5307239733245,\n },\n {\n x: 438.3605845653227,\n y: 660.7685646688132,\n },\n {\n x: 264.3723327748097,\n y: 660.7685646688132,\n },\n ],\n boundingBox: {\n left: 264.3723327748097,\n top: 594.5307239733245,\n right: 438.3605845653227,\n bottom: 660.7685646688132,\n },\n },\n {\n id: "block_1_Lx35WU",\n type: "text",\n content: "Noam Shazeer* Google Brain [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.983,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 479.08373644752226,\n y: 490.1169480632122,\n },\n {\n x: 643.7573955006842,\n y: 490.1169480632122,\n },\n {\n x: 643.7573955006842,\n y: 556.2343205043247,\n },\n {\n x: 479.08373644752226,\n y: 556.2343205043247,\n },\n ],\n boundingBox: {\n left: 479.08373644752226,\n top: 490.1169480632122,\n right: 643.7573955006842,\n bottom: 556.2343205043247,\n },\n },\n {\n id: "block_1_VxOJIL",\n type: "text",\n content:\n "Aidan N. Gomez* * University of Toronto [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.095,\n avgOcrConfidence: 0.875,\n },\n polygon: [\n {\n x: 489.9820146769503,\n y: 593.5908916444707,\n },\n {\n x: 708.1676900821881,\n y: 593.5908916444707,\n },\n {\n x: 708.1676900821881,\n y: 657.7173651788468,\n },\n {\n x: 489.9820146769503,\n y: 657.7173651788468,\n },\n ],\n boundingBox: {\n left: 489.9820146769503,\n top: 593.5908916444707,\n right: 708.1676900821881,\n bottom: 657.7173651788468,\n },\n },\n {\n id: "block_1_m1Gb17",\n type: "text",\n content: "Niki Parmar* Google Research [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 673.3537325893875,\n y: 490.2837284059453,\n },\n {\n x: 848.6601168221802,\n y: 490.2837284059453,\n },\n {\n x: 848.6601168221802,\n y: 556.287735673718,\n },\n {\n x: 673.3537325893875,\n y: 556.287735673718,\n },\n ],\n boundingBox: {\n left: 673.3537325893875,\n top: 490.2837284059453,\n right: 848.6601168221802,\n bottom: 556.287735673718,\n },\n },\n {\n id: "block_1_otnY8T",\n type: "text",\n content: "\\u0141ukasz Kaiser* Google Brain [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.984,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 759.3324257509552,\n y: 594.2661578816579,\n },\n {\n x: 1011.1333304078039,\n y: 594.2661578816579,\n },\n {\n x: 1011.1333304078039,\n y: 660.9298993160851,\n },\n {\n x: 759.3324257509552,\n y: 660.9298993160851,\n },\n ],\n boundingBox: {\n left: 759.3324257509552,\n top: 594.2661578816579,\n right: 1011.1333304078039,\n bottom: 660.9298993160851,\n },\n },\n {\n id: "block_1_ICaos6",\n type: "text",\n content: "Illia Polosukhin* * [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.107,\n avgOcrConfidence: 0.766,\n },\n polygon: [\n {\n x: 495.9563429338219,\n y: 697.325802423004,\n },\n {\n x: 778.5449758933407,\n y: 697.325802423004,\n },\n {\n x: 778.5449758933407,\n y: 742.1158899292909,\n },\n {\n x: 495.9563429338219,\n y: 742.1158899292909,\n },\n ],\n boundingBox: {\n left: 495.9563429338219,\n top: 697.325802423004,\n right: 778.5449758933407,\n bottom: 742.1158899292909,\n },\n },\n {\n id: "block_1_zNN0g5",\n type: "section_heading",\n content: "### Abstract",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 590.8429918498018,\n y: 804.3203170891095,\n },\n {\n x: 683.8031267597728,\n y: 804.3203170891095,\n },\n {\n x: 683.8031267597728,\n y: 823.7656170264223,\n },\n {\n x: 590.8429918498018,\n y: 823.7656170264223,\n },\n ],\n boundingBox: {\n left: 590.8429918498018,\n top: 804.3203170891095,\n right: 683.8031267597728,\n bottom: 823.7656170264223,\n },\n },\n {\n id: "block_1_Pzc7ia",\n type: "text",\n content:\n "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014 English- to-German translation task, improving over the existing best results, including ensembles, by over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training costs of the best models from the literature. We show that the Transformer generalizes well to other tasks by applying it successfully to English constituency parsing both with large and limited training data.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.987,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 298.2268201173657,\n y: 861.5167879950731,\n },\n {\n x: 978.0244980415288,\n y: 861.5167879950731,\n },\n {\n x: 978.0244980415288,\n y: 1201.6481075430274,\n },\n {\n x: 298.2268201173657,\n y: 1201.6481075430274,\n },\n ],\n boundingBox: {\n left: 298.2268201173657,\n top: 861.5167879950731,\n right: 978.0244980415288,\n bottom: 1201.6481075430274,\n },\n },\n {\n id: "block_1_bHnLKj",\n type: "text",\n content:\n "*Equal contribution. Listing order is random. Jakob proposed replacing RNNs with self-attention and started the effort to evaluate this idea. Ashish, with Illia, designed and implemented the first Transformer models and has been crucially involved in every aspect of this work. Noam proposed scaled dot-product attention, multi-head attention and the parameter-free position representation and became the other person involved in nearly every detail. Niki designed, implemented, tuned and evaluated countless model variants in our original codebase and tensor2tensor. Llion also experimented with novel model variants, was responsible for our initial codebase, and efficient inference and visualizations. Lukasz and Aidan spent countless long days designing various parts of and implementing tensor2tensor, replacing our earlier codebase, greatly improving results and massively accelerating our research.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.951,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.8755505415645,\n y: 1247.2573697082978,\n },\n {\n x: 1049.6971241749116,\n y: 1247.2573697082978,\n },\n {\n x: 1049.6971241749116,\n y: 1429.7100451476592,\n },\n {\n x: 222.8755505415645,\n y: 1429.7100451476592,\n },\n ],\n boundingBox: {\n left: 222.8755505415645,\n top: 1247.2573697082978,\n right: 1049.6971241749116,\n bottom: 1429.7100451476592,\n },\n },\n {\n id: "block_1_J3Olku",\n type: "text",\n content: "+ Work performed while at Google Brain.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.11,\n avgOcrConfidence: 0.869,\n },\n polygon: [\n {\n x: 250.1677060649343,\n y: 1434.3817888991277,\n },\n {\n x: 555.1793119333087,\n y: 1434.3817888991277,\n },\n {\n x: 555.1793119333087,\n y: 1456.532320926064,\n },\n {\n x: 250.1677060649343,\n y: 1456.532320926064,\n },\n ],\n boundingBox: {\n left: 250.1677060649343,\n top: 1434.3817888991277,\n right: 555.1793119333087,\n bottom: 1456.532320926064,\n },\n },\n {\n id: "block_1_aQsakB",\n type: "text",\n content: "#Work performed while at Google Research.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.652,\n avgOcrConfidence: 0.94,\n },\n polygon: [\n {\n x: 249.36288151427775,\n y: 1458.4100914288283,\n },\n {\n x: 582.4047478446125,\n y: 1458.4100914288283,\n },\n {\n x: 582.4047478446125,\n y: 1479.773507369192,\n },\n {\n x: 249.36288151427775,\n y: 1479.773507369192,\n },\n ],\n boundingBox: {\n left: 249.36288151427775,\n top: 1458.4100914288283,\n right: 582.4047478446125,\n bottom: 1479.773507369192,\n },\n },\n {\n id: "block_1_iKp4Ae",\n type: "footer",\n content:\n "31st Conference on Neural Information Processing Systems (NIPS 2017), Long Beach, CA, USA.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Footer",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.27405893367575,\n y: 1527.1945287374626,\n },\n {\n x: 958.2568426201814,\n y: 1527.1945287374626,\n },\n {\n x: 958.2568426201814,\n y: 1546.3855383736748,\n },\n {\n x: 224.27405893367575,\n y: 1546.3855383736748,\n },\n ],\n boundingBox: {\n left: 224.27405893367575,\n top: 1527.1945287374626,\n right: 958.2568426201814,\n bottom: 1546.3855383736748,\n },\n },\n {\n id: "block_1_zPHQaR",\n type: "text",\n content: "Jakob Uszkoreit* Google Research [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 879.2488933479699,\n y: 489.58686880240765,\n },\n {\n x: 1035.003756780694,\n y: 489.58686880240765,\n },\n {\n x: 1035.003756780694,\n y: 555.848623204052,\n },\n {\n x: 879.2488933479699,\n y: 555.848623204052,\n },\n ],\n boundingBox: {\n left: 879.2488933479699,\n top: 489.58686880240765,\n right: 1035.003756780694,\n bottom: 555.848623204052,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_2_UD1C1k",\n type: "heading",\n content: "# 1 Introduction",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 225.86025321570625,\n y: 152.1792611932396,\n },\n {\n x: 396.86960095036636,\n y: 152.1792611932396,\n },\n {\n x: 396.86960095036636,\n y: 171.96800693712737,\n },\n {\n x: 225.86025321570625,\n y: 171.96800693712737,\n },\n ],\n boundingBox: {\n left: 225.86025321570625,\n top: 152.1792611932396,\n right: 396.86960095036636,\n bottom: 171.96800693712737,\n },\n },\n {\n id: "block_2_C25o9D",\n type: "text",\n content:\n "Recurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks in particular, have been firmly established as state of the art approaches in sequence modeling and transduction problems such as language modeling and machine translation [35, 2, 5]. Numerous efforts have since continued to push the boundaries of recurrent language models and encoder-decoder architectures [38, 24, 15].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 223.64054213475134,\n y: 206.4059457563816,\n },\n {\n x: 1050.9159227357293,\n y: 206.4059457563816,\n },\n {\n x: 1050.9159227357293,\n y: 316.89823061720773,\n },\n {\n x: 223.64054213475134,\n y: 316.89823061720773,\n },\n ],\n boundingBox: {\n left: 223.64054213475134,\n top: 206.4059457563816,\n right: 1050.9159227357293,\n bottom: 316.89823061720773,\n },\n },\n {\n id: "block_2_Cw1VyU",\n type: "text",\n content:\n "Recurrent models typically factor computation along the symbol positions of the input and output sequences. Aligning the positions to steps in computation time, they generate a sequence of hidden states ht, as a function of the previous hidden state ht-1 and the input for position t. This inherently sequential nature precludes parallelization within training examples, which becomes critical at longer sequence lengths, as memory constraints limit batching across examples. Recent work has achieved significant improvements in computational efficiency through factorization tricks [21] and conditional computation [32], while also improving model performance in case of the latter. The fundamental constraint of sequential computation, however, remains.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.9,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.69928568819142,\n y: 331.227654822787,\n },\n {\n x: 1049.6158961832089,\n y: 331.227654822787,\n },\n {\n x: 1049.6158961832089,\n y: 511.80734250061494,\n },\n {\n x: 223.69928568819142,\n y: 511.80734250061494,\n },\n ],\n boundingBox: {\n left: 223.69928568819142,\n top: 331.227654822787,\n right: 1049.6158961832089,\n bottom: 511.80734250061494,\n },\n },\n {\n id: "block_2_FR7zlH",\n type: "text",\n content:\n "Attention mechanisms have become an integral part of compelling sequence modeling and transduc- tion models in various tasks, allowing modeling of dependencies without regard to their distance in the input or output sequences [2, 19]. In all but a few cases [27], however, such attention mechanisms are used in conjunction with a recurrent network.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.959,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.38852708357095,\n y: 525.5238181666324,\n },\n {\n x: 1052.1732525233804,\n y: 525.5238181666324,\n },\n {\n x: 1052.1732525233804,\n y: 613.7107948647406,\n },\n {\n x: 223.38852708357095,\n y: 613.7107948647406,\n },\n ],\n boundingBox: {\n left: 223.38852708357095,\n top: 525.5238181666324,\n right: 1052.1732525233804,\n bottom: 613.7107948647406,\n },\n },\n {\n id: "block_2_ZyhlFh",\n type: "text",\n content:\n "In this work we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output. The Transformer allows for significantly more parallelization and can reach a new state of the art in translation quality after being trained for as little as twelve hours on eight P100 GPUs.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.991,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.20226126343667,\n y: 627.2328828797304,\n },\n {\n x: 1052.7354108156078,\n y: 627.2328828797304,\n },\n {\n x: 1052.7354108156078,\n y: 716.0174654623619,\n },\n {\n x: 223.20226126343667,\n y: 716.0174654623619,\n },\n ],\n boundingBox: {\n left: 223.20226126343667,\n top: 627.2328828797304,\n right: 1052.7354108156078,\n bottom: 716.0174654623619,\n },\n },\n {\n id: "block_2_MZBXjP",\n type: "section_heading",\n content: "### 2 Background",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.22355178498873,\n y: 757.4257287333783,\n },\n {\n x: 392.45446198178036,\n y: 757.4257287333783,\n },\n {\n x: 392.45446198178036,\n y: 781.2853567654029,\n },\n {\n x: 224.22355178498873,\n y: 781.2853567654029,\n },\n ],\n boundingBox: {\n left: 224.22355178498873,\n top: 757.4257287333783,\n right: 392.45446198178036,\n bottom: 781.2853567654029,\n },\n },\n {\n id: "block_2_JeOnOk",\n type: "text",\n content:\n "The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU [16], ByteNet [18] and ConvS2S [9], all of which use convolutional neural networks as basic building block, computing hidden representations in parallel for all input and output positions. In these models, the number of operations required to relate signals from two arbitrary input or output positions grows in the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes it more difficult to learn dependencies between distant positions [12]. In the Transformer this is reduced to a constant number of operations, albeit at the cost of reduced effective resolution due to averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as described in section 3.2.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.893,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.30221050847186,\n y: 810.9956032315591,\n },\n {\n x: 1051.187440078624,\n y: 810.9956032315591,\n },\n {\n x: 1051.187440078624,\n y: 1010.7095232511822,\n },\n {\n x: 223.30221050847186,\n y: 1010.7095232511822,\n },\n ],\n boundingBox: {\n left: 223.30221050847186,\n top: 810.9956032315591,\n right: 1051.187440078624,\n bottom: 1010.7095232511822,\n },\n },\n {\n id: "block_2_tEzlrD",\n type: "text",\n content:\n "Self-attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence. Self-attention has been used successfully in a variety of tasks including reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations [4, 27, 28, 22].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.984,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.00045882176306,\n y: 1028.0413251030714,\n },\n {\n x: 1051.4467448213675,\n y: 1028.0413251030714,\n },\n {\n x: 1051.4467448213675,\n y: 1116.9915041815966,\n },\n {\n x: 224.00045882176306,\n y: 1116.9915041815966,\n },\n ],\n boundingBox: {\n left: 224.00045882176306,\n top: 1028.0413251030714,\n right: 1051.4467448213675,\n bottom: 1116.9915041815966,\n },\n },\n {\n id: "block_2_AFJ4ch",\n type: "text",\n content:\n "End-to-end memory networks are based on a recurrent attention mechanism instead of sequence- aligned recurrence and have been shown to perform well on simple-language question answering and language modeling tasks [34].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.05524984763485,\n y: 1129.9793457949072,\n },\n {\n x: 1052.8165441359918,\n y: 1129.9793457949072,\n },\n {\n x: 1052.8165441359918,\n y: 1196.1117767678168,\n },\n {\n x: 224.05524984763485,\n y: 1196.1117767678168,\n },\n ],\n boundingBox: {\n left: 224.05524984763485,\n top: 1129.9793457949072,\n right: 1052.8165441359918,\n bottom: 1196.1117767678168,\n },\n },\n {\n id: "block_2_CBbJP3",\n type: "text",\n content:\n "To the best of our knowledge, however, the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence- aligned RNNs or convolution. In the following sections, we will describe the Transformer, motivate self-attention and discuss its advantages over models such as [17, 18] and [9].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.898,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 222.86987026242443,\n y: 1210.5673043387276,\n },\n {\n x: 1052.2374396776631,\n y: 1210.5673043387276,\n },\n {\n x: 1052.2374396776631,\n y: 1298.352294004053,\n },\n {\n x: 222.86987026242443,\n y: 1298.352294004053,\n },\n ],\n boundingBox: {\n left: 222.86987026242443,\n top: 1210.5673043387276,\n right: 1052.2374396776631,\n bottom: 1298.352294004053,\n },\n },\n {\n id: "block_2_RlRHBW",\n type: "section_heading",\n content: "### 3 Model Architecture",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.20267675914906,\n y: 1339.2827093368187,\n },\n {\n x: 470.2105250671832,\n y: 1339.2827093368187,\n },\n {\n x: 470.2105250671832,\n y: 1359.0320211424864,\n },\n {\n x: 224.20267675914906,\n y: 1359.0320211424864,\n },\n ],\n boundingBox: {\n left: 224.20267675914906,\n top: 1339.2827093368187,\n right: 470.2105250671832,\n bottom: 1359.0320211424864,\n },\n },\n {\n id: "block_2_OhVaOm",\n type: "text",\n content:\n "Most competitive neural sequence transduction models have an encoder-decoder structure [5, 2, 35]. Here, the encoder maps an input sequence of symbol representations (x1, ... , In) to a sequence of continuous representations z = (Z1, ... , Zn). Given z, the decoder then generates an output sequence (31, ... , ym) of symbols one element at a time. At each step the model is auto-regressive [10], consuming the previously generated symbols as additional input when generating the next.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.619,\n avgOcrConfidence: 0.969,\n },\n polygon: [\n {\n x: 223.9033023806384,\n y: 1394.2295871247027,\n },\n {\n x: 1051.703398767179,\n y: 1394.2295871247027,\n },\n {\n x: 1051.703398767179,\n y: 1505.850527885265,\n },\n {\n x: 223.9033023806384,\n y: 1505.850527885265,\n },\n ],\n boundingBox: {\n left: 223.9033023806384,\n top: 1394.2295871247027,\n right: 1051.703398767179,\n bottom: 1505.850527885265,\n },\n },\n {\n id: "block_2_MzhUlf",\n type: "page_number",\n content: "2",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 631.4816022441336,\n y: 1547.6769732138268,\n },\n {\n x: 642.0810031194757,\n y: 1547.6769732138268,\n },\n {\n x: 642.0810031194757,\n y: 1563.2578182363868,\n },\n {\n x: 631.4816022441336,\n y: 1563.2578182363868,\n },\n ],\n boundingBox: {\n left: 631.4816022441336,\n top: 1547.6769732138268,\n right: 642.0810031194757,\n bottom: 1563.2578182363868,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_3_afwbz8",\n type: "figure",\n content:\n \'<figure type="diagram">\\nOutput Probabilities\\n\\nSoftmax\\n\\nLinear\\n\\nAdd & Norm Feed Forward\\n\\nAdd & Norm\\n\\nAdd & Norm\\n\\nMulti-Head Feed Attention Forward Nx\\n\\nAdd & Norm\\n\\nNx Add & Norm\\n\\nMasked Multi-Head Multi-Head Attention Attention\\n\\nPositional Positional Encoding Encoding Input Output Embedding Embedding\\n\\nInputs Outputs (shifted right)\\n<caption>Transformer Architecture Diagram\\n\\nLeft Side: Encoder (Nx)\\n- Inputs\\n\\u2193\\n- Input Embedding\\n\\u2193\\n- Positional Encoding (added to Input Embedding)\\n\\u2193\\n- Multi-Head Attention\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Feed Forward\\n\\u2193\\n- Add & Norm\\n\\nRight Side: Decoder (Nx)\\n- Outputs (shifted right)\\n\\u2193\\n- Output Embedding\\n\\u2193\\n- Positional Encoding (added to Output Embedding)\\n\\u2193\\n- Masked Multi-Head Attention\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Multi-Head Attention (receives input from Encoder\\\'s Add & Norm)\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Feed Forward\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Linear\\n\\u2193\\n- Softmax\\n\\u2193\\n- Output Probabilities</caption>\\n</figure>\',\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.868,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 409.83791490540887,\n y: 150.86351013900642,\n },\n {\n x: 863.1759754932709,\n y: 150.86351013900642,\n },\n {\n x: 863.1759754932709,\n y: 821.7723977798806,\n },\n {\n x: 409.83791490540887,\n y: 821.7723977798806,\n },\n ],\n boundingBox: {\n left: 409.83791490540887,\n top: 150.86351013900642,\n right: 863.1759754932709,\n bottom: 821.7723977798806,\n },\n },\n {\n id: "block_3_1WIk1S",\n type: "text",\n content: "Figure 1: The Transformer - model architecture.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 436.4703770101505,\n y: 843.2910397178248,\n },\n {\n x: 836.1937028648209,\n y: 843.2910397178248,\n },\n {\n x: 836.1937028648209,\n y: 863.7018851373429,\n },\n {\n x: 436.4703770101505,\n y: 863.7018851373429,\n },\n ],\n boundingBox: {\n left: 436.4703770101505,\n top: 843.2910397178248,\n right: 836.1937028648209,\n bottom: 863.7018851373429,\n },\n },\n {\n id: "block_3_jyPEOL",\n type: "text",\n content:\n "The Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1, respectively.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.973,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.86804783953366,\n y: 910.1303693154701,\n },\n {\n x: 1051.9256870241932,\n y: 910.1303693154701,\n },\n {\n x: 1051.9256870241932,\n y: 977.3362178945899,\n },\n {\n x: 222.86804783953366,\n y: 977.3362178945899,\n },\n ],\n boundingBox: {\n left: 222.86804783953366,\n top: 910.1303693154701,\n right: 1051.9256870241932,\n bottom: 977.3362178945899,\n },\n },\n {\n id: "block_3_nEQfm1",\n type: "section_heading",\n content: "### 3.1 Encoder and Decoder Stacks",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.72352154585568,\n y: 1007.3903008367782,\n },\n {\n x: 527.4041196725664,\n y: 1007.3903008367782,\n },\n {\n x: 527.4041196725664,\n y: 1023.9329030316575,\n },\n {\n x: 223.72352154585568,\n y: 1023.9329030316575,\n },\n ],\n boundingBox: {\n left: 223.72352154585568,\n top: 1007.3903008367782,\n right: 527.4041196725664,\n bottom: 1023.9329030316575,\n },\n },\n {\n id: "block_3_W2U9b2",\n type: "text",\n content:\n "Encoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position- wise fully connected feed-forward network. We employ a residual connection [11] around each of the two sub-layers, followed by layer normalization [1]. That is, the output of each sub-layer is LayerNorm(x + Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer itself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding layers, produce outputs of dimension dmodel = 512.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.657,\n avgOcrConfidence: 0.984,\n },\n polygon: [\n {\n x: 223.8025010937322,\n y: 1048.091523421438,\n },\n {\n x: 1053.5889674277203,\n y: 1048.091523421438,\n },\n {\n x: 1053.5889674277203,\n y: 1206.3018568225373,\n },\n {\n x: 223.8025010937322,\n y: 1206.3018568225373,\n },\n ],\n boundingBox: {\n left: 223.8025010937322,\n top: 1048.091523421438,\n right: 1053.5889674277203,\n bottom: 1206.3018568225373,\n },\n },\n {\n id: "block_3_8wxg0F",\n type: "text",\n content:\n "Decoder: The decoder is also composed of a stack of N = 6 identical layers. In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head attention over the output of the encoder stack. Similar to the encoder, we employ residual connections around each of the sub-layers, followed by layer normalization. We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position i can depend only on the known outputs at positions less than i.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.633,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 224.16407452882643,\n y: 1233.3413921729066,\n },\n {\n x: 1049.721170689938,\n y: 1233.3413921729066,\n },\n {\n x: 1049.721170689938,\n y: 1391.0596241198086,\n },\n {\n x: 224.16407452882643,\n y: 1391.0596241198086,\n },\n ],\n boundingBox: {\n left: 224.16407452882643,\n top: 1233.3413921729066,\n right: 1049.721170689938,\n bottom: 1391.0596241198086,\n },\n },\n {\n id: "block_3_i0stGS",\n type: "section_heading",\n content: "### 3.2 Attention",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 224.0832962258889,\n y: 1421.7722100279386,\n },\n {\n x: 354.57085797386446,\n y: 1421.7722100279386,\n },\n {\n x: 354.57085797386446,\n y: 1437.668053017523,\n },\n {\n x: 224.0832962258889,\n y: 1437.668053017523,\n },\n ],\n boundingBox: {\n left: 224.0832962258889,\n top: 1421.7722100279386,\n right: 354.57085797386446,\n bottom: 1437.668053017523,\n },\n },\n {\n id: "block_3_LwJLS3",\n type: "text",\n content:\n "An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.986,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.38670466068018,\n y: 1462.3713376611695,\n },\n {\n x: 1052.432178580848,\n y: 1462.3713376611695,\n },\n {\n x: 1052.432178580848,\n y: 1506.3117546138906,\n },\n {\n x: 223.38670466068018,\n y: 1506.3117546138906,\n },\n ],\n boundingBox: {\n left: 223.38670466068018,\n top: 1462.3713376611695,\n right: 1052.432178580848,\n bottom: 1506.3117546138906,\n },\n },\n {\n id: "block_3_gqT8MC",\n type: "page_number",\n content: "3",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.997,\n avgOcrConfidence: 0.997,\n },\n polygon: [\n {\n x: 632.2706403523466,\n y: 1547.236487481827,\n },\n {\n x: 642.0801037419451,\n y: 1547.236487481827,\n },\n {\n x: 642.0801037419451,\n y: 1562.977578012567,\n },\n {\n x: 632.2706403523466,\n y: 1562.977578012567,\n },\n ],\n boundingBox: {\n left: 632.2706403523466,\n top: 1547.236487481827,\n right: 642.0801037419451,\n bottom: 1562.977578012567,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_4_PplY2k",\n type: "header",\n content: "Scaled Dot-Product Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Header",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 307.9120037329458,\n y: 148.57123934236685,\n },\n {\n x: 554.1308270753735,\n y: 148.57123934236685,\n },\n {\n x: 554.1308270753735,\n y: 164.4924521697195,\n },\n {\n x: 307.9120037329458,\n y: 164.4924521697195,\n },\n ],\n boundingBox: {\n left: 307.9120037329458,\n top: 148.57123934236685,\n right: 554.1308270753735,\n bottom: 164.4924521697195,\n },\n },\n {\n id: "block_4_TZACGH",\n type: "text",\n content: "Multi-Head Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 756.6973442578839,\n y: 148.30866211339045,\n },\n {\n x: 937.5759876557511,\n y: 148.30866211339045,\n },\n {\n x: 937.5759876557511,\n y: 164.44492071911804,\n },\n {\n x: 756.6973442578839,\n y: 164.44492071911804,\n },\n ],\n boundingBox: {\n left: 756.6973442578839,\n top: 148.30866211339045,\n right: 937.5759876557511,\n bottom: 164.44492071911804,\n },\n },\n {\n id: "block_4_yRQL9Y",\n type: "figure",\n content:\n \'<figure type="diagram">\\n1 MatMul\\n\\n1 SoftMax 1 Mask (opt.) 1 Scale 1 MatMul 1 1 Q K V\\n<caption>Scaled Dot-Product Attention Diagram\\n\\nInputs: Q, K, V\\n\\n1. MatMul (Q, K)\\n \\u2193\\n2. Scale\\n \\u2193\\n3. Mask (opt.)\\n \\u2193\\n4. SoftMax\\n \\u2193\\n5. MatMul (Result of SoftMax, V)\\n \\u2193\\nOutput</caption>\\n</figure>\',\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.226,\n avgOcrConfidence: 0.815,\n },\n polygon: [\n {\n x: 364.7714322500855,\n y: 195.77549835434533,\n },\n {\n x: 497.28713766501767,\n y: 195.77549835434533,\n },\n {\n x: 497.28713766501767,\n y: 457.62115733784844,\n },\n {\n x: 364.7714322500855,\n y: 457.62115733784844,\n },\n ],\n boundingBox: {\n left: 364.7714322500855,\n top: 195.77549835434533,\n right: 497.28713766501767,\n bottom: 457.62115733784844,\n },\n },\n {\n id: "block_4_goCdts",\n type: "figure",\n content:\n \'<figure type="diagram">\\nLinear\\n\\nConcat\\n\\nScaled Dot-Product\\n\\nh\\n\\nAttention\\n\\nLinear Linear Linear\\n\\nV K Q\\n<caption>Multi-Head Attention\\n\\nInputs: V, K, Q\\n\\u2193\\nLinear (x3) \\u2192 Scaled Dot-Product Attention (h heads)\\n\\u2193\\nConcat\\n\\u2193\\nLinear</caption>\\n</figure>\',\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.981,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 723.0441991430129,\n y: 171.2063080421964,\n },\n {\n x: 971.0292342805515,\n y: 171.2063080421964,\n },\n {\n x: 971.0292342805515,\n y: 495.8982404264292,\n },\n {\n x: 723.0441991430129,\n y: 495.8982404264292,\n },\n ],\n boundingBox: {\n left: 723.0441991430129,\n top: 171.2063080421964,\n right: 971.0292342805515,\n bottom: 495.8982404264292,\n },\n },\n {\n id: "block_4_ZQ6XHX",\n type: "text",\n content:\n "Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.991,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.32437673972473,\n y: 572.2067347074809,\n },\n {\n x: 1050.060662039875,\n y: 572.2067347074809,\n },\n {\n x: 1050.060662039875,\n y: 615.706381804961,\n },\n {\n x: 224.32437673972473,\n y: 615.706381804961,\n },\n ],\n boundingBox: {\n left: 224.32437673972473,\n top: 572.2067347074809,\n right: 1050.060662039875,\n bottom: 615.706381804961,\n },\n },\n {\n id: "block_4_seZO33",\n type: "text",\n content:\n "of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.44408862260138,\n y: 661.3754045586836,\n },\n {\n x: 1049.3653012018135,\n y: 661.3754045586836,\n },\n {\n x: 1049.3653012018135,\n y: 705.0281940833071,\n },\n {\n x: 224.44408862260138,\n y: 705.0281940833071,\n },\n ],\n boundingBox: {\n left: 224.44408862260138,\n top: 661.3754045586836,\n right: 1049.3653012018135,\n bottom: 705.0281940833071,\n },\n },\n {\n id: "block_4_CMgLHk",\n type: "section_heading",\n content: "### 3.2.1 Scaled Dot-Product Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.53467593227862,\n y: 732.4767248397483,\n },\n {\n x: 549.2687448097842,\n y: 732.4767248397483,\n },\n {\n x: 549.2687448097842,\n y: 748.6887496431967,\n },\n {\n x: 223.53467593227862,\n y: 748.6887496431967,\n },\n ],\n boundingBox: {\n left: 223.53467593227862,\n top: 732.4767248397483,\n right: 549.2687448097842,\n bottom: 748.6887496431967,\n },\n },\n {\n id: "block_4_fmfLoy",\n type: "text",\n content:\n \'We call our particular attention "Scaled Dot-Product Attention" (Figure 2). The input consists of queries and keys of dimension dk, and values of dimension dy. We compute the dot products of the\\n\\nquery with all keys, divide each by Vdk, and apply a softmafunction to obtain the weights on the [x]\\n\\nvalues.\',\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.594,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 223.39593511428276,\n y: 771.1101458269851,\n },\n {\n x: 1051.4275265436104,\n y: 771.1101458269851,\n },\n {\n x: 1051.4275265436104,\n y: 856.1295272138783,\n },\n {\n x: 223.39593511428276,\n y: 856.1295272138783,\n },\n ],\n boundingBox: {\n left: 223.39593511428276,\n top: 771.1101458269851,\n right: 1051.4275265436104,\n bottom: 856.1295272138783,\n },\n },\n {\n id: "block_4_cDuW6h",\n type: "text",\n content:\n "In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix Q. The keys and values are also packed together into matrices K and V. We compute the matrix of outputs as:",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.976,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.08788778486044,\n y: 873.4355685585424,\n },\n {\n x: 1050.3812191260122,\n y: 873.4355685585424,\n },\n {\n x: 1050.3812191260122,\n y: 938.6725377821385,\n },\n {\n x: 224.08788778486044,\n y: 938.6725377821385,\n },\n ],\n boundingBox: {\n left: 224.08788778486044,\n top: 873.4355685585424,\n right: 1050.3812191260122,\n bottom: 938.6725377821385,\n },\n },\n {\n id: "block_4_VaSWNE",\n type: "text",\n content: "QKT Attention(Q, K, V) = softmax( V Vdk",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.961,\n },\n polygon: [\n {\n x: 458.52888900868214,\n y: 968.9788274549901,\n },\n {\n x: 816.6205023327013,\n y: 968.9788274549901,\n },\n {\n x: 816.6205023327013,\n y: 1021.9395890773686,\n },\n {\n x: 458.52888900868214,\n y: 1021.9395890773686,\n },\n ],\n boundingBox: {\n left: 458.52888900868214,\n top: 968.9788274549901,\n right: 816.6205023327013,\n bottom: 1021.9395890773686,\n },\n },\n {\n id: "block_4_Wtl7xI",\n type: "text",\n content: "(1)",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 1026.9459968065694,\n y: 986.4570474839747,\n },\n {\n x: 1051.0514920645387,\n y: 986.4570474839747,\n },\n {\n x: 1051.0514920645387,\n y: 1005.8566982871607,\n },\n {\n x: 1026.9459968065694,\n y: 1005.8566982871607,\n },\n ],\n boundingBox: {\n left: 1026.9459968065694,\n top: 986.4570474839747,\n right: 1051.0514920645387,\n bottom: 1005.8566982871607,\n },\n },\n {\n id: "block_4_HVInAp",\n type: "text",\n content:\n "The two most commonly used attention functions are additive attention [2], and dot-product (multi- plicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor\\n\\nof . Additive attention computes the compatibility function using a feed-forward network with [x] Vdk\\n\\na single hidden layer. While the two are similar in theoretical complexity, dot-product attention is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.098,\n avgOcrConfidence: 0.981,\n },\n polygon: [\n {\n x: 223.11696240501684,\n y: 1041.6009173859331,\n },\n {\n x: 1052.8067929901345,\n y: 1041.6009173859331,\n },\n {\n x: 1052.8067929901345,\n y: 1180.0422397699572,\n },\n {\n x: 223.11696240501684,\n y: 1180.0422397699572,\n },\n ],\n boundingBox: {\n left: 223.11696240501684,\n top: 1041.6009173859331,\n right: 1052.8067929901345,\n bottom: 1180.0422397699572,\n },\n },\n {\n id: "block_4_6NHlzf",\n type: "text",\n content:\n "While for small values of dk the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of dk [3]. We suspect that for large values of dk, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients 4. To counteract this effect, we scale the dot products by.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.58,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 223.18699551324775,\n y: 1194.0708248167111,\n },\n {\n x: 1050.8364934990875,\n y: 1194.0708248167111,\n },\n {\n x: 1050.8364934990875,\n y: 1289.5664457163416,\n },\n {\n x: 223.18699551324775,\n y: 1289.5664457163416,\n },\n ],\n boundingBox: {\n left: 223.18699551324775,\n top: 1194.0708248167111,\n right: 1050.8364934990875,\n bottom: 1289.5664457163416,\n },\n },\n {\n id: "block_4_4VWmvI",\n type: "section_heading",\n content: "### 3.2.2 Multi-Head Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.5976323594142,\n y: 1315.4335938647278,\n },\n {\n x: 479.8474026422431,\n y: 1315.4335938647278,\n },\n {\n x: 479.8474026422431,\n y: 1331.4542616650574,\n },\n {\n x: 223.5976323594142,\n y: 1331.4542616650574,\n },\n ],\n boundingBox: {\n left: 223.5976323594142,\n top: 1315.4335938647278,\n right: 479.8474026422431,\n bottom: 1331.4542616650574,\n },\n },\n {\n id: "block_4_n7aPpb",\n type: "text",\n content:\n "Instead of performing a single attention function with dmodel-dimensional keys, values and queries, we found it beneficial to linearly project the queries, keys and values h times with different, learned linear projections to dk, dk and dy dimensions, respectively. On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding dy-dimensional",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.619,\n avgOcrConfidence: 0.979,\n },\n polygon: [\n {\n x: 223.83094982509195,\n y: 1354.33461159154,\n },\n {\n x: 1052.0098498267848,\n y: 1354.33461159154,\n },\n {\n x: 1052.0098498267848,\n y: 1442.8801044664883,\n },\n {\n x: 223.83094982509195,\n y: 1442.8801044664883,\n },\n ],\n boundingBox: {\n left: 223.83094982509195,\n top: 1354.33461159154,\n right: 1052.0098498267848,\n bottom: 1442.8801044664883,\n },\n },\n {\n id: "block_4_rfqNPC",\n type: "text",\n content:\n "4To illustrate why the dot products get large, assume that the components of q and k are independent random variables with mean 0 and variance 1. Then their dot product, q \\u00b7 k = >i=1 qiki, has mean 0 and variance dk-",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.105,\n avgOcrConfidence: 0.921,\n },\n polygon: [\n {\n x: 224.42529636577967,\n y: 1459.9841341864794,\n },\n {\n x: 1049.4534401998033,\n y: 1459.9841341864794,\n },\n {\n x: 1049.4534401998033,\n y: 1506.815978659723,\n },\n {\n x: 224.42529636577967,\n y: 1506.815978659723,\n },\n ],\n boundingBox: {\n left: 224.42529636577967,\n top: 1459.9841341864794,\n right: 1049.4534401998033,\n bottom: 1506.815978659723,\n },\n },\n {\n id: "block_4_35BhDQ",\n type: "page_number",\n content: "4",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.996,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 631.2688757903385,\n y: 1548.1330857241064,\n },\n {\n x: 642.0564832478544,\n y: 1548.1330857241064,\n },\n {\n x: 642.0564832478544,\n y: 1562.0727401962854,\n },\n {\n x: 631.2688757903385,\n y: 1562.0727401962854,\n },\n ],\n boundingBox: {\n left: 631.2688757903385,\n top: 1548.1330857241064,\n right: 642.0564832478544,\n bottom: 1562.0727401962854,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_5_Zc8VSW",\n type: "text",\n content:\n "output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure 2.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.988,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.67903916853186,\n y: 155.68632458564932,\n },\n {\n x: 1049.4719957783275,\n y: 155.68632458564932,\n },\n {\n x: 1049.4719957783275,\n y: 199.30535079841326,\n },\n {\n x: 224.67903916853186,\n y: 199.30535079841326,\n },\n ],\n boundingBox: {\n left: 224.67903916853186,\n top: 155.68632458564932,\n right: 1049.4719957783275,\n bottom: 199.30535079841326,\n },\n },\n {\n id: "block_5_P72mUL",\n type: "text",\n content:\n "Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 224.58133836732293,\n y: 212.29537068990837,\n },\n {\n x: 1049.5524663994781,\n y: 212.29537068990837,\n },\n {\n x: 1049.5524663994781,\n y: 255.9039790504857,\n },\n {\n x: 224.58133836732293,\n y: 255.9039790504857,\n },\n ],\n boundingBox: {\n left: 224.58133836732293,\n top: 212.29537068990837,\n right: 1049.5524663994781,\n bottom: 255.9039790504857,\n },\n },\n {\n id: "block_5_zTpvNY",\n type: "text",\n content:\n "MultiHead(Q,K,V)=Concat(head1, ... , headh)W\\u00ba where head; = Attention(Qw?, KWK,VW)",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.581,\n avgOcrConfidence: 0.796,\n },\n polygon: [\n {\n x: 388.73733464818804,\n y: 302.5467395065422,\n },\n {\n x: 883.3280911410811,\n y: 302.5467395065422,\n },\n {\n x: 883.3280911410811,\n y: 364.6030674267532,\n },\n {\n x: 388.73733464818804,\n y: 364.6030674267532,\n },\n ],\n boundingBox: {\n left: 388.73733464818804,\n top: 302.5467395065422,\n right: 883.3280911410811,\n bottom: 364.6030674267532,\n },\n },\n {\n id: "block_5_cOSQOc",\n type: "text",\n content:\n "Where the projections are parameter matrices Wo E Rdmodel X dk , WK \\u20ac Rdmodel X dk , WY \\u20ac Rdmodel X dy and WO E Rhdy Xdmodel",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.252,\n avgOcrConfidence: 0.682,\n },\n polygon: [\n {\n x: 223.51567066498916,\n y: 424.5787134959285,\n },\n {\n x: 1047.1388211215499,\n y: 424.5787134959285,\n },\n {\n x: 1047.1388211215499,\n y: 472.1556711698833,\n },\n {\n x: 223.51567066498916,\n y: 472.1556711698833,\n },\n ],\n boundingBox: {\n left: 223.51567066498916,\n top: 424.5787134959285,\n right: 1047.1388211215499,\n bottom: 472.1556711698833,\n },\n },\n {\n id: "block_5_4oR3J2",\n type: "text",\n content:\n "In this work we employ h = 8 parallel attention layers, or heads. For each of these we use dk = dy = dmodel/h = 64. Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.557,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 223.83189653828197,\n y: 488.323372747665,\n },\n {\n x: 1049.9097559573877,\n y: 488.323372747665,\n },\n {\n x: 1049.9097559573877,\n y: 555.0531728357302,\n },\n {\n x: 223.83189653828197,\n y: 555.0531728357302,\n },\n ],\n boundingBox: {\n left: 223.83189653828197,\n top: 488.323372747665,\n right: 1049.9097559573877,\n bottom: 555.0531728357302,\n },\n },\n {\n id: "block_5_oGR7Tp",\n type: "section_heading",\n content: "### 3.2.3 Applications of Attention in our Model",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.9031130380004,\n y: 584.1135347409356,\n },\n {\n x: 629.6546824657133,\n y: 584.1135347409356,\n },\n {\n x: 629.6546824657133,\n y: 605.02614180486,\n },\n {\n x: 223.9031130380004,\n y: 605.02614180486,\n },\n ],\n boundingBox: {\n left: 223.9031130380004,\n top: 584.1135347409356,\n right: 629.6546824657133,\n bottom: 605.02614180486,\n },\n },\n {\n id: "block_5_b34egv",\n type: "text",\n content:\n "The Transformer uses multi-head attention in three different ways:",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.3985859112148,\n y: 623.9660812033746,\n },\n {\n x: 775.7513199409428,\n y: 623.9660812033746,\n },\n {\n x: 775.7513199409428,\n y: 644.7702005429376,\n },\n {\n x: 223.3985859112148,\n y: 644.7702005429376,\n },\n ],\n boundingBox: {\n left: 223.3985859112148,\n top: 623.9660812033746,\n right: 775.7513199409428,\n bottom: 644.7702005429376,\n },\n },\n {\n id: "block_5_NSYaLO",\n type: "text",\n content:\n \'\\u00b7 In "encoder-decoder attention" layers, the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder. This allows every position in the decoder to attend over all positions in the input sequence. This mimics the typical encoder-decoder attention mechanisms in sequence-to-sequence models such as [38, 2, 9].\',\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.586,\n avgOcrConfidence: 0.984,\n },\n polygon: [\n {\n x: 281.7719981618171,\n y: 667.4162908568419,\n },\n {\n x: 1052.1352893244612,\n y: 667.4162908568419,\n },\n {\n x: 1052.1352893244612,\n y: 778.3123385207098,\n },\n {\n x: 281.7719981618171,\n y: 778.3123385207098,\n },\n ],\n boundingBox: {\n left: 281.7719981618171,\n top: 667.4162908568419,\n right: 1052.1352893244612,\n bottom: 778.3123385207098,\n },\n },\n {\n id: "block_5_ZbEUX6",\n type: "text",\n content:\n "\\u00b7 The encoder contains self-attention layers. In a self-attention layer all of the keys, values and queries come from the same place, in this case, the output of the previous layer in the encoder. Each position in the encoder can attend to all positions in the previous layer of the encoder.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.407,\n avgOcrConfidence: 0.983,\n },\n polygon: [\n {\n x: 282.1731915439132,\n y: 791.5420637202442,\n },\n {\n x: 1049.6795153095775,\n y: 791.5420637202442,\n },\n {\n x: 1049.6795153095775,\n y: 876.9418387735697,\n },\n {\n x: 282.1731915439132,\n y: 876.9418387735697,\n },\n ],\n boundingBox: {\n left: 282.1731915439132,\n top: 791.5420637202442,\n right: 1049.6795153095775,\n bottom: 876.9418387735697,\n },\n },\n {\n id: "block_5_wkxEH8",\n type: "text",\n content:\n "\\u00b7 Similarly, self-attention layers in the decoder allow each position in the decoder to attend to all positions in the decoder up to and including that position. We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to -oo) all values in the input of the softmax which correspond to illegal connections. See Figure 2.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.543,\n avgOcrConfidence: 0.985,\n },\n polygon: [\n {\n x: 281.12820952478114,\n y: 893.687589086088,\n },\n {\n x: 1049.8325041610829,\n y: 893.687589086088,\n },\n {\n x: 1049.8325041610829,\n y: 1005.0602061336201,\n },\n {\n x: 281.12820952478114,\n y: 1005.0602061336201,\n },\n ],\n boundingBox: {\n left: 281.12820952478114,\n top: 893.687589086088,\n right: 1049.8325041610829,\n bottom: 1005.0602061336201,\n },\n },\n {\n id: "block_5_vVMF0e",\n type: "section_heading",\n content: "### 3.3 Position-wise Feed-Forward Networks",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.59919443617773,\n y: 1037.180243872162,\n },\n {\n x: 609.3837069768975,\n y: 1037.180243872162,\n },\n {\n x: 609.3837069768975,\n y: 1053.935843790384,\n },\n {\n x: 223.59919443617773,\n y: 1053.935843790384,\n },\n ],\n boundingBox: {\n left: 223.59919443617773,\n top: 1037.180243872162,\n right: 609.3837069768975,\n bottom: 1053.935843790384,\n },\n },\n {\n id: "block_5_WtW3Xc",\n type: "text",\n content:\n "In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forward network, which is applied to each position separately and identically. This consists of two linear transformations with a ReLU activation in between.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.986,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.937928415563,\n y: 1079.1571798109471,\n },\n {\n x: 1049.736412772297,\n y: 1079.1571798109471,\n },\n {\n x: 1049.736412772297,\n y: 1142.9025967246607,\n },\n {\n x: 223.937928415563,\n y: 1142.9025967246607,\n },\n ],\n boundingBox: {\n left: 223.937928415563,\n top: 1079.1571798109471,\n right: 1049.736412772297,\n bottom: 1142.9025967246607,\n },\n },\n {\n id: "block_5_TCB4QK",\n type: "text",\n content: "FFN(x)=max(0,xW1+b1)W2+b2",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.668,\n avgOcrConfidence: 0.668,\n },\n polygon: [\n {\n x: 471.6477776965956,\n y: 1184.1576702146604,\n },\n {\n x: 801.1487473536581,\n y: 1184.1576702146604,\n },\n {\n x: 801.1487473536581,\n y: 1206.444581397494,\n },\n {\n x: 471.6477776965956,\n y: 1206.444581397494,\n },\n ],\n boundingBox: {\n left: 471.6477776965956,\n top: 1184.1576702146604,\n right: 801.1487473536581,\n bottom: 1206.444581397494,\n },\n },\n {\n id: "block_5_olGJjx",\n type: "text",\n content: "(2)",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.997,\n avgOcrConfidence: 0.997,\n },\n polygon: [\n {\n x: 1026.9936164800267,\n y: 1185.5856736262042,\n },\n {\n x: 1051.1806237436558,\n y: 1185.5856736262042,\n },\n {\n x: 1051.1806237436558,\n y: 1204.3962422421102,\n },\n {\n x: 1026.9936164800267,\n y: 1204.3962422421102,\n },\n ],\n boundingBox: {\n left: 1026.9936164800267,\n top: 1185.5856736262042,\n right: 1051.1806237436558,\n bottom: 1204.3962422421102,\n },\n },\n {\n id: "block_5_KTjDsL",\n type: "text",\n content:\n "While the linear transformations are the same across different positions, they use different parameters from layer to layer. Another way of describing this is as two convolutions with kernel size 1. The dimensionality of input and output is dmodel = 512, and the inner-layer has dimensionality dff =2048.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.881,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 222.78797957148865,\n y: 1230.1093008858818,\n },\n {\n x: 1052.541145269018,\n y: 1230.1093008858818,\n },\n {\n x: 1052.541145269018,\n y: 1320.3967533541802,\n },\n {\n x: 222.78797957148865,\n y: 1320.3967533541802,\n },\n ],\n boundingBox: {\n left: 222.78797957148865,\n top: 1230.1093008858818,\n right: 1052.541145269018,\n bottom: 1320.3967533541802,\n },\n },\n {\n id: "block_5_Pwzvu2",\n type: "section_heading",\n content: "### 3.4 Embeddings and Softmax",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.997,\n },\n polygon: [\n {\n x: 223.80512822283447,\n y: 1351.0096120045598,\n },\n {\n x: 499.655388045485,\n y: 1351.0096120045598,\n },\n {\n x: 499.655388045485,\n y: 1371.2419333206979,\n },\n {\n x: 223.80512822283447,\n y: 1371.2419333206979,\n },\n ],\n boundingBox: {\n left: 223.80512822283447,\n top: 1351.0096120045598,\n right: 499.655388045485,\n bottom: 1371.2419333206979,\n },\n },\n {\n id: "block_5_6y9ZGB",\n type: "text",\n content:\n "Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension dmodel. We also use the usual learned linear transfor- mation and softmax function to convert the decoder output to predicted next-token probabilities. In our model, we share the same weight matrix between the two embedding layers and the pre-softmax linear transformation, similar to [30]. In the embedding layers, we multiply those weights by Vdmodel -",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.275,\n avgOcrConfidence: 0.983,\n },\n polygon: [\n {\n x: 224.49331770848184,\n y: 1394.318801822519,\n },\n {\n x: 1052.2855327077154,\n y: 1394.318801822519,\n },\n {\n x: 1052.2855327077154,\n y: 1505.8341434450076,\n },\n {\n x: 224.49331770848184,\n y: 1505.8341434450076,\n },\n ],\n boundingBox: {\n left: 224.49331770848184,\n top: 1394.318801822519,\n right: 1052.2855327077154,\n bottom: 1505.8341434450076,\n },\n },\n {\n id: "block_5_o8MKrc",\n type: "page_number",\n content: "5",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 631.5606054598397,\n y: 1547.4356578740858,\n },\n {\n x: 641.9868998283888,\n y: 1547.4356578740858,\n },\n {\n x: 641.9868998283888,\n y: 1563.1716341864794,\n },\n {\n x: 631.5606054598397,\n y: 1563.1716341864794,\n },\n ],\n boundingBox: {\n left: 631.5606054598397,\n top: 1547.4356578740858,\n right: 641.9868998283888,\n bottom: 1563.1716341864794,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_6_YmUPFZ",\n type: "text",\n content:\n "Table 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations for different layer types. n is the sequence length, d is the representation dimension, k is the kernel size of convolutions and r the size of the neighborhood in restricted self-attention.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.977,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.7798615058843,\n y: 148.2273318355245,\n },\n {\n x: 1048.906618661254,\n y: 148.2273318355245,\n },\n {\n x: 1048.906618661254,\n y: 214.40370720311216,\n },\n {\n x: 222.7798615058843,\n y: 214.40370720311216,\n },\n ],\n boundingBox: {\n left: 222.7798615058843,\n top: 148.2273318355245,\n right: 1048.906618661254,\n bottom: 214.40370720311216,\n },\n },\n {\n id: "block_6_kibLxu",\n type: "table",\n content:\n "| Layer Type | Complexity per Layer | Sequential Operations | Maximum Path Length |\\n| --- | --- | --- | --- |\\n| Self-Attention | O(n2 \\u00b7 d) | O(1) | O(1) |\\n| Recurrent | O(n \\u00b7 d2) | O(n) | O(n) |\\n| Convolutional | O(k \\u00b7 n \\u00b7 d2) | O(1) | O(logk(n)) |\\n| Self-Attention (restricted) | O(r . n . d) [ ] | O(1) | O(n/r) [ ] |",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.256,\n avgOcrConfidence: 0.856,\n },\n polygon: [\n {\n x: 246.08119491243013,\n y: 233.8958637983279,\n },\n {\n x: 1028.2713006012632,\n y: 233.8958637983279,\n },\n {\n x: 1028.2713006012632,\n y: 389.94297754674926,\n },\n {\n x: 246.08119491243013,\n y: 389.94297754674926,\n },\n ],\n boundingBox: {\n left: 246.08119491243013,\n top: 233.8958637983279,\n right: 1028.2713006012632,\n bottom: 389.94297754674926,\n },\n },\n {\n id: "block_6_tUIpoY",\n type: "section_heading",\n content: "### 3.5 Positional Encoding",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.00651778617916,\n y: 445.9595083078944,\n },\n {\n x: 448.20427163674015,\n y: 445.9595083078944,\n },\n {\n x: 448.20427163674015,\n y: 466.69903696390026,\n },\n {\n x: 224.00651778617916,\n y: 466.69903696390026,\n },\n ],\n boundingBox: {\n left: 224.00651778617916,\n top: 445.9595083078944,\n right: 448.20427163674015,\n bottom: 466.69903696390026,\n },\n },\n {\n id: "block_6_mmxGrc",\n type: "text",\n content:\n \'Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence. To this end, we add "positional encodings" to the input embeddings at the bottoms of the encoder and decoder stacks. The positional encodings have the same dimension dmodel as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [9].\',\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.83698512167825,\n y: 487.3354288832586,\n },\n {\n x: 1050.4121766473256,\n y: 487.3354288832586,\n },\n {\n x: 1050.4121766473256,\n y: 620.7750930786133,\n },\n {\n x: 223.83698512167825,\n y: 620.7750930786133,\n },\n ],\n boundingBox: {\n left: 223.83698512167825,\n top: 487.3354288832586,\n right: 1050.4121766473256,\n bottom: 620.7750930786133,\n },\n },\n {\n id: "block_6_NG2aN8",\n type: "text",\n content:\n "In this work, we use sine and cosine functions of different frequencies:",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.39521455416715,\n y: 635.0555533789154,\n },\n {\n x: 810.5588871197108,\n y: 635.0555533789154,\n },\n {\n x: 810.5588871197108,\n y: 655.9754529393705,\n },\n {\n x: 224.39521455416715,\n y: 655.9754529393705,\n },\n ],\n boundingBox: {\n left: 224.39521455416715,\n top: 635.0555533789154,\n right: 810.5588871197108,\n bottom: 655.9754529393705,\n },\n },\n {\n id: "block_6_ktOzAP",\n type: "text",\n content:\n "PE(pos,2i) = sin(pos/100002i/dmodel ) PE(pos,2i+1) = cos(pos/100002i/dmodel) )",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.646,\n avgOcrConfidence: 0.856,\n },\n polygon: [\n {\n x: 470.62755222738224,\n y: 700.6432727440855,\n },\n {\n x: 804.2361684089159,\n y: 700.6432727440855,\n },\n {\n x: 804.2361684089159,\n y: 763.5065343469606,\n },\n {\n x: 470.62755222738224,\n y: 763.5065343469606,\n },\n ],\n boundingBox: {\n left: 470.62755222738224,\n top: 700.6432727440855,\n right: 804.2361684089159,\n bottom: 763.5065343469606,\n },\n },\n {\n id: "block_6_L0vHNu",\n type: "text",\n content:\n "where pos is the position and i is the dimension. That is, each dimension of the positional encoding corresponds to a sinusoid. The wavelengths form a geometric progression from 27 to 10000 . 27. We chose this function because we hypothesized it would allow the model to easily learn to attend by relative positions, since for any fixed offset k, PEpos+k can be represented as a linear function of PEpos.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.291,\n avgOcrConfidence: 0.967,\n },\n polygon: [\n {\n x: 223.63699196028884,\n y: 787.3148307800293,\n },\n {\n x: 1050.8335586881985,\n y: 787.3148307800293,\n },\n {\n x: 1050.8335586881985,\n y: 900.202535012611,\n },\n {\n x: 223.63699196028884,\n y: 900.202535012611,\n },\n ],\n boundingBox: {\n left: 223.63699196028884,\n top: 787.3148307800293,\n right: 1050.8335586881985,\n bottom: 900.202535012611,\n },\n },\n {\n id: "block_6_Sai49H",\n type: "text",\n content:\n "We also experimented with using learned positional embeddings [9] instead, and found that the two versions produced nearly identical results (see Table 3 row (E)). We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.868,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 223.15007369883736,\n y: 912.2991767252298,\n },\n {\n x: 1049.522644933993,\n y: 912.2991767252298,\n },\n {\n x: 1049.522644933993,\n y: 1000.5864015736975,\n },\n {\n x: 223.15007369883736,\n y: 1000.5864015736975,\n },\n ],\n boundingBox: {\n left: 223.15007369883736,\n top: 912.2991767252298,\n right: 1049.522644933993,\n bottom: 1000.5864015736975,\n },\n },\n {\n id: "block_6_545oKE",\n type: "section_heading",\n content: "### 4 Why Self-Attention",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.44270274586924,\n y: 1036.185907234823,\n },\n {\n x: 468.14631162768734,\n y: 1036.185907234823,\n },\n {\n x: 468.14631162768734,\n y: 1059.806398205291,\n },\n {\n x: 223.44270274586924,\n y: 1059.806398205291,\n },\n ],\n boundingBox: {\n left: 223.44270274586924,\n top: 1036.185907234823,\n right: 468.14631162768734,\n bottom: 1059.806398205291,\n },\n },\n {\n id: "block_6_rdkytl",\n type: "text",\n content:\n "In this section we compare various aspects of self-attention layers to the recurrent and convolu- tional layers commonly used for mapping one variable-length sequence of symbol representations (x1, ... , In) to another sequence of equal length (21, ... , Zn), with xi, Zi E Rd, such as a hidden layer in a typical sequence transduction encoder or decoder. Motivating our use of self-attention we consider three desiderata.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.298,\n avgOcrConfidence: 0.936,\n },\n polygon: [\n {\n x: 222.55295802206888,\n y: 1087.3066867455505,\n },\n {\n x: 1052.7677884067061,\n y: 1087.3066867455505,\n },\n {\n x: 1052.7677884067061,\n y: 1195.3768446499244,\n },\n {\n x: 222.55295802206888,\n y: 1195.3768446499244,\n },\n ],\n boundingBox: {\n left: 222.55295802206888,\n top: 1087.3066867455505,\n right: 1052.7677884067061,\n bottom: 1195.3768446499244,\n },\n },\n {\n id: "block_6_y2UJTk",\n type: "text",\n content:\n "One is the total computational complexity per layer. Another is the amount of computation that can be parallelized, as measured by the minimum number of sequential operations required.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.43593374656064,\n y: 1212.4905345601246,\n },\n {\n x: 1048.7435946499345,\n y: 1212.4905345601246,\n },\n {\n x: 1048.7435946499345,\n y: 1255.7911059730932,\n },\n {\n x: 223.43593374656064,\n y: 1255.7911059730932,\n },\n ],\n boundingBox: {\n left: 223.43593374656064,\n top: 1212.4905345601246,\n right: 1048.7435946499345,\n bottom: 1255.7911059730932,\n },\n },\n {\n id: "block_6_OGHshO",\n type: "text",\n content:\n "The third is the path length between long-range dependencies in the network. Learning long-range dependencies is a key challenge in many sequence transduction tasks. One key factor affecting the ability to learn such dependencies is the length of the paths forward and backward signals have to traverse in the network. The shorter these paths between any combination of positions in the input and output sequences, the easier it is to learn long-range dependencies [12]. Hence we also compare the maximum path length between any two input and output positions in networks composed of the different layer types.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.983,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.87737296445525,\n y: 1268.8657945905413,\n },\n {\n x: 1049.749950770914,\n y: 1268.8657945905413,\n },\n {\n x: 1049.749950770914,\n y: 1426.1352065236945,\n },\n {\n x: 222.87737296445525,\n y: 1426.1352065236945,\n },\n ],\n boundingBox: {\n left: 222.87737296445525,\n top: 1268.8657945905413,\n right: 1049.749950770914,\n bottom: 1426.1352065236945,\n },\n },\n {\n id: "block_6_zgN3wO",\n type: "text",\n content:\n "As noted in Table 1, a self-attention layer connects all positions with a constant number of sequentially executed operations, whereas a recurrent layer requires O(n) sequential operations. In terms of computational complexity, self-attention layers are faster than recurrent layers when the sequence",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.4352473794979,\n y: 1439.235182109632,\n },\n {\n x: 1051.6017217705719,\n y: 1439.235182109632,\n },\n {\n x: 1051.6017217705719,\n y: 1506.1062388025728,\n },\n {\n x: 223.4352473794979,\n y: 1506.1062388025728,\n },\n ],\n boundingBox: {\n left: 223.4352473794979,\n top: 1439.235182109632,\n right: 1051.6017217705719,\n bottom: 1506.1062388025728,\n },\n },\n {\n id: "block_6_aNgpKT",\n type: "page_number",\n content: "6",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 631.7702550957673,\n y: 1548.2886905526757,\n },\n {\n x: 642.7105200551722,\n y: 1548.2886905526757,\n },\n {\n x: 642.7105200551722,\n y: 1563.5418467700931,\n },\n {\n x: 631.7702550957673,\n y: 1563.5418467700931,\n },\n ],\n boundingBox: {\n left: 631.7702550957673,\n top: 1548.2886905526757,\n right: 642.7105200551722,\n bottom: 1563.5418467700931,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_7_u723hy",\n type: "text",\n content:\n "length n is smaller than the representation dimensionality d, which is most often the case with sentence representations used by state-of-the-art models in machine translations, such as word-piece [38] and byte-pair [31] representations. To improve computational performance for tasks involving very long sequences, self-attention could be restricted to considering only a neighborhood of size r in the input sequence centered around the respective output position. This would increase the maximum path length to O(n/r). We plan to investigate this approach further in future work.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.909,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.89144479793353,\n y: 155.39061148363845,\n },\n {\n x: 1050.0338700565978,\n y: 155.39061148363845,\n },\n {\n x: 1050.0338700565978,\n y: 290.11272512163436,\n },\n {\n x: 223.89144479793353,\n y: 290.11272512163436,\n },\n ],\n boundingBox: {\n left: 223.89144479793353,\n top: 155.39061148363845,\n right: 1050.0338700565978,\n bottom: 290.11272512163436,\n },\n },\n {\n id: "block_7_SLgoxa",\n type: "text",\n content:\n "A single convolutional layer with kernel width k < n does not connect all pairs of input and output positions. Doing so requires a stack of O(n/k) convolutional layers in the case of contiguous kernels, or O(logk(n)) in the case of dilated convolutions [18], increasing the length of the longest paths between any two positions in the network. Convolutional layers are generally more expensive than recurrent layers, by a factor of k. Separable convolutions [6], however, decrease the complexity considerably, to O(k . n . d + n . d2). Even with k = n, however, the complexity of a separable convolution is equal to the combination of a self-attention layer and a point-wise feed-forward layer, the approach we take in our model.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.525,\n avgOcrConfidence: 0.977,\n },\n polygon: [\n {\n x: 223.84822734080961,\n y: 303.4973448416344,\n },\n {\n x: 1051.7048188369638,\n y: 303.4973448416344,\n },\n {\n x: 1051.7048188369638,\n y: 482.7421505003047,\n },\n {\n x: 223.84822734080961,\n y: 482.7421505003047,\n },\n ],\n boundingBox: {\n left: 223.84822734080961,\n top: 303.4973448416344,\n right: 1051.7048188369638,\n bottom: 482.7421505003047,\n },\n },\n {\n id: "block_7_lGN5L0",\n type: "text",\n content:\n "As side benefit, self-attention could yield more interpretable models. We inspect attention distributions from our models and present and discuss examples in the appendix. Not only do individual attention heads clearly learn to perform different tasks, many appear to exhibit behavior related to the syntactic and semantic structure of the sentences.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.94,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.7218884656029,\n y: 496.4417208334557,\n },\n {\n x: 1049.5183847246378,\n y: 496.4417208334557,\n },\n {\n x: 1049.5183847246378,\n y: 581.3287481437052,\n },\n {\n x: 223.7218884656029,\n y: 581.3287481437052,\n },\n ],\n boundingBox: {\n left: 223.7218884656029,\n top: 496.4417208334557,\n right: 1049.5183847246378,\n bottom: 581.3287481437052,\n },\n },\n {\n id: "block_7_FOtl5B",\n type: "heading",\n content: "# 5 Training",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.4122553915873,\n y: 625.3390120599503,\n },\n {\n x: 354.91415984439146,\n y: 625.3390120599503,\n },\n {\n x: 354.91415984439146,\n y: 649.7166914688913,\n },\n {\n x: 224.4122553915873,\n y: 649.7166914688913,\n },\n ],\n boundingBox: {\n left: 224.4122553915873,\n top: 625.3390120599503,\n right: 354.91415984439146,\n bottom: 649.7166914688913,\n },\n },\n {\n id: "block_7_3jYBCf",\n type: "text",\n content: "This section describes the training regime for our models.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.4527957665659,\n y: 679.1303132709704,\n },\n {\n x: 701.988161741382,\n y: 679.1303132709704,\n },\n {\n x: 701.988161741382,\n y: 699.7081758025894,\n },\n {\n x: 222.4527957665659,\n y: 699.7081758025894,\n },\n ],\n boundingBox: {\n left: 222.4527957665659,\n top: 679.1303132709704,\n right: 701.988161741382,\n bottom: 699.7081758025894,\n },\n },\n {\n id: "block_7_PIafds",\n type: "section_heading",\n content: "### 5.1 Training Data and Batching",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.68002007477475,\n y: 735.0401794318866,\n },\n {\n x: 519.6398407873446,\n y: 735.0401794318866,\n },\n {\n x: 519.6398407873446,\n y: 755.8565634247055,\n },\n {\n x: 223.68002007477475,\n y: 755.8565634247055,\n },\n ],\n boundingBox: {\n left: 223.68002007477475,\n top: 735.0401794318866,\n right: 519.6398407873446,\n bottom: 755.8565634247055,\n },\n },\n {\n id: "block_7_8RhsHH",\n type: "text",\n content:\n "We trained on the standard WMT 2014 English-German dataset consisting of about 4.5 million sentence pairs. Sentences were encoded using byte-pair encoding [3], which has a shared source- target vocabulary of about 37000 tokens. For English-French, we used the significantly larger WMT 2014 English-French dataset consisting of 36M sentences and split tokens into a 32000 word-piece vocabulary [38]. Sentence pairs were batched together by approximate sequence length. Each training batch contained a set of sentence pairs containing approximately 25000 source tokens and 25000 target tokens.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.911,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.70165247116648,\n y: 778.8621643467953,\n },\n {\n x: 1052.1871692072737,\n y: 778.8621643467953,\n },\n {\n x: 1052.1871692072737,\n y: 935.23512009929,\n },\n {\n x: 223.70165247116648,\n y: 935.23512009929,\n },\n ],\n boundingBox: {\n left: 223.70165247116648,\n top: 778.8621643467953,\n right: 1052.1871692072737,\n bottom: 935.23512009929,\n },\n },\n {\n id: "block_7_2fOgoW",\n type: "section_heading",\n content: "### 5.2 Hardware and Schedule",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.9209349138023,\n y: 971.4598863071069,\n },\n {\n x: 484.7486314982394,\n y: 971.4598863071069,\n },\n {\n x: 484.7486314982394,\n y: 987.6652342143811,\n },\n {\n x: 223.9209349138023,\n y: 987.6652342143811,\n },\n ],\n boundingBox: {\n left: 223.9209349138023,\n top: 971.4598863071069,\n right: 484.7486314982394,\n bottom: 987.6652342143811,\n },\n },\n {\n id: "block_7_7vykWe",\n type: "text",\n content:\n "We trained our models on one machine with 8 NVIDIA P100 GPUs. For our base models using the hyperparameters described throughout the paper, each training step took about 0.4 seconds. We trained the base models for a total of 100,000 steps or 12 hours. For our big models,(described on the bottom line of table 3), step time was 1.0 seconds. The big models were trained for 300,000 steps (3.5 days).",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.961,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.2459757449853,\n y: 1014.9955223485043,\n },\n {\n x: 1049.3973947789548,\n y: 1014.9955223485043,\n },\n {\n x: 1049.3973947789548,\n y: 1126.7015106660083,\n },\n {\n x: 223.2459757449853,\n y: 1126.7015106660083,\n },\n ],\n boundingBox: {\n left: 223.2459757449853,\n top: 1014.9955223485043,\n right: 1049.3973947789548,\n bottom: 1126.7015106660083,\n },\n },\n {\n id: "block_7_Xjy6qb",\n type: "section_heading",\n content: "### 5.3 Optimizer",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.84361211400832,\n y: 1161.1210525053784,\n },\n {\n x: 361.9454223744191,\n y: 1161.1210525053784,\n },\n {\n x: 361.9454223744191,\n y: 1181.9203891037102,\n },\n {\n x: 223.84361211400832,\n y: 1181.9203891037102,\n },\n ],\n boundingBox: {\n left: 223.84361211400832,\n top: 1161.1210525053784,\n right: 361.9454223744191,\n bottom: 1181.9203891037102,\n },\n },\n {\n id: "block_7_uZS3FC",\n type: "text",\n content:\n "We used the Adam optimizer [20] with 31 = 0.9, 32 = 0.98 and \\u20ac = 10-9. We varied the learning rate over the course of training, according to the formula:",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.472,\n avgOcrConfidence: 0.947,\n },\n polygon: [\n {\n x: 223.18536243299496,\n y: 1203.7906809068263,\n },\n {\n x: 1049.5936484232436,\n y: 1203.7906809068263,\n },\n {\n x: 1049.5936484232436,\n y: 1249.0720648514596,\n },\n {\n x: 223.18536243299496,\n y: 1249.0720648514596,\n },\n ],\n boundingBox: {\n left: 223.18536243299496,\n top: 1203.7906809068263,\n right: 1049.5936484232436,\n bottom: 1249.0720648514596,\n },\n },\n {\n id: "block_7_qvJczg",\n type: "text",\n content:\n "lrate = dmodel . min(step_num-0.5, step_num . warmup_steps-1.5)",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.563,\n avgOcrConfidence: 0.786,\n },\n polygon: [\n {\n x: 338.51696905428474,\n y: 1286.921258338412,\n },\n {\n x: 933.735361586522,\n y: 1286.921258338412,\n },\n {\n x: 933.735361586522,\n y: 1314.0637410099346,\n },\n {\n x: 338.51696905428474,\n y: 1314.0637410099346,\n },\n ],\n boundingBox: {\n left: 338.51696905428474,\n top: 1286.921258338412,\n right: 933.735361586522,\n bottom: 1314.0637410099346,\n },\n },\n {\n id: "block_7_ZRnl1T",\n type: "text",\n content: "(3)",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 1026.6387883764114,\n y: 1291.0368781986094,\n },\n {\n x: 1051.2767151324417,\n y: 1291.0368781986094,\n },\n {\n x: 1051.2767151324417,\n y: 1311.080825805664,\n },\n {\n x: 1026.6387883764114,\n y: 1311.080825805664,\n },\n ],\n boundingBox: {\n left: 1026.6387883764114,\n top: 1291.0368781986094,\n right: 1051.2767151324417,\n bottom: 1311.080825805664,\n },\n },\n {\n id: "block_7_M71nL9",\n type: "text",\n content:\n "This corresponds to increasing the learning rate linearly for the first warmup_steps training steps, and decreasing it thereafter proportionally to the inverse square root of the step number. We used warmup_steps = 4000.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.916,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 222.72840764400732,\n y: 1340.2761936044335,\n },\n {\n x: 1052.0266066502481,\n y: 1340.2761936044335,\n },\n {\n x: 1052.0266066502481,\n y: 1406.6737115616188,\n },\n {\n x: 222.72840764400732,\n y: 1406.6737115616188,\n },\n ],\n boundingBox: {\n left: 222.72840764400732,\n top: 1340.2761936044335,\n right: 1052.0266066502481,\n bottom: 1406.6737115616188,\n },\n },\n {\n id: "block_7_ACakMa",\n type: "section_heading",\n content: "### 5.4 Regularization",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.81116351942077,\n y: 1441.41800626597,\n },\n {\n x: 402.1996435457773,\n y: 1441.41800626597,\n },\n {\n x: 402.1996435457773,\n y: 1461.9926013803124,\n },\n {\n x: 223.81116351942077,\n y: 1461.9926013803124,\n },\n ],\n boundingBox: {\n left: 223.81116351942077,\n top: 1441.41800626597,\n right: 402.1996435457773,\n bottom: 1461.9926013803124,\n },\n },\n {\n id: "block_7_rR8JeL",\n type: "text",\n content: "We employ three types of regularization during training:",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.88627206844134,\n y: 1484.7892296583134,\n },\n {\n x: 690.987449144795,\n y: 1484.7892296583134,\n },\n {\n x: 690.987449144795,\n y: 1505.950728681751,\n },\n {\n x: 222.88627206844134,\n y: 1505.950728681751,\n },\n ],\n boundingBox: {\n left: 222.88627206844134,\n top: 1484.7892296583134,\n right: 690.987449144795,\n bottom: 1505.950728681751,\n },\n },\n {\n id: "block_7_I7j7Uy",\n type: "page_number",\n content: "7",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.996,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 631.8865114755004,\n y: 1547.4189893105872,\n },\n {\n x: 642.4512153124288,\n y: 1547.4189893105872,\n },\n {\n x: 642.4512153124288,\n y: 1562.541448836936,\n },\n {\n x: 631.8865114755004,\n y: 1562.541448836936,\n },\n ],\n boundingBox: {\n left: 631.8865114755004,\n top: 1547.4189893105872,\n right: 642.4512153124288,\n bottom: 1562.541448836936,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_8_8rtbBp",\n type: "text",\n content:\n "Table 2: The Transformer achieves better BLEU scores than previous state-of-the-art models on the English-to-German and English-to-French newstest2014 tests at a fraction of the training cost.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 222.40285664579295,\n y: 148.11078211418666,\n },\n {\n x: 1048.695596291201,\n y: 148.11078211418666,\n },\n {\n x: 1048.695596291201,\n y: 191.8824890538266,\n },\n {\n x: 222.40285664579295,\n y: 191.8824890538266,\n },\n ],\n boundingBox: {\n left: 222.40285664579295,\n top: 148.11078211418666,\n right: 1048.695596291201,\n bottom: 191.8824890538266,\n },\n },\n {\n id: "block_8_M3V7h9",\n type: "table",\n content:\n "| Model | BLEU | | Training Cost (FLOPs) | |\\n| --- | --- | --- | --- | --- |\\n| | EN-DE | EN-FR | EN-DE | EN-FR |\\n| ByteNet [18] | 23.75 | | | |\\n| Deep-Att + PosUnk [39] | | 39.2 | | 1.0 . 1020 |\\n| GNMT + RL [38] | 24.6 | 39.92 | 2.3 . 1019 | 1.4 . 1020 |\\n| ConvS2S [9] | 25.16 | 40.46 | 9.6 . 1018 | 1.5 . 1020 |\\n| MoE [32] | 26.03 | 40.56 | 2.0 \\u00b7 1019 | 1.2 . 1020 |\\n| Deep-Att + PosUnk Ensemble [39] | | 40.4 | | 8.0 . 1020 |\\n| GNMT + RL Ensemble [38] | 26.30 | 41.16 | 1.8 . 1020 | 1.1 . 1021 |\\n| ConvS2S Ensemble [9] | 26.36 | 41.29 | 7.7 . 1019 | 1.2 . 1021 |\\n| Transformer (base model) | 27.3 | 38.1 | 3.3 . | 1018 |\\n| Transformer (big) | 28.4 | 41.8 | 2.3. 1019 | |",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.141,\n avgOcrConfidence: 0.893,\n },\n polygon: [\n {\n x: 271.150136516042,\n y: 195.3426247575229,\n },\n {\n x: 1004.1704442379248,\n y: 195.3426247575229,\n },\n {\n x: 1004.1704442379248,\n y: 508.6132290201976,\n },\n {\n x: 271.150136516042,\n y: 508.6132290201976,\n },\n ],\n boundingBox: {\n left: 271.150136516042,\n top: 195.3426247575229,\n right: 1004.1704442379248,\n bottom: 508.6132290201976,\n },\n },\n {\n id: "block_8_Wl0xmI",\n type: "text",\n content:\n "Residual Dropout We apply dropout [33] to the output of each sub-layer, before it is added to the sub-layer input and normalized. In addition, we apply dropout to the sums of the embeddings and the positional encodings in both the encoder and decoder stacks. For the base model, we use a rate of Pdrop =0.1.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.893,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 223.9333605244212,\n y: 569.1121117154458,\n },\n {\n x: 1051.605887308608,\n y: 569.1121117154458,\n },\n {\n x: 1051.605887308608,\n y: 660.0886577520155,\n },\n {\n x: 223.9333605244212,\n y: 660.0886577520155,\n },\n ],\n boundingBox: {\n left: 223.9333605244212,\n top: 569.1121117154458,\n right: 1051.605887308608,\n bottom: 660.0886577520155,\n },\n },\n {\n id: "block_8_CtqTnb",\n type: "text",\n content:\n "Label Smoothing During training, we employed label smoothing of value Els = 0.1 [36]. This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.518,\n avgOcrConfidence: 0.977,\n },\n polygon: [\n {\n x: 223.52019122047145,\n y: 690.790115499855,\n },\n {\n x: 1049.6801780088103,\n y: 690.790115499855,\n },\n {\n x: 1049.6801780088103,\n y: 734.1354363233523,\n },\n {\n x: 223.52019122047145,\n y: 734.1354363233523,\n },\n ],\n boundingBox: {\n left: 223.52019122047145,\n top: 690.790115499855,\n right: 1049.6801780088103,\n bottom: 734.1354363233523,\n },\n },\n {\n id: "block_8_KA1kZT",\n type: "heading",\n content: "# 6 Results",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.16400352533717,\n y: 774.585115131579,\n },\n {\n x: 339.42863018843383,\n y: 774.585115131579,\n },\n {\n x: 339.42863018843383,\n y: 793.809935433524,\n },\n {\n x: 224.16400352533717,\n y: 793.809935433524,\n },\n ],\n boundingBox: {\n left: 224.16400352533717,\n top: 774.585115131579,\n right: 339.42863018843383,\n bottom: 793.809935433524,\n },\n },\n {\n id: "block_8_LYkEL8",\n type: "section_heading",\n content: "### 6.1 Machine Translation",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 224.2968510537252,\n y: 828.3471990026029,\n },\n {\n x: 455.2866330111984,\n y: 828.3471990026029,\n },\n {\n x: 455.2866330111984,\n y: 844.3720339438072,\n },\n {\n x: 224.2968510537252,\n y: 844.3720339438072,\n },\n ],\n boundingBox: {\n left: 224.2968510537252,\n top: 828.3471990026029,\n right: 455.2866330111984,\n bottom: 844.3720339438072,\n },\n },\n {\n id: "block_8_UnI1Ea",\n type: "text",\n content:\n "On the WMT 2014 English-to-German translation task, the big transformer model (Transformer (big) in Table 2) outperforms the best previously reported models (including ensembles) by more than 2.0 BLEU, establishing a new state-of-the-art BLEU score of 28.4. The configuration of this model is listed in the bottom line of Table 3. Training took 3.5 days on 8 P100 GPUs. Even our base model surpasses all previously published models and ensembles, at a fraction of the training cost of any of the competitive models.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.973,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.56291165317063,\n y: 872.0711140453367,\n },\n {\n x: 1050.5385628581919,\n y: 872.0711140453367,\n },\n {\n x: 1050.5385628581919,\n y: 1006.0390107004266,\n },\n {\n x: 223.56291165317063,\n y: 1006.0390107004266,\n },\n ],\n boundingBox: {\n left: 223.56291165317063,\n top: 872.0711140453367,\n right: 1050.5385628581919,\n bottom: 1006.0390107004266,\n },\n },\n {\n id: "block_8_pkBARc",\n type: "text",\n content:\n "On the WMT 2014 English-to-French translation task, our big model achieves a BLEU score of 41.0, outperforming all of the previously published single models, at less than 1/4 the training cost of the previous state-of-the-art model. The Transformer (big) model trained for English-to-French used dropout rate Pdrop = 0.1, instead of 0.3.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.945,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.05139199138557,\n y: 1019.1086798072756,\n },\n {\n x: 1052.2523977460653,\n y: 1019.1086798072756,\n },\n {\n x: 1052.2523977460653,\n y: 1109.5784446888401,\n },\n {\n x: 224.05139199138557,\n y: 1109.5784446888401,\n },\n ],\n boundingBox: {\n left: 224.05139199138557,\n top: 1019.1086798072756,\n right: 1052.2523977460653,\n bottom: 1109.5784446888401,\n },\n },\n {\n id: "block_8_vKs7Yg",\n type: "text",\n content:\n "For the base models, we used a single model obtained by averaging the last 5 checkpoints, which were written at 10-minute intervals. For the big models, we averaged the last 20 checkpoints. We used beam search with a beam size of 4 and length penalty & = 0.6 [38]. These hyperparameters were chosen after experimentation on the development set. We set the maximum output length during inference to input length + 50, but terminate early when possible [38].",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.099,\n avgOcrConfidence: 0.983,\n },\n polygon: [\n {\n x: 223.50279536560504,\n y: 1122.2645474197273,\n },\n {\n x: 1050.043905216412,\n y: 1122.2645474197273,\n },\n {\n x: 1050.043905216412,\n y: 1233.5787297872673,\n },\n {\n x: 223.50279536560504,\n y: 1233.5787297872673,\n },\n ],\n boundingBox: {\n left: 223.50279536560504,\n top: 1122.2645474197273,\n right: 1050.043905216412,\n bottom: 1233.5787297872673,\n },\n },\n {\n id: "block_8_42PSVl",\n type: "text",\n content:\n "Table 2 summarizes our results and compares our translation quality and training costs to other model architectures from the literature. We estimate the number of floating point operations used to train a model by multiplying the training time, the number of GPUs used, and an estimate of the sustained single-precision floating-point capacity of each GPU 5.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.975,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 222.3879459130503,\n y: 1247.2785842436597,\n },\n {\n x: 1049.63284234931,\n y: 1247.2785842436597,\n },\n {\n x: 1049.63284234931,\n y: 1336.1913537620603,\n },\n {\n x: 222.3879459130503,\n y: 1336.1913537620603,\n },\n ],\n boundingBox: {\n left: 222.3879459130503,\n top: 1247.2785842436597,\n right: 1049.63284234931,\n bottom: 1336.1913537620603,\n },\n },\n {\n id: "block_8_pDx0nB",\n type: "section_heading",\n content: "### 6.2 Model Variations",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.05955739264942,\n y: 1370.9984397027727,\n },\n {\n x: 424.93188398597886,\n y: 1370.9984397027727,\n },\n {\n x: 424.93188398597886,\n y: 1387.4261614003576,\n },\n {\n x: 224.05955739264942,\n y: 1387.4261614003576,\n },\n ],\n boundingBox: {\n left: 224.05955739264942,\n top: 1370.9984397027727,\n right: 424.93188398597886,\n bottom: 1387.4261614003576,\n },\n },\n {\n id: "block_8_XCLvsN",\n type: "text",\n content:\n "To evaluate the importance of different components of the Transformer, we varied our base model in different ways, measuring the change in performance on English-to-German translation on the",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.6526705888066,\n y: 1413.835037862448,\n },\n {\n x: 1049.9819901737853,\n y: 1413.835037862448,\n },\n {\n x: 1049.9819901737853,\n y: 1458.0598621798638,\n },\n {\n x: 222.6526705888066,\n y: 1458.0598621798638,\n },\n ],\n boundingBox: {\n left: 222.6526705888066,\n top: 1413.835037862448,\n right: 1049.9819901737853,\n bottom: 1458.0598621798638,\n },\n },\n {\n id: "block_8_6e9VRc",\n type: "text",\n content:\n "5We used values of 2.8, 3.7, 6.0 and 9.5 TFLOPS for K80, K40, M40 and P100, respectively.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.976,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 249.0640041601919,\n y: 1482.8447849015545,\n },\n {\n x: 944.2274051861172,\n y: 1482.8447849015545,\n },\n {\n x: 944.2274051861172,\n y: 1505.4603319670025,\n },\n {\n x: 249.0640041601919,\n y: 1505.4603319670025,\n },\n ],\n boundingBox: {\n left: 249.0640041601919,\n top: 1482.8447849015545,\n right: 944.2274051861172,\n bottom: 1505.4603319670025,\n },\n },\n {\n id: "block_8_HHxEh9",\n type: "page_number",\n content: "8",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.996,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 631.7743259624843,\n y: 1547.954182789738,\n },\n {\n x: 642.6607229413778,\n y: 1547.954182789738,\n },\n {\n x: 642.6607229413778,\n y: 1563.2957013352473,\n },\n {\n x: 631.7743259624843,\n y: 1563.2957013352473,\n },\n ],\n boundingBox: {\n left: 631.7743259624843,\n top: 1547.954182789738,\n right: 642.6607229413778,\n bottom: 1563.2957013352473,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_9_2CG18E",\n type: "text",\n content:\n "Table 3: Variations on the Transformer architecture. Unlisted values are identical to those of the base model. All metrics are on the English-to-German translation development set, newstest2013. Listed perplexities are per-wordpiece, according to our byte-pair encoding, and should not be compared to per-word perplexities.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 222.6654748847015,\n y: 147.86792777355453,\n },\n {\n x: 1049.6700481776775,\n y: 147.86792777355453,\n },\n {\n x: 1049.6700481776775,\n y: 237.19010704442076,\n },\n {\n x: 222.6654748847015,\n y: 237.19010704442076,\n },\n ],\n boundingBox: {\n left: 222.6654748847015,\n top: 147.86792777355453,\n right: 1049.6700481776775,\n bottom: 237.19010704442076,\n },\n },\n {\n id: "block_9_0WToWH",\n type: "table",\n content:\n "| | N | dmodel | dff | h | dk | dv | Pdrop | Els | train steps | PPL (dev) | BLEU (dev) | params \\u00d7106 |\\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\\n| base | 6 | 512 | 2048 | 8 | 64 | 64 | 0.1 | 0.1 | 100K | 4.92 | 25.8 | 65 |\\n| (A) | | | | 1 | 512 | 512 | | | | 5.29 | 24.9 | |\\n| | | | | 4 | 128 | 128 | | | | 5.00 | 25.5 | |\\n| | | | | 16 | 32 | 32 | | | | 4.91 | 25.8 | |\\n| | | | | 32 | 16 | 16 | | | | 5.01 | 25.4 | |\\n| (B) | | | | | 16 | | | | | 5.16 | 25.1 | 58 |\\n| | | | | | 32 | | | | | 5.01 | 25.4 | 60 |\\n| (C) | 2 | | | | | | | | | 6.11 | 23.7 | 36 |\\n| | 4 | | | | | | | | | 5.19 | 25.3 | 50 |\\n| | 8 | | | | | | | | | 4.88 | 25.5 | 80 |\\n| | | 256 | | | 32 | 32 | | | | 5.75 | 24.5 | 28 |\\n| | | 1024 | | | 128 | 128 | | | | 4.66 | 26.0 | 168 |\\n| | | | 1024 | | | | | | | 5.12 | 25.4 | 53 |\\n| | | | 4096 | | | | | | | 4.75 | 26.2 | 90 |\\n| (D) | | | | | | | 0.0 | | | 5.77 | 24.6 | |\\n| | | | | | | | 0.2 | | | 4.95 | 25.5 | |\\n| | | | | | | | | 0.0 | | 4.67 | 25.3 | |\\n| | | | | | | | | 0.2 | | 5.47 | 25.7 | |\\n| (E) | positional embedding | | | | | instead of | sinusoids | | | 4.92 | 25.7 | |\\n| big | 6 | 1024 | 4096 | 16 | | | 0.3 | | 300K | 4.33 | 26.4 | 213 |",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.612,\n avgOcrConfidence: 0.986,\n },\n polygon: [\n {\n x: 224.84461930546448,\n y: 268.65403318763674,\n },\n {\n x: 1060.6742636130673,\n y: 268.65403318763674,\n },\n {\n x: 1060.6742636130673,\n y: 801.2216690178204,\n },\n {\n x: 224.84461930546448,\n y: 801.2216690178204,\n },\n ],\n boundingBox: {\n left: 224.84461930546448,\n top: 268.65403318763674,\n right: 1060.6742636130673,\n bottom: 801.2216690178204,\n },\n },\n {\n id: "block_9_p8WB9c",\n type: "text",\n content:\n "development set, newstest2013. We used beam search as described in the previous section, but no checkpoint averaging. We present these results in Table 3.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.42882287241247,\n y: 862.6040329323675,\n },\n {\n x: 1049.5265264580719,\n y: 862.6040329323675,\n },\n {\n x: 1049.5265264580719,\n y: 905.6541023541213,\n },\n {\n x: 224.42882287241247,\n y: 905.6541023541213,\n },\n ],\n boundingBox: {\n left: 224.42882287241247,\n top: 862.6040329323675,\n right: 1049.5265264580719,\n bottom: 905.6541023541213,\n },\n },\n {\n id: "block_9_XvsIA2",\n type: "text",\n content:\n "In Table 3 rows (A), we vary the number of attention heads and the attention key and value dimensions, keeping the amount of computation constant, as described in Section 3.2.2. While single-head attention is 0.9 BLEU worse than the best setting, quality also drops off with too many heads.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.967,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.23600106343736,\n y: 918.8913094656807,\n },\n {\n x: 1052.034559041044,\n y: 918.8913094656807,\n },\n {\n x: 1052.034559041044,\n y: 986.1080494357232,\n },\n {\n x: 224.23600106343736,\n y: 986.1080494357232,\n },\n ],\n boundingBox: {\n left: 224.23600106343736,\n top: 918.8913094656807,\n right: 1052.034559041044,\n bottom: 986.1080494357232,\n },\n },\n {\n id: "block_9_lFHLbG",\n type: "text",\n content:\n "In Table 3 rows (B), we observe that reducing the attention key size dk hurts model quality. This suggests that determining compatibility is not easy and that a more sophisticated compatibility function than dot product may be beneficial. We further observe in rows (C) and (D) that, as expected, bigger models are better, and dropout is very helpful in avoiding over-fitting. In row (E) we replace our sinusoidal positional encoding with learned positional embeddings [9], and observe nearly identical results to the base model.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.881,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.0262804240206,\n y: 998.9746651326803,\n },\n {\n x: 1052.338643317675,\n y: 998.9746651326803,\n },\n {\n x: 1052.338643317675,\n y: 1130.1984048140678,\n },\n {\n x: 224.0262804240206,\n y: 1130.1984048140678,\n },\n ],\n boundingBox: {\n left: 224.0262804240206,\n top: 998.9746651326803,\n right: 1052.338643317675,\n bottom: 1130.1984048140678,\n },\n },\n {\n id: "block_9_nnE2Kn",\n type: "section_heading",\n content: "### 6.3 English Constituency Parsing",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.00199723069687,\n y: 1168.0604785546325,\n },\n {\n x: 533.1579584274849,\n y: 1168.0604785546325,\n },\n {\n x: 533.1579584274849,\n y: 1188.5333575485345,\n },\n {\n x: 224.00199723069687,\n y: 1188.5333575485345,\n },\n ],\n boundingBox: {\n left: 224.00199723069687,\n top: 1168.0604785546325,\n right: 533.1579584274849,\n bottom: 1188.5333575485345,\n },\n },\n {\n id: "block_9_UvLm1J",\n type: "text",\n content:\n "To evaluate if the Transformer can generalize to other tasks we performed experiments on English constituency parsing. This task presents specific challenges: the output is subject to strong structural constraints and is significantly longer than the input. Furthermore, RNN sequence-to-sequence models have not been able to attain state-of-the-art results in small-data regimes [37].",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.0787388599702,\n y: 1212.099580979885,\n },\n {\n x: 1049.9080518736457,\n y: 1212.099580979885,\n },\n {\n x: 1049.9080518736457,\n y: 1300.6617424183323,\n },\n {\n x: 223.0787388599702,\n y: 1300.6617424183323,\n },\n ],\n boundingBox: {\n left: 223.0787388599702,\n top: 1212.099580979885,\n right: 1049.9080518736457,\n bottom: 1300.6617424183323,\n },\n },\n {\n id: "block_9_nmNLPf",\n type: "text",\n content:\n "We trained a 4-layer transformer with dmodel = 1024 on the Wall Street Journal (WSJ) portion of the Penn Treebank [25], about 40K training sentences. We also trained it in a semi-supervised setting, using the larger high-confidence and BerkleyParser corpora from with approximately 17M sentences [37]. We used a vocabulary of 16K tokens for the WSJ only setting and a vocabulary of 32K tokens for the semi-supervised setting.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 223.08401678600453,\n y: 1314.1105266370273,\n },\n {\n x: 1051.1732393807738,\n y: 1314.1105266370273,\n },\n {\n x: 1051.1732393807738,\n y: 1425.9921031177494,\n },\n {\n x: 223.08401678600453,\n y: 1425.9921031177494,\n },\n ],\n boundingBox: {\n left: 223.08401678600453,\n top: 1314.1105266370273,\n right: 1051.1732393807738,\n bottom: 1425.9921031177494,\n },\n },\n {\n id: "block_9_kQhH3x",\n type: "text",\n content:\n "We performed only a small number of experiments to select the dropout, both attention and residual (section 5.4), learning rates and beam size on the Section 22 development set, all other parameters remained unchanged from the English-to-German base translation model. During inference, we",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.1762739863709,\n y: 1439.0945411051127,\n },\n {\n x: 1050.7557388639798,\n y: 1439.0945411051127,\n },\n {\n x: 1050.7557388639798,\n y: 1505.8386894168711,\n },\n {\n x: 223.1762739863709,\n y: 1505.8386894168711,\n },\n ],\n boundingBox: {\n left: 223.1762739863709,\n top: 1439.0945411051127,\n right: 1050.7557388639798,\n bottom: 1505.8386894168711,\n },\n },\n {\n id: "block_9_C4QuNg",\n type: "page_number",\n content: "9",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 631.6446262554531,\n y: 1547.2787271370566,\n },\n {\n x: 642.3550765879834,\n y: 1547.2787271370566,\n },\n {\n x: 642.3550765879834,\n y: 1562.906831325445,\n },\n {\n x: 631.6446262554531,\n y: 1562.906831325445,\n },\n ],\n boundingBox: {\n left: 631.6446262554531,\n top: 1547.2787271370566,\n right: 642.3550765879834,\n bottom: 1562.906831325445,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_10_Whfo1k",\n type: "text",\n content:\n "Table 4: The Transformer generalizes well to English constituency parsing (Results are on Section 23 of WSJ)",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.988,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.60232911492787,\n y: 147.913837353986,\n },\n {\n x: 1049.0453121435903,\n y: 147.913837353986,\n },\n {\n x: 1049.0453121435903,\n y: 190.50408882485297,\n },\n {\n x: 222.60232911492787,\n y: 190.50408882485297,\n },\n ],\n boundingBox: {\n left: 222.60232911492787,\n top: 147.913837353986,\n right: 1049.0453121435903,\n bottom: 190.50408882485297,\n },\n },\n {\n id: "block_10_Oq0boE",\n type: "table",\n content:\n "| Parser | Training | WSJ 23 F1 |\\n| --- | --- | --- |\\n| Vinyals & Kaiser el al. (2014) [37] | WSJ only, discriminative | 88.3 |\\n| Petrov et al. (2006) [29] | WSJ only, discriminative | 90.4 |\\n| Zhu et al. (2013) [40] | WSJ only, discriminative | 90.4 |\\n| Dyer et al. (2016) [8] | WSJ only, discriminative | 91.7 |\\n| Transformer (4 layers) | WSJ only, discriminative | 91.3 |\\n| Zhu et al. (2013) [40] | semi-supervised | 91.3 |\\n| Huang & Harper (2009) [14] | semi-supervised | 91.3 |\\n| McClosky et al. (2006) [26] | semi-supervised | 92.1 |\\n| Vinyals & Kaiser el al. (2014) [37] | semi-supervised | 92.1 |\\n| Transformer (4 layers) | semi-supervised | 92.7 |\\n| Luong et al. (2015) [23] | multi-task | 93.0 |\\n| Dyer et al. (2016) [8] | generative | 93.3 |",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.926,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 300.48226962124346,\n y: 193.81453893417702,\n },\n {\n x: 974.1206315312072,\n y: 193.81453893417702,\n },\n {\n x: 974.1206315312072,\n y: 493.68785631567016,\n },\n {\n x: 300.48226962124346,\n y: 493.68785631567016,\n },\n ],\n boundingBox: {\n left: 300.48226962124346,\n top: 193.81453893417702,\n right: 974.1206315312072,\n bottom: 493.68785631567016,\n },\n },\n {\n id: "block_10_wSUPzw",\n type: "text",\n content:\n "increased the maximum output length to input length + 300. We used a beam size of 21 and & = 0.3 for both WSJ only and the semi-supervised setting.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.117,\n avgOcrConfidence: 0.964,\n },\n polygon: [\n {\n x: 223.84354111051908,\n y: 546.3992524398001,\n },\n {\n x: 1049.2353174808252,\n y: 546.3992524398001,\n },\n {\n x: 1049.2353174808252,\n y: 589.787902057619,\n },\n {\n x: 223.84354111051908,\n y: 589.787902057619,\n },\n ],\n boundingBox: {\n left: 223.84354111051908,\n top: 546.3992524398001,\n right: 1049.2353174808252,\n bottom: 589.787902057619,\n },\n },\n {\n id: "block_10_KdYXbX",\n type: "text",\n content:\n "Our results in Table 4 show that despite the lack of task-specific tuning our model performs sur- prisingly well, yielding better results than all previously reported models with the exception of the Recurrent Neural Network Grammar [8].",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.917,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.34470740548016,\n y: 603.5821801379211,\n },\n {\n x: 1052.1757139776746,\n y: 603.5821801379211,\n },\n {\n x: 1052.1757139776746,\n y: 667.7562916691143,\n },\n {\n x: 224.34470740548016,\n y: 667.7562916691143,\n },\n ],\n boundingBox: {\n left: 224.34470740548016,\n top: 603.5821801379211,\n right: 1052.1757139776746,\n bottom: 667.7562916691143,\n },\n },\n {\n id: "block_10_spL6f1",\n type: "text",\n content:\n "In contrast to RNN sequence-to-sequence models [37], the Transformer outperforms the Berkeley- Parser [29] even when training only on the WSJ training set of 40K sentences.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.907,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.93137242672216,\n y: 683.4819921909419,\n },\n {\n x: 1052.021589070341,\n y: 683.4819921909419,\n },\n {\n x: 1052.021589070341,\n y: 725.8283830513632,\n },\n {\n x: 223.93137242672216,\n y: 725.8283830513632,\n },\n ],\n boundingBox: {\n left: 223.93137242672216,\n top: 683.4819921909419,\n right: 1052.021589070341,\n bottom: 725.8283830513632,\n },\n },\n {\n id: "block_10_FpxS4M",\n type: "section_heading",\n content: "### 7 Conclusion",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.87968188654767,\n y: 760.911873552136,\n },\n {\n x: 380.37754949862074,\n y: 760.911873552136,\n },\n {\n x: 380.37754949862074,\n y: 780.8896204439321,\n },\n {\n x: 223.87968188654767,\n y: 780.8896204439321,\n },\n ],\n boundingBox: {\n left: 223.87968188654767,\n top: 760.911873552136,\n right: 380.37754949862074,\n bottom: 780.8896204439321,\n },\n },\n {\n id: "block_10_06Cxhy",\n type: "text",\n content:\n "In this work, we presented the Transformer, the first sequence transduction model based entirely on attention, replacing the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.7800876589587,\n y: 811.1846398948727,\n },\n {\n x: 1049.4503160462762,\n y: 811.1846398948727,\n },\n {\n x: 1049.4503160462762,\n y: 872.951422555106,\n },\n {\n x: 223.7800876589587,\n y: 872.951422555106,\n },\n ],\n boundingBox: {\n left: 223.7800876589587,\n top: 811.1846398948727,\n right: 1049.4503160462762,\n bottom: 872.951422555106,\n },\n },\n {\n id: "block_10_4PqBx5",\n type: "text",\n content:\n "For translation tasks, the Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers. On both WMT 2014 English-to-German and WMT 2014 English-to-French translation tasks, we achieve a new state of the art. In the former task our best model outperforms even all previously reported ensembles.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.91187013500797,\n y: 890.9364237390963,\n },\n {\n x: 1049.8108244290318,\n y: 890.9364237390963,\n },\n {\n x: 1049.8108244290318,\n y: 980.2941302536126,\n },\n {\n x: 223.91187013500797,\n y: 980.2941302536126,\n },\n ],\n boundingBox: {\n left: 223.91187013500797,\n top: 890.9364237390963,\n right: 1049.8108244290318,\n bottom: 980.2941302536126,\n },\n },\n {\n id: "block_10_9Aa2OZ",\n type: "text",\n content:\n "We are excited about the future of attention-based models and plan to apply them to other tasks. We plan to extend the Transformer to problems involving input and output modalities other than text and to investigate local, restricted attention mechanisms to efficiently handle large inputs and outputs such as images, audio and video. Making generation less sequential is another research goals of ours.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.985,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.4691397117002,\n y: 993.4156992059005,\n },\n {\n x: 1051.09778633953,\n y: 993.4156992059005,\n },\n {\n x: 1051.09778633953,\n y: 1081.8706514745727,\n },\n {\n x: 223.4691397117002,\n y: 1081.8706514745727,\n },\n ],\n boundingBox: {\n left: 223.4691397117002,\n top: 993.4156992059005,\n right: 1051.09778633953,\n bottom: 1081.8706514745727,\n },\n },\n {\n id: "block_10_eXUU9v",\n type: "text",\n content:\n "The code we used to train and evaluate our models is available at https://github.com/ tensorflow/tensor2tensor.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.94,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 222.4288912585182,\n y: 1095.2490678371344,\n },\n {\n x: 1050.6089983195284,\n y: 1095.2490678371344,\n },\n {\n x: 1050.6089983195284,\n y: 1136.225321719521,\n },\n {\n x: 222.4288912585182,\n y: 1136.225321719521,\n },\n ],\n boundingBox: {\n left: 222.4288912585182,\n top: 1095.2490678371344,\n right: 1050.6089983195284,\n bottom: 1136.225321719521,\n },\n },\n {\n id: "block_10_HbnFiy",\n type: "text",\n content:\n "Acknowledgements We are grateful to Nal Kalchbrenner and Stephan Gouws for their fruitful comments, corrections and inspiration.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.74068072242457,\n y: 1165.530171673997,\n },\n {\n x: 1049.9162882783987,\n y: 1165.530171673997,\n },\n {\n x: 1049.9162882783987,\n y: 1209.6124608319503,\n },\n {\n x: 223.74068072242457,\n y: 1209.6124608319503,\n },\n ],\n boundingBox: {\n left: 223.74068072242457,\n top: 1165.530171673997,\n right: 1049.9162882783987,\n bottom: 1209.6124608319503,\n },\n },\n {\n id: "block_10_FqHFgA",\n type: "section_heading",\n content: "### References",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.3401158465086,\n y: 1243.4205694557131,\n },\n {\n x: 340.41243086766156,\n y: 1243.4205694557131,\n },\n {\n x: 340.41243086766156,\n y: 1263.1433630921786,\n },\n {\n x: 224.3401158465086,\n y: 1263.1433630921786,\n },\n ],\n boundingBox: {\n left: 224.3401158465086,\n top: 1243.4205694557131,\n right: 340.41243086766156,\n bottom: 1263.1433630921786,\n },\n },\n {\n id: "block_10_PnBCYC",\n type: "text",\n content:\n "[1] Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint arXiv: 1607.06450, 2016.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 234.62492392881074,\n y: 1281.5349446346884,\n },\n {\n x: 1049.520940850251,\n y: 1281.5349446346884,\n },\n {\n x: 1049.520940850251,\n y: 1323.6168167573169,\n },\n {\n x: 234.62492392881074,\n y: 1323.6168167573169,\n },\n ],\n boundingBox: {\n left: 234.62492392881074,\n top: 1281.5349446346884,\n right: 1049.520940850251,\n bottom: 1323.6168167573169,\n },\n },\n {\n id: "block_10_sUAYRJ",\n type: "text",\n content:\n "[2] Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly learning to align and translate. CoRR, abs/1409.0473, 2014.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 233.7351792050104,\n y: 1342.1247941210754,\n },\n {\n x: 1048.5688313950586,\n y: 1342.1247941210754,\n },\n {\n x: 1048.5688313950586,\n y: 1385.6842018070079,\n },\n {\n x: 233.7351792050104,\n y: 1385.6842018070079,\n },\n ],\n boundingBox: {\n left: 233.7351792050104,\n top: 1342.1247941210754,\n right: 1048.5688313950586,\n bottom: 1385.6842018070079,\n },\n },\n {\n id: "block_10_cYNyCb",\n type: "text",\n content:\n "[3] Denny Britz, Anna Goldie, Minh-Thang Luong, and Quoc V. Le. Massive exploration of neural machine translation architectures. CoRR, abs/1703.03906, 2017.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.914,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 234.47555625525703,\n y: 1401.96474766552,\n },\n {\n x: 1050.0915248898693,\n y: 1401.96474766552,\n },\n {\n x: 1050.0915248898693,\n y: 1443.4021335687853,\n },\n {\n x: 234.47555625525703,\n y: 1443.4021335687853,\n },\n ],\n boundingBox: {\n left: 234.47555625525703,\n top: 1401.96474766552,\n right: 1050.0915248898693,\n bottom: 1443.4021335687853,\n },\n },\n {\n id: "block_10_akeHB3",\n type: "text",\n content:\n "[4] Jianpeng Cheng, Li Dong, and Mirella Lapata. Long short-term memory-networks for machine reading. arXiv preprint arXiv: 1601.06733, 2016.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.91,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 235.1935672063897,\n y: 1461.8473196961825,\n },\n {\n x: 1049.3358584216041,\n y: 1461.8473196961825,\n },\n {\n x: 1049.3358584216041,\n y: 1505.7106445427228,\n },\n {\n x: 235.1935672063897,\n y: 1505.7106445427228,\n },\n ],\n boundingBox: {\n left: 235.1935672063897,\n top: 1461.8473196961825,\n right: 1049.3358584216041,\n bottom: 1505.7106445427228,\n },\n },\n {\n id: "block_10_sJYSgt",\n type: "page_number",\n content: "10",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.999,\n avgOcrConfidence: 0.999,\n },\n polygon: [\n {\n x: 628.4902252420022,\n y: 1547.7831405983832,\n },\n {\n x: 647.7796484954166,\n y: 1547.7831405983832,\n },\n {\n x: 647.7796484954166,\n y: 1563.3856736950409,\n },\n {\n x: 628.4902252420022,\n y: 1563.3856736950409,\n },\n ],\n boundingBox: {\n left: 628.4902252420022,\n top: 1547.7831405983832,\n right: 647.7796484954166,\n bottom: 1563.3856736950409,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_11_VBbBwR",\n type: "text",\n content:\n "[5] Kyunghyun Cho, Bart van Merrienboer, Caglar Gulcehre, Fethi Bougares, Holger Schwenk, and Yoshua Bengio. Learning phrase representations using rnn encoder-decoder for statistical machine translation. CoRR, abs/1406.1078, 2014.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.932,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 234.95565818174043,\n y: 155.04768656967278,\n },\n {\n x: 1051.617910566121,\n y: 155.04768656967278,\n },\n {\n x: 1051.617910566121,\n y: 219.22101676195186,\n },\n {\n x: 234.95565818174043,\n y: 219.22101676195186,\n },\n ],\n boundingBox: {\n left: 234.95565818174043,\n top: 155.04768656967278,\n right: 1051.617910566121,\n bottom: 219.22101676195186,\n },\n },\n {\n id: "block_11_fZULb0",\n type: "text",\n content:\n "[6] Francois Chollet. Xception: Deep learning with depthwise separable convolutions. arXiv preprint arXiv: 1610.02357, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.916,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 234.37082610861228,\n y: 242.1581676597882,\n },\n {\n x: 1050.1136779785156,\n y: 242.1581676597882,\n },\n {\n x: 1050.1136779785156,\n y: 284.96119192309845,\n },\n {\n x: 234.37082610861228,\n y: 284.96119192309845,\n },\n ],\n boundingBox: {\n left: 234.37082610861228,\n top: 242.1581676597882,\n right: 1050.1136779785156,\n bottom: 284.96119192309845,\n },\n },\n {\n id: "block_11_KQxaZG",\n type: "text",\n content:\n "[7] Junyoung Chung, \\u00c7aglar G\\u00fcl\\u00e7ehre, Kyunghyun Cho, and Yoshua Bengio. Empirical evaluation of gated recurrent neural networks on sequence modeling. CoRR, abs/1412.3555, 2014.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.937,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 234.59709056102446,\n y: 305.8525607747243,\n },\n {\n x: 1050.252182118214,\n y: 305.8525607747243,\n },\n {\n x: 1050.252182118214,\n y: 348.70033444856347,\n },\n {\n x: 234.59709056102446,\n y: 348.70033444856347,\n },\n ],\n boundingBox: {\n left: 234.59709056102446,\n top: 305.8525607747243,\n right: 1050.252182118214,\n bottom: 348.70033444856347,\n },\n },\n {\n id: "block_11_lSxX1m",\n type: "text",\n content:\n "[8] Chris Dyer, Adhiguna Kuncoro, Miguel Ballesteros, and Noah A. Smith. Recurrent neural network grammars. In Proc. of NAACL, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.92,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 234.54393261540545,\n y: 369.88837531814,\n },\n {\n x: 1049.7648141679972,\n y: 369.88837531814,\n },\n {\n x: 1049.7648141679972,\n y: 412.63161531606113,\n },\n {\n x: 234.54393261540545,\n y: 412.63161531606113,\n },\n ],\n boundingBox: {\n left: 234.54393261540545,\n top: 369.88837531814,\n right: 1049.7648141679972,\n bottom: 412.63161531606113,\n },\n },\n {\n id: "block_11_3YLXoz",\n type: "text",\n content:\n "[9] Jonas Gehring, Michael Auli, David Grangier, Denis Yarats, and Yann N. Dauphin. Convolu- tional sequence to sequence learning. arXiv preprint arXiv: 1705.03122v2, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.927,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 233.81299902922916,\n y: 434.3302966813395,\n },\n {\n x: 1052.8067929901345,\n y: 434.3302966813395,\n },\n {\n x: 1052.8067929901345,\n y: 476.945989020785,\n },\n {\n x: 233.81299902922916,\n y: 476.945989020785,\n },\n ],\n boundingBox: {\n left: 233.81299902922916,\n top: 434.3302966813395,\n right: 1052.8067929901345,\n bottom: 476.945989020785,\n },\n },\n {\n id: "block_11_OkxRaO",\n type: "text",\n content:\n "[10] Alex Graves. Generating sequences with recurrent neural networks. arXiv preprint arXiv: 1308.0850, 2013.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.904,\n avgOcrConfidence: 0.986,\n },\n polygon: [\n {\n x: 224.38643378932983,\n y: 498.1091927836712,\n },\n {\n x: 1050.5877919440723,\n y: 498.1091927836712,\n },\n {\n x: 1050.5877919440723,\n y: 539.0395607625632,\n },\n {\n x: 224.38643378932983,\n y: 539.0395607625632,\n },\n ],\n boundingBox: {\n left: 224.38643378932983,\n top: 498.1091927836712,\n right: 1050.5877919440723,\n bottom: 539.0395607625632,\n },\n },\n {\n id: "block_11_RVnHcs",\n type: "text",\n content:\n "[11] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for im- age recognition. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 770-778, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.919,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.3475475450502,\n y: 561.9494121522832,\n },\n {\n x: 1053.1976908662893,\n y: 561.9494121522832,\n },\n {\n x: 1053.1976908662893,\n y: 627.2271530610278,\n },\n {\n x: 224.3475475450502,\n y: 627.2271530610278,\n },\n ],\n boundingBox: {\n left: 224.3475475450502,\n top: 561.9494121522832,\n right: 1053.1976908662893,\n bottom: 627.2271530610278,\n },\n },\n {\n id: "block_11_s96TQd",\n type: "text",\n content:\n "[12] Sepp Hochreiter, Yoshua Bengio, Paolo Frasconi, and J\\u00fcrgen Schmidhuber. Gradient flow in recurrent nets: the difficulty of learning long-term dependencies, 2001.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.892,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 224.27874516396628,\n y: 647.9830188034173,\n },\n {\n x: 1048.8635432111087,\n y: 647.9830188034173,\n },\n {\n x: 1048.8635432111087,\n y: 692.1669293740639,\n },\n {\n x: 224.27874516396628,\n y: 692.1669293740639,\n },\n ],\n boundingBox: {\n left: 224.27874516396628,\n top: 647.9830188034173,\n right: 1048.8635432111087,\n bottom: 692.1669293740639,\n },\n },\n {\n id: "block_11_bKrlBK",\n type: "text",\n content:\n "[13] Sepp Hochreiter and J\\u00fcrgen Schmidhuber. Long short-term memory. Neural computation, 9(8):1735-1780, 1997.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.903,\n avgOcrConfidence: 0.984,\n },\n polygon: [\n {\n x: 224.36335765532334,\n y: 712.3709330738038,\n },\n {\n x: 1051.7104044447851,\n y: 712.3709330738038,\n },\n {\n x: 1051.7104044447851,\n y: 754.2910917181719,\n },\n {\n x: 224.36335765532334,\n y: 754.2910917181719,\n },\n ],\n boundingBox: {\n left: 224.36335765532334,\n top: 712.3709330738038,\n right: 1051.7104044447851,\n bottom: 754.2910917181719,\n },\n },\n {\n id: "block_11_c3sQ7S",\n type: "text",\n content:\n "[14] Zhongqiang Huang and Mary Harper. Self-training PCFG grammars with latent annotations across languages. In Proceedings of the 2009 Conference on Empirical Methods in Natural Language Processing, pages 832-841. ACL, August 2009.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.70277800177138,\n y: 777.0990849258308,\n },\n {\n x: 1050.1772024335653,\n y: 777.0990849258308,\n },\n {\n x: 1050.1772024335653,\n y: 842.7015786995565,\n },\n {\n x: 224.70277800177138,\n y: 842.7015786995565,\n },\n ],\n boundingBox: {\n left: 224.70277800177138,\n top: 777.0990849258308,\n right: 1050.1772024335653,\n bottom: 842.7015786995565,\n },\n },\n {\n id: "block_11_HmSxMA",\n type: "text",\n content:\n "[15] Rafal Jozefowicz, Oriol Vinyals, Mike Schuster, Noam Shazeer, and Yonghui Wu. Exploring the limits of language modeling. arXiv preprint arXiv: 1602.02410, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.906,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 223.96287430811972,\n y: 863.015632801486,\n },\n {\n x: 1049.822942357864,\n y: 863.015632801486,\n },\n {\n x: 1049.822942357864,\n y: 907.0369301702743,\n },\n {\n x: 223.96287430811972,\n y: 907.0369301702743,\n },\n ],\n boundingBox: {\n left: 223.96287430811972,\n top: 863.015632801486,\n right: 1049.822942357864,\n bottom: 907.0369301702743,\n },\n },\n {\n id: "block_11_XlCObz",\n type: "text",\n content:\n "[16] \\u0141ukasz Kaiser and Samy Bengio. Can active memory replace attention? In Advances in Neural Information Processing Systems, (NIPS), 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.902,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.17545875493627,\n y: 927.1137413655905,\n },\n {\n x: 1050.2528448174469,\n y: 927.1137413655905,\n },\n {\n x: 1050.2528448174469,\n y: 970.5487977795134,\n },\n {\n x: 224.17545875493627,\n y: 970.5487977795134,\n },\n ],\n boundingBox: {\n left: 224.17545875493627,\n top: 927.1137413655905,\n right: 1050.2528448174469,\n bottom: 970.5487977795134,\n },\n },\n {\n id: "block_11_48mMcn",\n type: "text",\n content:\n "[17] \\u0141ukasz Kaiser and Ilya Sutskever. Neural GPUs learn algorithms. In International Conference on Learning Representations (ICLR), 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.903,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 224.42198286961465,\n y: 991.1752927392946,\n },\n {\n x: 1049.7810976348653,\n y: 991.1752927392946,\n },\n {\n x: 1049.7810976348653,\n y: 1034.8329123590227,\n },\n {\n x: 224.42198286961465,\n y: 1034.8329123590227,\n },\n ],\n boundingBox: {\n left: 224.42198286961465,\n top: 991.1752927392946,\n right: 1049.7810976348653,\n bottom: 1034.8329123590227,\n },\n },\n {\n id: "block_11_lBImir",\n type: "text",\n content:\n "[18] Nal Kalchbrenner, Lasse Espeholt, Karen Simonyan, Aaron van den Oord, Alex Graves, and Ko- ray Kavukcuoglu. Neural machine translation in linear time. arXiv preprint arXiv: 1610.10099v2, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.934,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.23202486803933,\n y: 1055.1385374714557,\n },\n {\n x: 1052.4190192675069,\n y: 1055.1385374714557,\n },\n {\n x: 1052.4190192675069,\n y: 1117.975328259002,\n },\n {\n x: 224.23202486803933,\n y: 1117.975328259002,\n },\n ],\n boundingBox: {\n left: 224.23202486803933,\n top: 1055.1385374714557,\n right: 1052.4190192675069,\n bottom: 1117.975328259002,\n },\n },\n {\n id: "block_11_Y0ddKF",\n type: "text",\n content:\n "[19] Yoon Kim, Carl Denton, Luong Hoang, and Alexander M. Rush. Structured attention networks. In International Conference on Learning Representations, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.974,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.29036606837366,\n y: 1142.1438929622334,\n },\n {\n x: 1052.7023705252766,\n y: 1142.1438929622334,\n },\n {\n x: 1052.7023705252766,\n y: 1185.793178300212,\n },\n {\n x: 224.29036606837366,\n y: 1185.793178300212,\n },\n ],\n boundingBox: {\n left: 224.29036606837366,\n top: 1142.1438929622334,\n right: 1052.7023705252766,\n bottom: 1185.793178300212,\n },\n },\n {\n id: "block_11_nehypx",\n type: "text",\n content:\n "[20] Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In ICLR, 2015.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 223.92950266817192,\n y: 1205.8213097134928,\n },\n {\n x: 1052.7550077786411,\n y: 1205.8213097134928,\n },\n {\n x: 1052.7550077786411,\n y: 1227.2851158658366,\n },\n {\n x: 223.92950266817192,\n y: 1227.2851158658366,\n },\n ],\n boundingBox: {\n left: 223.92950266817192,\n top: 1205.8213097134928,\n right: 1052.7550077786411,\n bottom: 1227.2851158658366,\n },\n },\n {\n id: "block_11_af7MVz",\n type: "text",\n content:\n "[21] Oleksii Kuchaiev and Boris Ginsburg. Factorization tricks for LSTM networks. arXiv preprint arXiv: 1703.10722, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.925,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 223.78512890669552,\n y: 1247.11833873548,\n },\n {\n x: 1050.4177622551465,\n y: 1247.11833873548,\n },\n {\n x: 1050.4177622551465,\n y: 1289.109575544085,\n },\n {\n x: 223.78512890669552,\n y: 1289.109575544085,\n },\n ],\n boundingBox: {\n left: 223.78512890669552,\n top: 1247.11833873548,\n right: 1050.4177622551465,\n bottom: 1289.109575544085,\n },\n },\n {\n id: "block_11_vnPlfZ",\n type: "text",\n content:\n "[22] Zhouhan Lin, Minwei Feng, Cicero Nogueira dos Santos, Mo Yu, Bing Xiang, Bowen Zhou, and Yoshua Bengio. A structured self-attentive sentence embedding. arXiv preprint arXiv: 1703.03130, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.74063338676507,\n y: 1311.0246641116034,\n },\n {\n x: 1050.2205618976677,\n y: 1311.0246641116034,\n },\n {\n x: 1050.2205618976677,\n y: 1375.8748468958345,\n },\n {\n x: 223.74063338676507,\n y: 1375.8748468958345,\n },\n ],\n boundingBox: {\n left: 223.74063338676507,\n top: 1311.0246641116034,\n right: 1050.2205618976677,\n bottom: 1375.8748468958345,\n },\n },\n {\n id: "block_11_g0SHxO",\n type: "text",\n content:\n "[23] Minh-Thang Luong, Quoc V. Le, Ilya Sutskever, Oriol Vinyals, and Lukasz Kaiser. Multi-task sequence to sequence learning. arXiv preprint arXiv: 1511.06114, 2015.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.355428932357,\n y: 1397.7982697451025,\n },\n {\n x: 1050.4997476174015,\n y: 1397.7982697451025,\n },\n {\n x: 1050.4997476174015,\n y: 1441.9434448471643,\n },\n {\n x: 224.355428932357,\n y: 1441.9434448471643,\n },\n ],\n boundingBox: {\n left: 224.355428932357,\n top: 1397.7982697451025,\n right: 1050.4997476174015,\n bottom: 1441.9434448471643,\n },\n },\n {\n id: "block_11_gDtqYI",\n type: "text",\n content:\n "[24] Minh-Thang Luong, Hieu Pham, and Christopher D Manning. Effective approaches to attention- based neural machine translation. arXiv preprint arXiv: 1508.04025, 2015.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.927,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 224.7064228475529,\n y: 1461.612349775501,\n },\n {\n x: 1052.9802308465444,\n y: 1461.612349775501,\n },\n {\n x: 1052.9802308465444,\n y: 1506.2439438669305,\n },\n {\n x: 224.7064228475529,\n y: 1506.2439438669305,\n },\n ],\n boundingBox: {\n left: 224.7064228475529,\n top: 1461.612349775501,\n right: 1052.9802308465444,\n bottom: 1506.2439438669305,\n },\n },\n {\n id: "block_11_JWTkzE",\n type: "page_number",\n content: "11",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 629.039650241824,\n y: 1547.854550239735,\n },\n {\n x: 645.38100862155,\n y: 1547.854550239735,\n },\n {\n x: 645.38100862155,\n y: 1563.4467601919532,\n },\n {\n x: 629.039650241824,\n y: 1563.4467601919532,\n },\n ],\n boundingBox: {\n left: 629.039650241824,\n top: 1547.854550239735,\n right: 645.38100862155,\n bottom: 1563.4467601919532,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_12_TQ4Lbe",\n type: "text",\n content:\n "[25] Mitchell P Marcus, Mary Ann Marcinkiewicz, and Beatrice Santorini. Building a large annotated corpus of english: The penn treebank. Computational linguistics, 19(2):313-330, 1993.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.94512343580706,\n y: 154.85743054411464,\n },\n {\n x: 1050.2930801280222,\n y: 154.85743054411464,\n },\n {\n x: 1050.2930801280222,\n y: 198.76930494953817,\n },\n {\n x: 223.94512343580706,\n y: 198.76930494953817,\n },\n ],\n boundingBox: {\n left: 223.94512343580706,\n top: 154.85743054411464,\n right: 1050.2930801280222,\n bottom: 198.76930494953817,\n },\n },\n {\n id: "block_12_LvCkff",\n type: "text",\n content:\n "[26] David McClosky, Eugene Charniak, and Mark Johnson. Effective self-training for parsing. In Proceedings of the Human Language Technology Conference of the NAACL, Main Conference, pages 152-159. ACL, June 2006.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.907,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.21323261121762,\n y: 226.782506971431,\n },\n {\n x: 1051.9384676522582,\n y: 226.782506971431,\n },\n {\n x: 1051.9384676522582,\n y: 292.8687442406676,\n },\n {\n x: 224.21323261121762,\n y: 292.8687442406676,\n },\n ],\n boundingBox: {\n left: 224.21323261121762,\n top: 226.782506971431,\n right: 1051.9384676522582,\n bottom: 292.8687442406676,\n },\n },\n {\n id: "block_12_Rm8AFL",\n type: "text",\n content:\n "[27] Ankur Parikh, Oscar T\\u00e4ckstr\\u00f6m, Dipanjan Das, and Jakob Uszkoreit. A decomposable attention model. In Empirical Methods in Natural Language Processing, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.916,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.08847948060418,\n y: 321.2656073462694,\n },\n {\n x: 1048.8436622341185,\n y: 321.2656073462694,\n },\n {\n x: 1048.8436622341185,\n y: 364.85913349811295,\n },\n {\n x: 224.08847948060418,\n y: 364.85913349811295,\n },\n ],\n boundingBox: {\n left: 224.08847948060418,\n top: 321.2656073462694,\n right: 1048.8436622341185,\n bottom: 364.85913349811295,\n },\n },\n {\n id: "block_12_cqas9e",\n type: "text",\n content:\n "[28] Romain Paulus, Caiming Xiong, and Richard Socher. A deep reinforced model for abstractive summarization. arXiv preprint arXiv: 1705.04304, 2017.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.67392691730583,\n y: 392.7383714116606,\n },\n {\n x: 1049.3349117084142,\n y: 392.7383714116606,\n },\n {\n x: 1049.3349117084142,\n y: 435.42904860991285,\n },\n {\n x: 224.67392691730583,\n y: 435.42904860991285,\n },\n ],\n boundingBox: {\n left: 224.67392691730583,\n top: 392.7383714116606,\n right: 1049.3349117084142,\n bottom: 435.42904860991285,\n },\n },\n {\n id: "block_12_hfa5dB",\n type: "text",\n content:\n "[29] Slav Petrov, Leon Barrett, Romain Thibaux, and Dan Klein. Learning accurate, compact, and interpretable tree annotation. In Proceedings of the 21st International Conference on Computational Linguistics and 44th Annual Meeting of the ACL, pages 433-440. ACL, July 2006.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.899,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.91392923619625,\n y: 463.67279296530813,\n },\n {\n x: 1051.5214404920591,\n y: 463.67279296530813,\n },\n {\n x: 1051.5214404920591,\n y: 549.7230681799408,\n },\n {\n x: 223.91392923619625,\n y: 549.7230681799408,\n },\n ],\n boundingBox: {\n left: 223.91392923619625,\n top: 463.67279296530813,\n right: 1051.5214404920591,\n bottom: 549.7230681799408,\n },\n },\n {\n id: "block_12_H2k7w4",\n type: "text",\n content:\n "[30] Ofir Press and Lior Wolf. Using the output embedding to improve language models. arXiv preprint arXiv: 1608.05859, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.898,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 224.29183347381814,\n y: 581.8894180068396,\n },\n {\n x: 1049.7876299558764,\n y: 581.8894180068396,\n },\n {\n x: 1049.7876299558764,\n y: 624.918793785841,\n },\n {\n x: 224.29183347381814,\n y: 624.918793785841,\n },\n ],\n boundingBox: {\n left: 224.29183347381814,\n top: 581.8894180068396,\n right: 1049.7876299558764,\n bottom: 624.918793785841,\n },\n },\n {\n id: "block_12_UrZIEK",\n type: "text",\n content:\n "[31] Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words with subword units. arXiv preprint arXiv: 1508.07909, 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.925,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.35140540129947,\n y: 653.3260510666926,\n },\n {\n x: 1049.4855337769445,\n y: 653.3260510666926,\n },\n {\n x: 1049.4855337769445,\n y: 696.2955715494944,\n },\n {\n x: 224.35140540129947,\n y: 696.2955715494944,\n },\n ],\n boundingBox: {\n left: 224.35140540129947,\n top: 653.3260510666926,\n right: 1049.4855337769445,\n bottom: 696.2955715494944,\n },\n },\n {\n id: "block_12_IIwlxZ",\n type: "text",\n content:\n "[32] Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz, Andy Davis, Quoc Le, Geoffrey Hinton, and Jeff Dean. Outrageously large neural networks: The sparsely-gated mixture-of-experts layer. arXiv preprint arXiv: 1701.06538, 2017.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.88,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.15238262092979,\n y: 724.7319041087216,\n },\n {\n x: 1051.274348349467,\n y: 724.7319041087216,\n },\n {\n x: 1051.274348349467,\n y: 791.0497254966793,\n },\n {\n x: 224.15238262092979,\n y: 791.0497254966793,\n },\n ],\n boundingBox: {\n left: 224.15238262092979,\n top: 724.7319041087216,\n right: 1051.274348349467,\n bottom: 791.0497254966793,\n },\n },\n {\n id: "block_12_pGLzhM",\n type: "text",\n content:\n "[33] Nitish Srivastava, Geoffrey E Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdi- nov. Dropout: a simple way to prevent neural networks from overfitting. Journal of Machine Learning Research, 15(1):1929-1958, 2014.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.938,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.4417928431156,\n y: 819.0001126052741,\n },\n {\n x: 1053.3042907714844,\n y: 819.0001126052741,\n },\n {\n x: 1053.3042907714844,\n y: 885.2761205228649,\n },\n {\n x: 224.4417928431156,\n y: 885.2761205228649,\n },\n ],\n boundingBox: {\n left: 224.4417928431156,\n top: 819.0001126052741,\n right: 1053.3042907714844,\n bottom: 885.2761205228649,\n },\n },\n {\n id: "block_12_Bz8MfK",\n type: "text",\n content:\n "[34] Sainbayar Sukhbaatar, Arthur Szlam, Jason Weston, and Rob Fergus. End-to-end memory networks. In C. Cortes, N. D. Lawrence, D. D. Lee, M. Sugiyama, and R. Garnett, editors, Advances in Neural Information Processing Systems 28, pages 2440-2448. Curran Associates, Inc., 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.897,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.0948934624665,\n y: 913.8373252467105,\n },\n {\n x: 1051.823347328353,\n y: 913.8373252467105,\n },\n {\n x: 1051.823347328353,\n y: 1000.8878563328793,\n },\n {\n x: 224.0948934624665,\n y: 1000.8878563328793,\n },\n ],\n boundingBox: {\n left: 224.0948934624665,\n top: 913.8373252467105,\n right: 1051.823347328353,\n bottom: 1000.8878563328793,\n },\n },\n {\n id: "block_12_m0nnSr",\n type: "text",\n content:\n "[35] Ilya Sutskever, Oriol Vinyals, and Quoc VV Le. Sequence to sequence learning with neural networks. In Advances in Neural Information Processing Systems, pages 3104-3112, 2014.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.899,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.52872478178818,\n y: 1030.965426796361,\n },\n {\n x: 1050.1110271815835,\n y: 1030.965426796361,\n },\n {\n x: 1050.1110271815835,\n y: 1074.9609636579241,\n },\n {\n x: 224.52872478178818,\n y: 1074.9609636579241,\n },\n ],\n boundingBox: {\n left: 224.52872478178818,\n top: 1030.965426796361,\n right: 1050.1110271815835,\n bottom: 1074.9609636579241,\n },\n },\n {\n id: "block_12_C1nzdD",\n type: "text",\n content:\n "[36] Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, and Zbigniew Wojna. Rethinking the inception architecture for computer vision. CoRR, abs/1512.00567, 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.939,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.60145602261062,\n y: 1102.9526906981505,\n },\n {\n x: 1051.9790816481095,\n y: 1102.9526906981505,\n },\n {\n x: 1051.9790816481095,\n y: 1146.15116715969,\n },\n {\n x: 224.60145602261062,\n y: 1146.15116715969,\n },\n ],\n boundingBox: {\n left: 224.60145602261062,\n top: 1102.9526906981505,\n right: 1051.9790816481095,\n bottom: 1146.15116715969,\n },\n },\n {\n id: "block_12_smJ629",\n type: "text",\n content:\n "[37] Vinyals & Kaiser, Koo, Petrov, Sutskever, and Hinton. Grammar as a foreign language. In Advances in Neural Information Processing Systems, 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.70363004364236,\n y: 1173.716330506748,\n },\n {\n x: 1049.93891472364,\n y: 1173.716330506748,\n },\n {\n x: 1049.93891472364,\n y: 1218.0808487512115,\n },\n {\n x: 224.70363004364236,\n y: 1218.0808487512115,\n },\n ],\n boundingBox: {\n left: 224.70363004364236,\n top: 1173.716330506748,\n right: 1049.93891472364,\n bottom: 1218.0808487512115,\n },\n },\n {\n id: "block_12_oKrqzS",\n type: "text",\n content:\n "[38] Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. Google\'s neural machine translation system: Bridging the gap between human and machine translation. arXiv preprint arXiv: 1609.08144, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.935,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.222865417926,\n y: 1246.0137622804568,\n },\n {\n x: 1050.4285547855127,\n y: 1246.0137622804568,\n },\n {\n x: 1050.4285547855127,\n y: 1332.3901636224045,\n },\n {\n x: 224.222865417926,\n y: 1332.3901636224045,\n },\n ],\n boundingBox: {\n left: 224.222865417926,\n top: 1246.0137622804568,\n right: 1050.4285547855127,\n bottom: 1332.3901636224045,\n },\n },\n {\n id: "block_12_5hQUgX",\n type: "text",\n content:\n "[39] Jie Zhou, Ying Cao, Xuguang Wang, Peng Li, and Wei Xu. Deep recurrent models with fast-forward connections for neural machine translation. CoRR, abs/1606.04199, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.977,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.40534438530025,\n y: 1362.7727877394598,\n },\n {\n x: 1049.6643678985372,\n y: 1362.7727877394598,\n },\n {\n x: 1049.6643678985372,\n y: 1404.796982844073,\n },\n {\n x: 224.40534438530025,\n y: 1404.796982844073,\n },\n ],\n boundingBox: {\n left: 224.40534438530025,\n top: 1362.7727877394598,\n right: 1049.6643678985372,\n bottom: 1404.796982844073,\n },\n },\n {\n id: "block_12_7qyMnf",\n type: "text",\n content:\n "[40] Muhua Zhu, Yue Zhang, Wenliang Chen, Min Zhang, and Jingbo Zhu. Fast and accurate shift-reduce constituent parsing. In Proceedings of the 51st Annual Meeting of the ACL (Volume 1: Long Papers), pages 434-443. ACL, August 2013.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.905,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.04902520841057,\n y: 1434.5126750056904,\n },\n {\n x: 1049.9945814592124,\n y: 1434.5126750056904,\n },\n {\n x: 1049.9945814592124,\n y: 1501.148572362455,\n },\n {\n x: 224.04902520841057,\n y: 1501.148572362455,\n },\n ],\n boundingBox: {\n left: 224.04902520841057,\n top: 1434.5126750056904,\n right: 1049.9945814592124,\n bottom: 1501.148572362455,\n },\n },\n {\n id: "block_12_6o6JUd",\n type: "page_number",\n content: "12",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.998,\n avgOcrConfidence: 0.998,\n },\n polygon: [\n {\n x: 628.997000812614,\n y: 1547.789391309695,\n },\n {\n x: 647.0427269483133,\n y: 1547.789391309695,\n },\n {\n x: 647.0427269483133,\n y: 1563.398364533159,\n },\n {\n x: 628.997000812614,\n y: 1563.398364533159,\n },\n ],\n boundingBox: {\n left: 628.997000812614,\n top: 1547.789391309695,\n right: 647.0427269483133,\n bottom: 1563.398364533159,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_13_KlKk5h",\n type: "page_number",\n content: "13",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.999,\n avgOcrConfidence: 0.999,\n },\n polygon: [\n {\n x: 103.29433033878627,\n y: 628.7723457726248,\n },\n {\n x: 103.29433033878627,\n y: 646.9001519418981,\n },\n {\n x: 87.59273293860883,\n y: 646.9001519418981,\n },\n {\n x: 87.59273293860883,\n y: 628.7723457726248,\n },\n ],\n boundingBox: {\n left: 87.59273293860883,\n top: 628.7723457726248,\n right: 103.29433033878627,\n bottom: 646.9001519418981,\n },\n },\n {\n id: "block_13_PkaOm5",\n type: "text",\n content:\n "the word \'making\'. Different colors represent different heads. Best viewed in color. the verb \'making\', completing the phrase \'making ... more difficult\'. Attentions here shown only for encoder self-attention in layer 5 of 6. Many of the attention heads attend to a distant dependency of Figure 3: An example of the attention mechanism following long-distance dependencies in the",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.937,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 999.8870322148603,\n y: 224.33585563715354,\n },\n {\n x: 999.8870322148603,\n y: 1052.0067256732577,\n },\n {\n x: 911.037953656419,\n y: 1052.0067256732577,\n },\n {\n x: 911.037953656419,\n y: 224.33585563715354,\n },\n ],\n boundingBox: {\n left: 911.037953656419,\n top: 224.33585563715354,\n right: 999.8870322148603,\n bottom: 1052.0067256732577,\n },\n },\n {\n id: "block_13_xamkHQ",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nIt It is is in in this this spirit spirit that that a a majority majority of of American American governments governments have have passed passed new new laws laws since since 2009 2009 making making the the registration registration or or voting voting process process more more difficult difficult\\n\\n. . <EOS> <EOS> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad>\\n<caption>Diagram showing attention mechanism or word alignment between two identical sequences of text. The word \'making\' in the right column is highlighted in gray and acts as the target for connections from the left column. Connections originate from the words \'laws\', \'2009\', \'making\', \'more\', and \'difficult\' in the left column and point to \'making\' in the right column. The sequence of text is: \'It is in this spirit that a majority of American governments have passed new laws since 2009 making the registration or voting process more difficult. <EOS> <pad> <pad> <pad> <pad> <pad> <pad> <pad>\'</caption>\\n</figure>",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.717,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 1444.0009233001479,\n y: 252.8656019781628,\n },\n {\n x: 1444.0009233001479,\n y: 1047.5539548553688,\n },\n {\n x: 1022.9538143416097,\n y: 1047.5539548553688,\n },\n {\n x: 1022.9538143416097,\n y: 252.8656019781628,\n },\n ],\n boundingBox: {\n left: 1022.9538143416097,\n top: 252.8656019781628,\n right: 1444.0009233001479,\n bottom: 1047.5539548553688,\n },\n },\n {\n id: "block_13_5eYqPZ",\n type: "heading",\n content: "# Attention Visualizations",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 1498.6412794643775,\n y: 224.94428453654268,\n },\n {\n x: 1498.6412794643775,\n y: 480.8453803514912,\n },\n {\n x: 1479.199057528847,\n y: 480.8453803514912,\n },\n {\n x: 1479.199057528847,\n y: 224.94428453654268,\n },\n ],\n boundingBox: {\n left: 1479.199057528847,\n top: 224.94428453654268,\n right: 1498.6412794643775,\n bottom: 480.8453803514912,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_14_DaAuYi",\n type: "page_number",\n content: "14",\n metadata: {\n page: {\n number: 14,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.998,\n avgOcrConfidence: 0.998,\n },\n polygon: [\n {\n x: 103.12243577770732,\n y: 628.7327731612825,\n },\n {\n x: 103.12243577770732,\n y: 647.0026336447166,\n },\n {\n x: 87.74237117910752,\n y: 647.0026336447166,\n },\n {\n x: 87.74237117910752,\n y: 628.7327731612825,\n },\n ],\n boundingBox: {\n left: 87.74237117910752,\n top: 628.7327731612825,\n right: 103.12243577770732,\n bottom: 647.0026336447166,\n },\n },\n {\n id: "block_14_VDKMys",\n type: "text",\n content:\n "and 6. Note that the attentions are very sharp for this word. Full attentions for head 5. Bottom: Isolated attentions from just the word \'its\' for attention heads 5 Figure 4: Two attention heads, also in layer 5 of 6, apparently involved in anaphora resolution. Top:",\n metadata: {\n page: {\n number: 14,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.972,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 370.4634644357782,\n y: 224.1528559775248,\n },\n {\n x: 370.4634644357782,\n y: 1051.3102287793681,\n },\n {\n x: 303.81733864232115,\n y: 1051.3102287793681,\n },\n {\n x: 303.81733864232115,\n y: 224.1528559775248,\n },\n ],\n boundingBox: {\n left: 303.81733864232115,\n top: 224.1528559775248,\n right: 370.4634644357782,\n bottom: 1051.3102287793681,\n },\n },\n {\n id: "block_14_QRz2LE",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nThe The The The Law Law Law Law will will will will never never never never be be be be perfect perfect perfect perfect , , , , but but but but its its its its application application application application should should should should be be be be just just just just - - - - this this this this is is is is what what what what we we we we are are are are missing missing missing missing , , , , in in in in my my my my opinion opinion opinion opinion . . . . <EOS> <EOS> <EOS> <EOS> <pad> <pad> <pad> <pad>\\n<caption>Attention weight visualization diagram showing alignment between two sequences of text tokens. The diagram consists of three columns of text, with lines connecting tokens between the columns to represent attention strength. Thicker, more opaque lines indicate higher attention weights. The text sequence is: \'The\', \'Law\', \'will\', \'never\', \'be\', \'perfect\', \',\', \'but\', \'its\', \'application\', \'should\', \'be\', \'just\', \'-\', \'this\', \'is\', \'what\', \'we\', \'are\', \'missing\', \',\', \'in\', \'my\', \'opinion\', \'.\', \'<EOS>\', \'<pad>\'. Specific highlights are present: the word \'Law\' in the first column and \'its\' in the second column are highlighted with a purple/grey background, and lines connect these highlighted tokens to corresponding tokens in the third column.</caption>\\n</figure>",\n metadata: {\n page: {\n number: 14,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.379,\n avgOcrConfidence: 0.963,\n },\n polygon: [\n {\n x: 1294.7974623916741,\n y: 255.12043611846704,\n },\n {\n x: 1294.7974623916741,\n y: 1044.444475382784,\n },\n {\n x: 388.9633916410289,\n y: 1044.444475382784,\n },\n {\n x: 388.9633916410289,\n y: 255.12043611846704,\n },\n ],\n boundingBox: {\n left: 388.9633916410289,\n top: 255.12043611846704,\n right: 1294.7974623916741,\n bottom: 1044.444475382784,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_15_pV91a2",\n type: "page_number",\n content: "15",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.998,\n avgOcrConfidence: 0.998,\n },\n polygon: [\n {\n x: 103.26014084206486,\n y: 628.7008215911197,\n },\n {\n x: 103.26014084206486,\n y: 647.1549124613296,\n },\n {\n x: 87.58487219559515,\n y: 647.1549124613296,\n },\n {\n x: 87.58487219559515,\n y: 628.7008215911197,\n },\n ],\n boundingBox: {\n left: 87.58487219559515,\n top: 628.7008215911197,\n right: 103.26014084206486,\n bottom: 647.1549124613296,\n },\n },\n {\n id: "block_15_2igWoi",\n type: "text",\n content:\n "at layer 5 of 6. The heads clearly learned to perform different tasks. sentence. We give two such examples above, from two different heads from the encoder self-attention Figure 5: Many of the attention heads exhibit behaviour that seems related to the structure of the",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.976,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 394.6980404387739,\n y: 223.74716570777616,\n },\n {\n x: 394.6980404387739,\n y: 1049.736980800211,\n },\n {\n x: 328.87227315113955,\n y: 1049.736980800211,\n },\n {\n x: 328.87227315113955,\n y: 223.74716570777616,\n },\n ],\n boundingBox: {\n left: 328.87227315113955,\n top: 223.74716570777616,\n right: 394.6980404387739,\n bottom: 1049.736980800211,\n },\n },\n {\n id: "block_15_OqCqJD",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nThe The Law Law will will never never be be perfect perfect , , but but its its application application should should be be just just - - this this is is what what we we are are missing missing , , in in my my opinion opinion\\n\\n. . <EOS> <EOS> <pad> <pad>\\n<caption>Attention weight visualization showing connections between two identical sequences of text: \'The Law will never be perfect , but its application should be just - this is what we are missing , in my opinion . <EOS> <pad>\'. The diagram uses lines of varying thickness and red color intensity to indicate the strength of attention between words in the left sequence and words in the right sequence. Stronger connections are represented by thicker, more opaque red lines, while weaker connections are represented by thinner, more transparent red lines.</caption>\\n</figure>",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.651,\n avgOcrConfidence: 0.969,\n },\n polygon: [\n {\n x: 810.314180990807,\n y: 253.4944325467966,\n },\n {\n x: 810.314180990807,\n y: 1035.3522419059364,\n },\n {\n x: 421.96601087527165,\n y: 1035.3522419059364,\n },\n {\n x: 421.96601087527165,\n y: 253.4944325467966,\n },\n ],\n boundingBox: {\n left: 421.96601087527165,\n top: 253.4944325467966,\n right: 810.314180990807,\n bottom: 1035.3522419059364,\n },\n },\n {\n id: "block_15_sK8Nre",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nThe The Law Law will will never never be be perfect perfect , , but but its its application application should should be be just just - - this this is is what what we we are are missing missing , , in in my my opinion opinion\\n\\n. . <EOS> <EOS> <pad> <pad>\\n<caption>Attention weight visualization diagram showing connections between two identical sequences of text: \'The\', \'Law\', \'will\', \'never\', \'be\', \'perfect\', \',\', \'but\', \'its\', \'application\', \'should\', \'be\', \'just\', \'-\', \'this\', \'is\', \'what\', \'we\', \'are\', \'missing\', \',\', \'in\', \'my\', \'opinion\', \'.\', \'<EOS>\', \'<pad>\'. The diagram displays lines connecting tokens from the left sequence to the right sequence, where line thickness and opacity represent the strength of the attention weight. Notable high-attention connections include: \'Law\' to \'Law\', \'application\' to \'application\', \'missing\' to \'missing\', \'opinion\' to \'opinion\', and \'<pad>\' to \'<pad>\'.</caption>\\n</figure>",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.6,\n avgOcrConfidence: 0.968,\n },\n polygon: [\n {\n x: 1255.9501913113702,\n y: 254.50874105857238,\n },\n {\n x: 1255.9501913113702,\n y: 1034.3072598868043,\n },\n {\n x: 882.2701913360366,\n y: 1034.3072598868043,\n },\n {\n x: 882.2701913360366,\n y: 254.50874105857238,\n },\n ],\n boundingBox: {\n left: 882.2701913360366,\n top: 254.50874105857238,\n right: 1255.9501913113702,\n bottom: 1034.3072598868043,\n },\n },\n ],\n },\n ],\n} satisfies ParsedOcrOutput\n\nconst BLOCK_STYLES: Record<\n OcrBlockType,\n {\n label: string\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n overlay: string\n mutedOverlay: string\n ring: string\n badge: string\n }\n> = {\n heading: {\n label: "Heading",\n icon: Heading01Icon,\n overlay: "border-violet-500/70 bg-violet-500/10",\n mutedOverlay: "border-violet-500/35 bg-violet-500/5",\n ring: "border-violet-500/60 bg-violet-500/5 text-violet-600",\n badge:\n "bg-violet-50 text-violet-600 dark:bg-violet-300/10 dark:text-violet-300",\n },\n paragraph: {\n label: "Paragraph",\n icon: ParagraphIcon,\n overlay: "border-blue-500/70 bg-blue-500/10",\n mutedOverlay: "border-blue-500/35 bg-blue-500/5",\n ring: "border-blue-500/60 bg-blue-500/5 text-blue-600",\n badge: "bg-blue-50 text-blue-600 dark:bg-blue-300/10 dark:text-blue-300",\n },\n list: {\n label: "List",\n icon: LeftToRightListBulletIcon,\n overlay: "border-emerald-500/70 bg-emerald-500/10",\n mutedOverlay: "border-emerald-500/35 bg-emerald-500/5",\n ring: "border-emerald-500/60 bg-emerald-500/5 text-emerald-600",\n badge:\n "bg-emerald-50 text-emerald-600 dark:bg-emerald-300/10 dark:text-emerald-300",\n },\n table: {\n label: "Table",\n icon: Table01Icon,\n overlay: "border-amber-500/70 bg-amber-500/10",\n mutedOverlay: "border-amber-500/35 bg-amber-500/5",\n ring: "border-amber-500/60 bg-amber-500/5 text-amber-700",\n badge:\n "bg-amber-50 text-amber-600 dark:bg-amber-300/10 dark:text-amber-300",\n },\n figure: {\n label: "Figure",\n icon: ImageCompositionIcon,\n overlay: "border-rose-500/70 bg-rose-500/10",\n mutedOverlay: "border-rose-500/35 bg-rose-500/5",\n ring: "border-rose-500/60 bg-rose-500/5 text-rose-600",\n badge: "bg-rose-50 text-rose-600 dark:bg-rose-300/10 dark:text-rose-300",\n },\n header: {\n label: "Header",\n icon: TextCenterlineCenterTopIcon,\n overlay: "border-cyan-500/70 bg-cyan-500/10",\n mutedOverlay: "border-cyan-500/35 bg-cyan-500/5",\n ring: "border-cyan-500/60 bg-cyan-500/5 text-cyan-700",\n badge: "bg-cyan-50 text-cyan-600 dark:bg-cyan-300/10 dark:text-cyan-300",\n },\n footer: {\n label: "Footer",\n icon: AlignBoxBottomCenterIcon,\n overlay: "border-slate-500/70 bg-slate-500/10",\n mutedOverlay: "border-slate-500/35 bg-slate-500/5",\n ring: "border-slate-500/60 bg-slate-500/5 text-slate-700",\n badge:\n "bg-slate-50 text-slate-600 dark:bg-slate-300/10 dark:text-slate-300",\n },\n page_number: {\n label: "Page number",\n icon: TextNumberSignIcon,\n overlay: "border-zinc-500/70 bg-zinc-500/10",\n mutedOverlay: "border-zinc-500/35 bg-zinc-500/5",\n ring: "border-zinc-500/60 bg-zinc-500/5 text-zinc-700",\n badge: "bg-zinc-50 text-zinc-600 dark:bg-zinc-300/10 dark:text-zinc-300",\n },\n}\n\nfunction getBlockType(block: ParsedOcrBlock): OcrBlockType | undefined {\n if (block.type === "heading" || block.type === "section_heading") {\n return "heading"\n }\n\n if (block.type === "header") {\n return "header"\n }\n\n if (block.type === "footer") {\n return "footer"\n }\n\n if (block.type === "page_number") {\n return "page_number"\n }\n\n if (block.type === "figure" || block.type === "image") {\n return "figure"\n }\n\n if (block.type === "table") {\n return "table"\n }\n\n if (block.metadata.layoutClass === "List Item") {\n return "list"\n }\n\n if (block.type === "text") {\n return "paragraph"\n }\n}\n\nexport function getOcrBlocks(output: ParsedOcrOutput): OcrBlock[] {\n return output.chunks.flatMap((chunk) =>\n chunk.blocks.flatMap((block) => {\n const type = getBlockType(block)\n const { page } = block.metadata\n\n if (!type || page.width <= 0 || page.height <= 0) {\n return []\n }\n\n return {\n id: block.id,\n type,\n text: block.content,\n page: page.number,\n pageWidth: page.width,\n pageHeight: page.height,\n confidence:\n block.metadata.avgOcrConfidence ??\n block.metadata.minOcrConfidence ??\n 1,\n polygon: block.polygon,\n boundingBox: block.boundingBox,\n }\n })\n )\n}\n\nfunction getBoundingBox(block: OcrBlock): BoundingBox {\n if (block.boundingBox) {\n return block.boundingBox\n }\n\n const polygon = block.polygon ?? []\n const xValues = polygon.map((point) => point.x)\n const yValues = polygon.map((point) => point.y)\n const left = Math.min(...xValues)\n const right = Math.max(...xValues)\n const top = Math.min(...yValues)\n const bottom = Math.max(...yValues)\n\n return { left, top, right, bottom }\n}\n\nfunction getBlockCoordinateRotation(\n block: OcrBlock,\n pageSize?: { width: number; height: number }\n) {\n const blockIsLandscape = block.pageWidth > block.pageHeight\n\n if (!pageSize) return blockIsLandscape ? 1 : 0\n\n const pageIsLandscape = pageSize.width > pageSize.height\n\n if (blockIsLandscape && !pageIsLandscape) return 1\n if (!blockIsLandscape && pageIsLandscape) return 3\n\n return 0\n}\n\nfunction normalizeHighlightAreaForRotation(\n area: HighlightArea,\n rotation: number\n): HighlightArea {\n if (rotation === 1) {\n return {\n left: area.top,\n top: 100 - area.left - area.width,\n width: area.height,\n height: area.width,\n }\n }\n\n if (rotation === 3) {\n return {\n left: 100 - area.top - area.height,\n top: area.left,\n width: area.height,\n height: area.width,\n }\n }\n\n return area\n}\n\nexport function blockToHighlightArea(\n block: OcrBlock,\n pageSize?: { width: number; height: number }\n): HighlightArea {\n const { left, top, right, bottom } = getBoundingBox(block)\n\n const area = {\n left: (left / block.pageWidth) * 100,\n top: (top / block.pageHeight) * 100,\n width: ((right - left) / block.pageWidth) * 100,\n height: ((bottom - top) / block.pageHeight) * 100,\n }\n\n return normalizeHighlightAreaForRotation(\n area,\n getBlockCoordinateRotation(block, pageSize)\n )\n}\n\nexport function blockToArea(\n block: OcrBlock,\n pageSize?: { width: number; height: number }\n): React.CSSProperties {\n const area = blockToHighlightArea(block, pageSize)\n\n return {\n left: `${area.left}%`,\n top: `${area.top}%`,\n width: `${area.width}%`,\n height: `${area.height}%`,\n }\n}\n\nconst OcrBlockMarkdown = React.memo(function OcrBlockMarkdown({\n text,\n}: {\n text: string\n}) {\n const markdown = text.replace(OCR_MARKDOWN_FIGURE_CAPTION_PATTERN, (tag) =>\n tag.startsWith("</") ? "</figcaption>" : "<figcaption>"\n )\n\n return (\n <div className="space-y-1 text-sm leading-5 text-foreground/90">\n <ReactMarkdown\n rehypePlugins={OCR_MARKDOWN_REHYPE_PLUGINS}\n remarkPlugins={OCR_MARKDOWN_REMARK_PLUGINS}\n components={{\n h1: ({ node: _node, ...props }) => (\n <h1\n className="my-0 text-base leading-5 font-semibold text-foreground"\n {...props}\n />\n ),\n p: ({ node: _node, ...props }) => (\n <p className="my-0 text-[13px] leading-5" {...props} />\n ),\n ol: ({ node: _node, ...props }) => (\n <ol className="my-0 list-decimal space-y-0.5 pl-4" {...props} />\n ),\n table: ({ node: _node, ...props }) => (\n <div className="overflow-hidden rounded-md border bg-background">\n <table className="w-full border-collapse text-xs" {...props} />\n </div>\n ),\n figure: ({ node: _node, ...props }) => (\n <figure\n className="my-0 space-y-2 rounded-md border bg-muted/20 p-2 text-[13px]"\n {...props}\n />\n ),\n figcaption: ({ node: _node, ...props }) => (\n <figcaption\n className="border-t pt-2 text-xs leading-5 text-muted-foreground"\n {...props}\n />\n ),\n caption: ({ node: _node, ...props }) => (\n <figcaption\n className="block border-t pt-2 text-xs leading-5 text-muted-foreground"\n {...props}\n />\n ),\n th: ({ node: _node, ...props }) => (\n <th className="border-b bg-muted px-2 py-1 text-left" {...props} />\n ),\n td: ({ node: _node, ...props }) => (\n <td className="border-t px-2 py-1" {...props} />\n ),\n }}\n >\n {markdown}\n </ReactMarkdown>\n </div>\n )\n})\n\nconst OcrBlockButton = React.memo(function OcrBlockButton({\n block,\n isActive,\n onFocusBlock,\n}: {\n block: OcrBlock\n isActive: boolean\n onFocusBlock: (block: OcrBlock) => void\n}) {\n const style = BLOCK_STYLES[block.type]\n\n return (\n <button\n type="button"\n onMouseEnter={() => onFocusBlock(block)}\n onFocus={() => onFocusBlock(block)}\n className={cn(\n "w-full rounded-lg border bg-background p-3 text-left hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",\n isActive && style.ring\n )}\n >\n <div className="min-w-0">\n <div className="flex items-center justify-between gap-2">\n <div className="flex min-w-0 items-center gap-2">\n <div\n className={cn(\n "inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium",\n style.badge\n )}\n >\n <HugeiconsIcon icon={style.icon} className="size-3.5" />\n {style.label}\n </div>\n <div className="truncate text-xs text-muted-foreground">\n {Math.round(block.confidence * 100)}%\n </div>\n </div>\n <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">\n p. {block.page}\n </div>\n </div>\n <div className="mt-2 text-sm text-foreground/90">\n <OcrBlockMarkdown text={block.text} />\n </div>\n </div>\n </button>\n )\n})\n\nexport const OcrBlockOverlay = React.memo(function OcrBlockOverlay({\n block,\n isActive,\n pageHeight,\n pageWidth,\n}: {\n block: OcrBlock\n isActive?: boolean\n pageHeight?: number\n pageWidth?: number\n}) {\n const style = BLOCK_STYLES[block.type]\n\n return (\n <div\n className={cn(\n "pointer-events-none absolute z-10 border",\n isActive ? style.overlay : style.mutedOverlay\n )}\n style={blockToArea(\n block,\n pageWidth && pageHeight ? { width: pageWidth, height: pageHeight } : undefined\n )}\n />\n )\n})\n\nexport function OcrBlocksPanel({\n activeBlockId,\n blocks,\n className,\n onBlockFocus,\n}: {\n activeBlockId?: string\n blocks: OcrBlock[]\n className?: string\n onBlockFocus?: (block: OcrBlock) => void\n}) {\n const scrollViewportRef = React.useRef<HTMLDivElement | null>(null)\n const [localActiveBlockId, setLocalActiveBlockId] = React.useState(\n activeBlockId ?? blocks[0]?.id\n )\n const firstBlock = blocks[0]\n const focusedBlockId = activeBlockId ?? localActiveBlockId\n const activeBlock =\n blocks.find((block) => block.id === focusedBlockId) ?? firstBlock\n const focusedBlockIdRef = React.useRef(focusedBlockId)\n\n React.useEffect(() => {\n focusedBlockIdRef.current = focusedBlockId\n }, [focusedBlockId])\n\n const estimateBlockSize = React.useCallback(\n (index: number) => {\n const block = blocks[index]\n return block\n ? getEstimatedOcrBlockRowHeight(block)\n : OCR_BLOCK_ROW_MIN_ESTIMATE\n },\n [blocks]\n )\n const virtualizer = useVirtualizer({\n count: blocks.length,\n estimateSize: estimateBlockSize,\n getItemKey: (index) => blocks[index]?.id ?? index,\n getScrollElement: () => scrollViewportRef.current,\n overscan: 6,\n })\n\n const focusBlock = React.useCallback(\n (block: OcrBlock) => {\n if (block.id === focusedBlockIdRef.current) return\n\n focusedBlockIdRef.current = block.id\n setLocalActiveBlockId(block.id)\n onBlockFocus?.(block)\n },\n [onBlockFocus]\n )\n\n React.useEffect(() => {\n if (!firstBlock) return\n if (\n activeBlockId ||\n blocks.some((block) => block.id === localActiveBlockId)\n ) {\n return\n }\n\n setLocalActiveBlockId(firstBlock.id)\n }, [activeBlockId, blocks, firstBlock, localActiveBlockId])\n\n return (\n <aside\n className={cn("flex h-[420px] min-h-0 flex-col bg-background", className)}\n >\n <ScrollArea\n className="min-h-0 flex-1"\n scrollFade\n viewportRef={scrollViewportRef}\n >\n {blocks.length ? (\n <div\n className="relative"\n style={{\n height: virtualizer.getTotalSize() + OCR_BLOCK_LIST_PADDING * 2,\n }}\n >\n {virtualizer.getVirtualItems().map((virtualRow) => {\n const block = blocks[virtualRow.index]\n if (!block) return null\n\n return (\n <div\n key={virtualRow.key}\n ref={virtualizer.measureElement}\n data-index={virtualRow.index}\n className="absolute top-0 right-3 left-3 pb-2 [contain:layout_paint]"\n style={{\n transform: `translateY(${\n virtualRow.start + OCR_BLOCK_LIST_PADDING\n }px)`,\n }}\n >\n <OcrBlockButton\n block={block}\n isActive={block.id === activeBlock?.id}\n onFocusBlock={focusBlock}\n />\n </div>\n )\n })}\n </div>\n ) : (\n <div className="p-3">\n <div className="rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground">\n No layout blocks found.\n </div>\n </div>\n )}\n </ScrollArea>\n </aside>\n )\n}\n\nexport function OcrBlocks() {\n return (\n <OcrBlocksPanel blocks={getOcrBlocks(ATTENTION_OCR_OUTPUT).slice(0, 12)} />\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport { useVirtualizer } from "@tanstack/react-virtual"\nimport ReactMarkdown from "react-markdown"\nimport rehypeRaw from "rehype-raw"\nimport rehypeSanitize, { defaultSchema } from "rehype-sanitize"\nimport remarkGfm from "remark-gfm"\n\nimport { cn } from "@/lib/utils"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nfunction AlignBoxBottomCenterGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="AlignVerticalJustifyEnd"\n tabler="IconAlignBoxBottomCenter"\n hugeicons="AlignBoxBottomCenterIcon"\n phosphor="AlignBottomIcon"\n remixicon="RiAlignBottom"\n {...props}\n />\n )\n}\n\nfunction Heading01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Heading1"\n tabler="IconH1"\n hugeicons="Heading01Icon"\n phosphor="TextHOneIcon"\n remixicon="RiH1"\n {...props}\n />\n )\n}\n\nfunction ImageCompositionGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Image"\n tabler="IconPhoto"\n hugeicons="ImageCompositionIcon"\n phosphor="ImageSquareIcon"\n remixicon="RiImageLine"\n {...props}\n />\n )\n}\n\nfunction LeftToRightListBulletGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Columns3Icon"\n tabler="IconLayoutColumns"\n hugeicons="LeftToRightListBulletIcon"\n phosphor="ColumnsIcon"\n remixicon="RiLayoutColumnLine"\n {...props}\n />\n )\n}\n\nfunction ParagraphGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Pilcrow"\n tabler="IconPilcrow"\n hugeicons="ParagraphIcon"\n phosphor="ParagraphIcon"\n remixicon="RiParagraph"\n {...props}\n />\n )\n}\n\nfunction Table01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Table"\n tabler="IconTable"\n hugeicons="Table01Icon"\n phosphor="TableIcon"\n remixicon="RiTableLine"\n {...props}\n />\n )\n}\n\nfunction TextCenterlineCenterTopGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelTop"\n tabler="IconLayoutNavbar"\n hugeicons="TextCenterlineCenterTopIcon"\n phosphor="AlignTopSimpleIcon"\n remixicon="RiLayoutTopLine"\n {...props}\n />\n )\n}\n\nfunction TextNumberSignGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Hash"\n tabler="IconHash"\n hugeicons="TextNumberSignIcon"\n phosphor="HashIcon"\n remixicon="RiHashtag"\n {...props}\n />\n )\n}\n\nexport type Point = {\n x: number\n y: number\n}\n\nexport type BoundingBox = {\n left: number\n top: number\n right: number\n bottom: number\n}\n\nexport type OcrBlockType =\n | "heading"\n | "paragraph"\n | "list"\n | "table"\n | "figure"\n | "header"\n | "footer"\n | "page_number"\n\nexport type ParsedOcrBlock = {\n id: string\n type: string\n content: string\n metadata: {\n page: {\n number: number\n width: number\n height: number\n }\n layoutClass?: string\n minOcrConfidence?: number\n avgOcrConfidence?: number\n }\n polygon?: Point[]\n boundingBox?: BoundingBox\n}\n\nexport type ParsedOcrOutput = {\n chunks: {\n blocks: ParsedOcrBlock[]\n }[]\n}\n\nexport type OcrBlock = {\n id: string\n type: OcrBlockType\n text: string\n page: number\n pageWidth: number\n pageHeight: number\n confidence: number\n polygon?: Point[]\n boundingBox?: BoundingBox\n}\n\nexport type HighlightArea = {\n left: number\n top: number\n width: number\n height: number\n}\n\nexport const PDF_URL = "/samples/attention.pdf"\nconst OCR_BLOCK_ROW_MIN_ESTIMATE = 92\nconst OCR_BLOCK_ROW_VERTICAL_CHROME = 62\nconst OCR_BLOCK_LINE_HEIGHT = 20\nconst OCR_BLOCK_ESTIMATED_CHARS_PER_LINE = 42\nconst OCR_BLOCK_ROW_GAP = 8\nconst OCR_BLOCK_LIST_PADDING = 12\nconst OCR_MARKDOWN_SCHEMA = {\n ...defaultSchema,\n attributes: {\n ...defaultSchema.attributes,\n figure: [...(defaultSchema.attributes?.figure ?? []), "type"],\n },\n tagNames: [\n ...(defaultSchema.tagNames ?? []),\n "caption",\n "figcaption",\n "figure",\n ],\n}\nconst OCR_MARKDOWN_REHYPE_PLUGINS: NonNullable<\n React.ComponentProps<typeof ReactMarkdown>["rehypePlugins"]\n> = [rehypeRaw, [rehypeSanitize, OCR_MARKDOWN_SCHEMA]]\nconst OCR_MARKDOWN_REMARK_PLUGINS: NonNullable<\n React.ComponentProps<typeof ReactMarkdown>["remarkPlugins"]\n> = [remarkGfm]\nconst OCR_MARKDOWN_FIGURE_CAPTION_PATTERN = /<\\/?caption>/gi\n\nfunction getEstimatedOcrBlockRowHeight(block: OcrBlock) {\n const plainText = block.text\n .replace(OCR_MARKDOWN_FIGURE_CAPTION_PATTERN, "")\n .replace(/<[^>]*>/g, "")\n .replace(/\\s+/g, " ")\n .trim()\n const explicitLineCount = block.text.split(/\\n+/).filter(Boolean).length\n const wrappedLineCount = Math.max(\n explicitLineCount,\n Math.ceil(plainText.length / OCR_BLOCK_ESTIMATED_CHARS_PER_LINE)\n )\n const contentHeight = Math.max(1, wrappedLineCount) * OCR_BLOCK_LINE_HEIGHT\n const typeExtraHeight =\n block.type === "figure" ? 44 : block.type === "table" ? 28 : 0\n\n return Math.max(\n OCR_BLOCK_ROW_MIN_ESTIMATE,\n OCR_BLOCK_ROW_VERTICAL_CHROME +\n contentHeight +\n typeExtraHeight +\n OCR_BLOCK_ROW_GAP\n )\n}\n\nexport const ATTENTION_OCR_OUTPUT = {\n chunks: [\n {\n blocks: [\n {\n id: "block_1_IKDP4i",\n type: "header",\n content: "arXiv:1706.03762v7 [cs.CL] 2 Aug 2023",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Header",\n minOcrConfidence: 0.959,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 36.16179897837395,\n y: 447.38040863840206,\n },\n {\n x: 75.85163708150822,\n y: 447.38040863840206,\n },\n {\n x: 75.85163708150822,\n y: 1155.1796566956025,\n },\n {\n x: 36.16179897837395,\n y: 1155.1796566956025,\n },\n ],\n boundingBox: {\n left: 36.16179897837395,\n top: 447.38040863840206,\n right: 75.85163708150822,\n bottom: 1155.1796566956025,\n },\n },\n {\n id: "block_1_rtNdsr",\n type: "header",\n content:\n "Provided proper attribution is provided, Google hereby grants permission to reproduce the tables and figures in this paper solely for use in journalistic or scholarly works.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Header",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 258.50183528705236,\n y: 151.7837261257315,\n },\n {\n x: 1016.8830982960054,\n y: 151.7837261257315,\n },\n {\n x: 1016.8830982960054,\n y: 233.84929126366637,\n },\n {\n x: 258.50183528705236,\n y: 233.84929126366637,\n },\n ],\n boundingBox: {\n left: 258.50183528705236,\n top: 151.7837261257315,\n right: 1016.8830982960054,\n bottom: 233.84929126366637,\n },\n },\n {\n id: "block_1_eo9AoV",\n type: "heading",\n content: "# Attention Is All You Need",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 440.0215455215343,\n y: 312.01490975860366,\n },\n {\n x: 831.4373211268961,\n y: 312.01490975860366,\n },\n {\n x: 831.4373211268961,\n y: 339.0022611402928,\n },\n {\n x: 440.0215455215343,\n y: 339.0022611402928,\n },\n ],\n boundingBox: {\n left: 440.0215455215343,\n top: 312.01490975860366,\n right: 831.4373211268961,\n bottom: 339.0022611402928,\n },\n },\n {\n id: "block_1_Kdt5Cu",\n type: "text",\n content: "Ashish Vaswani* Google Brain [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.977,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 242.9606625633518,\n y: 490.4495616712068,\n },\n {\n x: 449.64758323056856,\n y: 490.4495616712068,\n },\n {\n x: 449.64758323056856,\n y: 555.9028907431696,\n },\n {\n x: 242.9606625633518,\n y: 555.9028907431696,\n },\n ],\n boundingBox: {\n left: 242.9606625633518,\n top: 490.4495616712068,\n right: 449.64758323056856,\n bottom: 555.9028907431696,\n },\n },\n {\n id: "block_1_6Xv6uR",\n type: "text",\n content: "Llion Jones* Google Research [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.927,\n avgOcrConfidence: 0.982,\n },\n polygon: [\n {\n x: 264.3723327748097,\n y: 594.5307239733245,\n },\n {\n x: 438.3605845653227,\n y: 594.5307239733245,\n },\n {\n x: 438.3605845653227,\n y: 660.7685646688132,\n },\n {\n x: 264.3723327748097,\n y: 660.7685646688132,\n },\n ],\n boundingBox: {\n left: 264.3723327748097,\n top: 594.5307239733245,\n right: 438.3605845653227,\n bottom: 660.7685646688132,\n },\n },\n {\n id: "block_1_Lx35WU",\n type: "text",\n content: "Noam Shazeer* Google Brain [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.983,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 479.08373644752226,\n y: 490.1169480632122,\n },\n {\n x: 643.7573955006842,\n y: 490.1169480632122,\n },\n {\n x: 643.7573955006842,\n y: 556.2343205043247,\n },\n {\n x: 479.08373644752226,\n y: 556.2343205043247,\n },\n ],\n boundingBox: {\n left: 479.08373644752226,\n top: 490.1169480632122,\n right: 643.7573955006842,\n bottom: 556.2343205043247,\n },\n },\n {\n id: "block_1_VxOJIL",\n type: "text",\n content:\n "Aidan N. Gomez* * University of Toronto [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.095,\n avgOcrConfidence: 0.875,\n },\n polygon: [\n {\n x: 489.9820146769503,\n y: 593.5908916444707,\n },\n {\n x: 708.1676900821881,\n y: 593.5908916444707,\n },\n {\n x: 708.1676900821881,\n y: 657.7173651788468,\n },\n {\n x: 489.9820146769503,\n y: 657.7173651788468,\n },\n ],\n boundingBox: {\n left: 489.9820146769503,\n top: 593.5908916444707,\n right: 708.1676900821881,\n bottom: 657.7173651788468,\n },\n },\n {\n id: "block_1_m1Gb17",\n type: "text",\n content: "Niki Parmar* Google Research [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 673.3537325893875,\n y: 490.2837284059453,\n },\n {\n x: 848.6601168221802,\n y: 490.2837284059453,\n },\n {\n x: 848.6601168221802,\n y: 556.287735673718,\n },\n {\n x: 673.3537325893875,\n y: 556.287735673718,\n },\n ],\n boundingBox: {\n left: 673.3537325893875,\n top: 490.2837284059453,\n right: 848.6601168221802,\n bottom: 556.287735673718,\n },\n },\n {\n id: "block_1_otnY8T",\n type: "text",\n content: "\\u0141ukasz Kaiser* Google Brain [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.984,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 759.3324257509552,\n y: 594.2661578816579,\n },\n {\n x: 1011.1333304078039,\n y: 594.2661578816579,\n },\n {\n x: 1011.1333304078039,\n y: 660.9298993160851,\n },\n {\n x: 759.3324257509552,\n y: 660.9298993160851,\n },\n ],\n boundingBox: {\n left: 759.3324257509552,\n top: 594.2661578816579,\n right: 1011.1333304078039,\n bottom: 660.9298993160851,\n },\n },\n {\n id: "block_1_ICaos6",\n type: "text",\n content: "Illia Polosukhin* * [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.107,\n avgOcrConfidence: 0.766,\n },\n polygon: [\n {\n x: 495.9563429338219,\n y: 697.325802423004,\n },\n {\n x: 778.5449758933407,\n y: 697.325802423004,\n },\n {\n x: 778.5449758933407,\n y: 742.1158899292909,\n },\n {\n x: 495.9563429338219,\n y: 742.1158899292909,\n },\n ],\n boundingBox: {\n left: 495.9563429338219,\n top: 697.325802423004,\n right: 778.5449758933407,\n bottom: 742.1158899292909,\n },\n },\n {\n id: "block_1_zNN0g5",\n type: "section_heading",\n content: "### Abstract",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 590.8429918498018,\n y: 804.3203170891095,\n },\n {\n x: 683.8031267597728,\n y: 804.3203170891095,\n },\n {\n x: 683.8031267597728,\n y: 823.7656170264223,\n },\n {\n x: 590.8429918498018,\n y: 823.7656170264223,\n },\n ],\n boundingBox: {\n left: 590.8429918498018,\n top: 804.3203170891095,\n right: 683.8031267597728,\n bottom: 823.7656170264223,\n },\n },\n {\n id: "block_1_Pzc7ia",\n type: "text",\n content:\n "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014 English- to-German translation task, improving over the existing best results, including ensembles, by over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training costs of the best models from the literature. We show that the Transformer generalizes well to other tasks by applying it successfully to English constituency parsing both with large and limited training data.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.987,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 298.2268201173657,\n y: 861.5167879950731,\n },\n {\n x: 978.0244980415288,\n y: 861.5167879950731,\n },\n {\n x: 978.0244980415288,\n y: 1201.6481075430274,\n },\n {\n x: 298.2268201173657,\n y: 1201.6481075430274,\n },\n ],\n boundingBox: {\n left: 298.2268201173657,\n top: 861.5167879950731,\n right: 978.0244980415288,\n bottom: 1201.6481075430274,\n },\n },\n {\n id: "block_1_bHnLKj",\n type: "text",\n content:\n "*Equal contribution. Listing order is random. Jakob proposed replacing RNNs with self-attention and started the effort to evaluate this idea. Ashish, with Illia, designed and implemented the first Transformer models and has been crucially involved in every aspect of this work. Noam proposed scaled dot-product attention, multi-head attention and the parameter-free position representation and became the other person involved in nearly every detail. Niki designed, implemented, tuned and evaluated countless model variants in our original codebase and tensor2tensor. Llion also experimented with novel model variants, was responsible for our initial codebase, and efficient inference and visualizations. Lukasz and Aidan spent countless long days designing various parts of and implementing tensor2tensor, replacing our earlier codebase, greatly improving results and massively accelerating our research.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.951,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.8755505415645,\n y: 1247.2573697082978,\n },\n {\n x: 1049.6971241749116,\n y: 1247.2573697082978,\n },\n {\n x: 1049.6971241749116,\n y: 1429.7100451476592,\n },\n {\n x: 222.8755505415645,\n y: 1429.7100451476592,\n },\n ],\n boundingBox: {\n left: 222.8755505415645,\n top: 1247.2573697082978,\n right: 1049.6971241749116,\n bottom: 1429.7100451476592,\n },\n },\n {\n id: "block_1_J3Olku",\n type: "text",\n content: "+ Work performed while at Google Brain.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.11,\n avgOcrConfidence: 0.869,\n },\n polygon: [\n {\n x: 250.1677060649343,\n y: 1434.3817888991277,\n },\n {\n x: 555.1793119333087,\n y: 1434.3817888991277,\n },\n {\n x: 555.1793119333087,\n y: 1456.532320926064,\n },\n {\n x: 250.1677060649343,\n y: 1456.532320926064,\n },\n ],\n boundingBox: {\n left: 250.1677060649343,\n top: 1434.3817888991277,\n right: 555.1793119333087,\n bottom: 1456.532320926064,\n },\n },\n {\n id: "block_1_aQsakB",\n type: "text",\n content: "#Work performed while at Google Research.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.652,\n avgOcrConfidence: 0.94,\n },\n polygon: [\n {\n x: 249.36288151427775,\n y: 1458.4100914288283,\n },\n {\n x: 582.4047478446125,\n y: 1458.4100914288283,\n },\n {\n x: 582.4047478446125,\n y: 1479.773507369192,\n },\n {\n x: 249.36288151427775,\n y: 1479.773507369192,\n },\n ],\n boundingBox: {\n left: 249.36288151427775,\n top: 1458.4100914288283,\n right: 582.4047478446125,\n bottom: 1479.773507369192,\n },\n },\n {\n id: "block_1_iKp4Ae",\n type: "footer",\n content:\n "31st Conference on Neural Information Processing Systems (NIPS 2017), Long Beach, CA, USA.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Footer",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.27405893367575,\n y: 1527.1945287374626,\n },\n {\n x: 958.2568426201814,\n y: 1527.1945287374626,\n },\n {\n x: 958.2568426201814,\n y: 1546.3855383736748,\n },\n {\n x: 224.27405893367575,\n y: 1546.3855383736748,\n },\n ],\n boundingBox: {\n left: 224.27405893367575,\n top: 1527.1945287374626,\n right: 958.2568426201814,\n bottom: 1546.3855383736748,\n },\n },\n {\n id: "block_1_zPHQaR",\n type: "text",\n content: "Jakob Uszkoreit* Google Research [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 879.2488933479699,\n y: 489.58686880240765,\n },\n {\n x: 1035.003756780694,\n y: 489.58686880240765,\n },\n {\n x: 1035.003756780694,\n y: 555.848623204052,\n },\n {\n x: 879.2488933479699,\n y: 555.848623204052,\n },\n ],\n boundingBox: {\n left: 879.2488933479699,\n top: 489.58686880240765,\n right: 1035.003756780694,\n bottom: 555.848623204052,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_2_UD1C1k",\n type: "heading",\n content: "# 1 Introduction",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 225.86025321570625,\n y: 152.1792611932396,\n },\n {\n x: 396.86960095036636,\n y: 152.1792611932396,\n },\n {\n x: 396.86960095036636,\n y: 171.96800693712737,\n },\n {\n x: 225.86025321570625,\n y: 171.96800693712737,\n },\n ],\n boundingBox: {\n left: 225.86025321570625,\n top: 152.1792611932396,\n right: 396.86960095036636,\n bottom: 171.96800693712737,\n },\n },\n {\n id: "block_2_C25o9D",\n type: "text",\n content:\n "Recurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks in particular, have been firmly established as state of the art approaches in sequence modeling and transduction problems such as language modeling and machine translation [35, 2, 5]. Numerous efforts have since continued to push the boundaries of recurrent language models and encoder-decoder architectures [38, 24, 15].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 223.64054213475134,\n y: 206.4059457563816,\n },\n {\n x: 1050.9159227357293,\n y: 206.4059457563816,\n },\n {\n x: 1050.9159227357293,\n y: 316.89823061720773,\n },\n {\n x: 223.64054213475134,\n y: 316.89823061720773,\n },\n ],\n boundingBox: {\n left: 223.64054213475134,\n top: 206.4059457563816,\n right: 1050.9159227357293,\n bottom: 316.89823061720773,\n },\n },\n {\n id: "block_2_Cw1VyU",\n type: "text",\n content:\n "Recurrent models typically factor computation along the symbol positions of the input and output sequences. Aligning the positions to steps in computation time, they generate a sequence of hidden states ht, as a function of the previous hidden state ht-1 and the input for position t. This inherently sequential nature precludes parallelization within training examples, which becomes critical at longer sequence lengths, as memory constraints limit batching across examples. Recent work has achieved significant improvements in computational efficiency through factorization tricks [21] and conditional computation [32], while also improving model performance in case of the latter. The fundamental constraint of sequential computation, however, remains.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.9,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.69928568819142,\n y: 331.227654822787,\n },\n {\n x: 1049.6158961832089,\n y: 331.227654822787,\n },\n {\n x: 1049.6158961832089,\n y: 511.80734250061494,\n },\n {\n x: 223.69928568819142,\n y: 511.80734250061494,\n },\n ],\n boundingBox: {\n left: 223.69928568819142,\n top: 331.227654822787,\n right: 1049.6158961832089,\n bottom: 511.80734250061494,\n },\n },\n {\n id: "block_2_FR7zlH",\n type: "text",\n content:\n "Attention mechanisms have become an integral part of compelling sequence modeling and transduc- tion models in various tasks, allowing modeling of dependencies without regard to their distance in the input or output sequences [2, 19]. In all but a few cases [27], however, such attention mechanisms are used in conjunction with a recurrent network.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.959,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.38852708357095,\n y: 525.5238181666324,\n },\n {\n x: 1052.1732525233804,\n y: 525.5238181666324,\n },\n {\n x: 1052.1732525233804,\n y: 613.7107948647406,\n },\n {\n x: 223.38852708357095,\n y: 613.7107948647406,\n },\n ],\n boundingBox: {\n left: 223.38852708357095,\n top: 525.5238181666324,\n right: 1052.1732525233804,\n bottom: 613.7107948647406,\n },\n },\n {\n id: "block_2_ZyhlFh",\n type: "text",\n content:\n "In this work we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output. The Transformer allows for significantly more parallelization and can reach a new state of the art in translation quality after being trained for as little as twelve hours on eight P100 GPUs.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.991,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.20226126343667,\n y: 627.2328828797304,\n },\n {\n x: 1052.7354108156078,\n y: 627.2328828797304,\n },\n {\n x: 1052.7354108156078,\n y: 716.0174654623619,\n },\n {\n x: 223.20226126343667,\n y: 716.0174654623619,\n },\n ],\n boundingBox: {\n left: 223.20226126343667,\n top: 627.2328828797304,\n right: 1052.7354108156078,\n bottom: 716.0174654623619,\n },\n },\n {\n id: "block_2_MZBXjP",\n type: "section_heading",\n content: "### 2 Background",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.22355178498873,\n y: 757.4257287333783,\n },\n {\n x: 392.45446198178036,\n y: 757.4257287333783,\n },\n {\n x: 392.45446198178036,\n y: 781.2853567654029,\n },\n {\n x: 224.22355178498873,\n y: 781.2853567654029,\n },\n ],\n boundingBox: {\n left: 224.22355178498873,\n top: 757.4257287333783,\n right: 392.45446198178036,\n bottom: 781.2853567654029,\n },\n },\n {\n id: "block_2_JeOnOk",\n type: "text",\n content:\n "The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU [16], ByteNet [18] and ConvS2S [9], all of which use convolutional neural networks as basic building block, computing hidden representations in parallel for all input and output positions. In these models, the number of operations required to relate signals from two arbitrary input or output positions grows in the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes it more difficult to learn dependencies between distant positions [12]. In the Transformer this is reduced to a constant number of operations, albeit at the cost of reduced effective resolution due to averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as described in section 3.2.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.893,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.30221050847186,\n y: 810.9956032315591,\n },\n {\n x: 1051.187440078624,\n y: 810.9956032315591,\n },\n {\n x: 1051.187440078624,\n y: 1010.7095232511822,\n },\n {\n x: 223.30221050847186,\n y: 1010.7095232511822,\n },\n ],\n boundingBox: {\n left: 223.30221050847186,\n top: 810.9956032315591,\n right: 1051.187440078624,\n bottom: 1010.7095232511822,\n },\n },\n {\n id: "block_2_tEzlrD",\n type: "text",\n content:\n "Self-attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence. Self-attention has been used successfully in a variety of tasks including reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations [4, 27, 28, 22].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.984,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.00045882176306,\n y: 1028.0413251030714,\n },\n {\n x: 1051.4467448213675,\n y: 1028.0413251030714,\n },\n {\n x: 1051.4467448213675,\n y: 1116.9915041815966,\n },\n {\n x: 224.00045882176306,\n y: 1116.9915041815966,\n },\n ],\n boundingBox: {\n left: 224.00045882176306,\n top: 1028.0413251030714,\n right: 1051.4467448213675,\n bottom: 1116.9915041815966,\n },\n },\n {\n id: "block_2_AFJ4ch",\n type: "text",\n content:\n "End-to-end memory networks are based on a recurrent attention mechanism instead of sequence- aligned recurrence and have been shown to perform well on simple-language question answering and language modeling tasks [34].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.05524984763485,\n y: 1129.9793457949072,\n },\n {\n x: 1052.8165441359918,\n y: 1129.9793457949072,\n },\n {\n x: 1052.8165441359918,\n y: 1196.1117767678168,\n },\n {\n x: 224.05524984763485,\n y: 1196.1117767678168,\n },\n ],\n boundingBox: {\n left: 224.05524984763485,\n top: 1129.9793457949072,\n right: 1052.8165441359918,\n bottom: 1196.1117767678168,\n },\n },\n {\n id: "block_2_CBbJP3",\n type: "text",\n content:\n "To the best of our knowledge, however, the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence- aligned RNNs or convolution. In the following sections, we will describe the Transformer, motivate self-attention and discuss its advantages over models such as [17, 18] and [9].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.898,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 222.86987026242443,\n y: 1210.5673043387276,\n },\n {\n x: 1052.2374396776631,\n y: 1210.5673043387276,\n },\n {\n x: 1052.2374396776631,\n y: 1298.352294004053,\n },\n {\n x: 222.86987026242443,\n y: 1298.352294004053,\n },\n ],\n boundingBox: {\n left: 222.86987026242443,\n top: 1210.5673043387276,\n right: 1052.2374396776631,\n bottom: 1298.352294004053,\n },\n },\n {\n id: "block_2_RlRHBW",\n type: "section_heading",\n content: "### 3 Model Architecture",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.20267675914906,\n y: 1339.2827093368187,\n },\n {\n x: 470.2105250671832,\n y: 1339.2827093368187,\n },\n {\n x: 470.2105250671832,\n y: 1359.0320211424864,\n },\n {\n x: 224.20267675914906,\n y: 1359.0320211424864,\n },\n ],\n boundingBox: {\n left: 224.20267675914906,\n top: 1339.2827093368187,\n right: 470.2105250671832,\n bottom: 1359.0320211424864,\n },\n },\n {\n id: "block_2_OhVaOm",\n type: "text",\n content:\n "Most competitive neural sequence transduction models have an encoder-decoder structure [5, 2, 35]. Here, the encoder maps an input sequence of symbol representations (x1, ... , In) to a sequence of continuous representations z = (Z1, ... , Zn). Given z, the decoder then generates an output sequence (31, ... , ym) of symbols one element at a time. At each step the model is auto-regressive [10], consuming the previously generated symbols as additional input when generating the next.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.619,\n avgOcrConfidence: 0.969,\n },\n polygon: [\n {\n x: 223.9033023806384,\n y: 1394.2295871247027,\n },\n {\n x: 1051.703398767179,\n y: 1394.2295871247027,\n },\n {\n x: 1051.703398767179,\n y: 1505.850527885265,\n },\n {\n x: 223.9033023806384,\n y: 1505.850527885265,\n },\n ],\n boundingBox: {\n left: 223.9033023806384,\n top: 1394.2295871247027,\n right: 1051.703398767179,\n bottom: 1505.850527885265,\n },\n },\n {\n id: "block_2_MzhUlf",\n type: "page_number",\n content: "2",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 631.4816022441336,\n y: 1547.6769732138268,\n },\n {\n x: 642.0810031194757,\n y: 1547.6769732138268,\n },\n {\n x: 642.0810031194757,\n y: 1563.2578182363868,\n },\n {\n x: 631.4816022441336,\n y: 1563.2578182363868,\n },\n ],\n boundingBox: {\n left: 631.4816022441336,\n top: 1547.6769732138268,\n right: 642.0810031194757,\n bottom: 1563.2578182363868,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_3_afwbz8",\n type: "figure",\n content:\n \'<figure type="diagram">\\nOutput Probabilities\\n\\nSoftmax\\n\\nLinear\\n\\nAdd & Norm Feed Forward\\n\\nAdd & Norm\\n\\nAdd & Norm\\n\\nMulti-Head Feed Attention Forward Nx\\n\\nAdd & Norm\\n\\nNx Add & Norm\\n\\nMasked Multi-Head Multi-Head Attention Attention\\n\\nPositional Positional Encoding Encoding Input Output Embedding Embedding\\n\\nInputs Outputs (shifted right)\\n<caption>Transformer Architecture Diagram\\n\\nLeft Side: Encoder (Nx)\\n- Inputs\\n\\u2193\\n- Input Embedding\\n\\u2193\\n- Positional Encoding (added to Input Embedding)\\n\\u2193\\n- Multi-Head Attention\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Feed Forward\\n\\u2193\\n- Add & Norm\\n\\nRight Side: Decoder (Nx)\\n- Outputs (shifted right)\\n\\u2193\\n- Output Embedding\\n\\u2193\\n- Positional Encoding (added to Output Embedding)\\n\\u2193\\n- Masked Multi-Head Attention\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Multi-Head Attention (receives input from Encoder\\\'s Add & Norm)\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Feed Forward\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Linear\\n\\u2193\\n- Softmax\\n\\u2193\\n- Output Probabilities</caption>\\n</figure>\',\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.868,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 409.83791490540887,\n y: 150.86351013900642,\n },\n {\n x: 863.1759754932709,\n y: 150.86351013900642,\n },\n {\n x: 863.1759754932709,\n y: 821.7723977798806,\n },\n {\n x: 409.83791490540887,\n y: 821.7723977798806,\n },\n ],\n boundingBox: {\n left: 409.83791490540887,\n top: 150.86351013900642,\n right: 863.1759754932709,\n bottom: 821.7723977798806,\n },\n },\n {\n id: "block_3_1WIk1S",\n type: "text",\n content: "Figure 1: The Transformer - model architecture.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 436.4703770101505,\n y: 843.2910397178248,\n },\n {\n x: 836.1937028648209,\n y: 843.2910397178248,\n },\n {\n x: 836.1937028648209,\n y: 863.7018851373429,\n },\n {\n x: 436.4703770101505,\n y: 863.7018851373429,\n },\n ],\n boundingBox: {\n left: 436.4703770101505,\n top: 843.2910397178248,\n right: 836.1937028648209,\n bottom: 863.7018851373429,\n },\n },\n {\n id: "block_3_jyPEOL",\n type: "text",\n content:\n "The Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1, respectively.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.973,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.86804783953366,\n y: 910.1303693154701,\n },\n {\n x: 1051.9256870241932,\n y: 910.1303693154701,\n },\n {\n x: 1051.9256870241932,\n y: 977.3362178945899,\n },\n {\n x: 222.86804783953366,\n y: 977.3362178945899,\n },\n ],\n boundingBox: {\n left: 222.86804783953366,\n top: 910.1303693154701,\n right: 1051.9256870241932,\n bottom: 977.3362178945899,\n },\n },\n {\n id: "block_3_nEQfm1",\n type: "section_heading",\n content: "### 3.1 Encoder and Decoder Stacks",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.72352154585568,\n y: 1007.3903008367782,\n },\n {\n x: 527.4041196725664,\n y: 1007.3903008367782,\n },\n {\n x: 527.4041196725664,\n y: 1023.9329030316575,\n },\n {\n x: 223.72352154585568,\n y: 1023.9329030316575,\n },\n ],\n boundingBox: {\n left: 223.72352154585568,\n top: 1007.3903008367782,\n right: 527.4041196725664,\n bottom: 1023.9329030316575,\n },\n },\n {\n id: "block_3_W2U9b2",\n type: "text",\n content:\n "Encoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position- wise fully connected feed-forward network. We employ a residual connection [11] around each of the two sub-layers, followed by layer normalization [1]. That is, the output of each sub-layer is LayerNorm(x + Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer itself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding layers, produce outputs of dimension dmodel = 512.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.657,\n avgOcrConfidence: 0.984,\n },\n polygon: [\n {\n x: 223.8025010937322,\n y: 1048.091523421438,\n },\n {\n x: 1053.5889674277203,\n y: 1048.091523421438,\n },\n {\n x: 1053.5889674277203,\n y: 1206.3018568225373,\n },\n {\n x: 223.8025010937322,\n y: 1206.3018568225373,\n },\n ],\n boundingBox: {\n left: 223.8025010937322,\n top: 1048.091523421438,\n right: 1053.5889674277203,\n bottom: 1206.3018568225373,\n },\n },\n {\n id: "block_3_8wxg0F",\n type: "text",\n content:\n "Decoder: The decoder is also composed of a stack of N = 6 identical layers. In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head attention over the output of the encoder stack. Similar to the encoder, we employ residual connections around each of the sub-layers, followed by layer normalization. We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position i can depend only on the known outputs at positions less than i.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.633,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 224.16407452882643,\n y: 1233.3413921729066,\n },\n {\n x: 1049.721170689938,\n y: 1233.3413921729066,\n },\n {\n x: 1049.721170689938,\n y: 1391.0596241198086,\n },\n {\n x: 224.16407452882643,\n y: 1391.0596241198086,\n },\n ],\n boundingBox: {\n left: 224.16407452882643,\n top: 1233.3413921729066,\n right: 1049.721170689938,\n bottom: 1391.0596241198086,\n },\n },\n {\n id: "block_3_i0stGS",\n type: "section_heading",\n content: "### 3.2 Attention",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 224.0832962258889,\n y: 1421.7722100279386,\n },\n {\n x: 354.57085797386446,\n y: 1421.7722100279386,\n },\n {\n x: 354.57085797386446,\n y: 1437.668053017523,\n },\n {\n x: 224.0832962258889,\n y: 1437.668053017523,\n },\n ],\n boundingBox: {\n left: 224.0832962258889,\n top: 1421.7722100279386,\n right: 354.57085797386446,\n bottom: 1437.668053017523,\n },\n },\n {\n id: "block_3_LwJLS3",\n type: "text",\n content:\n "An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.986,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.38670466068018,\n y: 1462.3713376611695,\n },\n {\n x: 1052.432178580848,\n y: 1462.3713376611695,\n },\n {\n x: 1052.432178580848,\n y: 1506.3117546138906,\n },\n {\n x: 223.38670466068018,\n y: 1506.3117546138906,\n },\n ],\n boundingBox: {\n left: 223.38670466068018,\n top: 1462.3713376611695,\n right: 1052.432178580848,\n bottom: 1506.3117546138906,\n },\n },\n {\n id: "block_3_gqT8MC",\n type: "page_number",\n content: "3",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.997,\n avgOcrConfidence: 0.997,\n },\n polygon: [\n {\n x: 632.2706403523466,\n y: 1547.236487481827,\n },\n {\n x: 642.0801037419451,\n y: 1547.236487481827,\n },\n {\n x: 642.0801037419451,\n y: 1562.977578012567,\n },\n {\n x: 632.2706403523466,\n y: 1562.977578012567,\n },\n ],\n boundingBox: {\n left: 632.2706403523466,\n top: 1547.236487481827,\n right: 642.0801037419451,\n bottom: 1562.977578012567,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_4_PplY2k",\n type: "header",\n content: "Scaled Dot-Product Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Header",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 307.9120037329458,\n y: 148.57123934236685,\n },\n {\n x: 554.1308270753735,\n y: 148.57123934236685,\n },\n {\n x: 554.1308270753735,\n y: 164.4924521697195,\n },\n {\n x: 307.9120037329458,\n y: 164.4924521697195,\n },\n ],\n boundingBox: {\n left: 307.9120037329458,\n top: 148.57123934236685,\n right: 554.1308270753735,\n bottom: 164.4924521697195,\n },\n },\n {\n id: "block_4_TZACGH",\n type: "text",\n content: "Multi-Head Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 756.6973442578839,\n y: 148.30866211339045,\n },\n {\n x: 937.5759876557511,\n y: 148.30866211339045,\n },\n {\n x: 937.5759876557511,\n y: 164.44492071911804,\n },\n {\n x: 756.6973442578839,\n y: 164.44492071911804,\n },\n ],\n boundingBox: {\n left: 756.6973442578839,\n top: 148.30866211339045,\n right: 937.5759876557511,\n bottom: 164.44492071911804,\n },\n },\n {\n id: "block_4_yRQL9Y",\n type: "figure",\n content:\n \'<figure type="diagram">\\n1 MatMul\\n\\n1 SoftMax 1 Mask (opt.) 1 Scale 1 MatMul 1 1 Q K V\\n<caption>Scaled Dot-Product Attention Diagram\\n\\nInputs: Q, K, V\\n\\n1. MatMul (Q, K)\\n \\u2193\\n2. Scale\\n \\u2193\\n3. Mask (opt.)\\n \\u2193\\n4. SoftMax\\n \\u2193\\n5. MatMul (Result of SoftMax, V)\\n \\u2193\\nOutput</caption>\\n</figure>\',\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.226,\n avgOcrConfidence: 0.815,\n },\n polygon: [\n {\n x: 364.7714322500855,\n y: 195.77549835434533,\n },\n {\n x: 497.28713766501767,\n y: 195.77549835434533,\n },\n {\n x: 497.28713766501767,\n y: 457.62115733784844,\n },\n {\n x: 364.7714322500855,\n y: 457.62115733784844,\n },\n ],\n boundingBox: {\n left: 364.7714322500855,\n top: 195.77549835434533,\n right: 497.28713766501767,\n bottom: 457.62115733784844,\n },\n },\n {\n id: "block_4_goCdts",\n type: "figure",\n content:\n \'<figure type="diagram">\\nLinear\\n\\nConcat\\n\\nScaled Dot-Product\\n\\nh\\n\\nAttention\\n\\nLinear Linear Linear\\n\\nV K Q\\n<caption>Multi-Head Attention\\n\\nInputs: V, K, Q\\n\\u2193\\nLinear (x3) \\u2192 Scaled Dot-Product Attention (h heads)\\n\\u2193\\nConcat\\n\\u2193\\nLinear</caption>\\n</figure>\',\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.981,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 723.0441991430129,\n y: 171.2063080421964,\n },\n {\n x: 971.0292342805515,\n y: 171.2063080421964,\n },\n {\n x: 971.0292342805515,\n y: 495.8982404264292,\n },\n {\n x: 723.0441991430129,\n y: 495.8982404264292,\n },\n ],\n boundingBox: {\n left: 723.0441991430129,\n top: 171.2063080421964,\n right: 971.0292342805515,\n bottom: 495.8982404264292,\n },\n },\n {\n id: "block_4_ZQ6XHX",\n type: "text",\n content:\n "Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.991,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.32437673972473,\n y: 572.2067347074809,\n },\n {\n x: 1050.060662039875,\n y: 572.2067347074809,\n },\n {\n x: 1050.060662039875,\n y: 615.706381804961,\n },\n {\n x: 224.32437673972473,\n y: 615.706381804961,\n },\n ],\n boundingBox: {\n left: 224.32437673972473,\n top: 572.2067347074809,\n right: 1050.060662039875,\n bottom: 615.706381804961,\n },\n },\n {\n id: "block_4_seZO33",\n type: "text",\n content:\n "of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.44408862260138,\n y: 661.3754045586836,\n },\n {\n x: 1049.3653012018135,\n y: 661.3754045586836,\n },\n {\n x: 1049.3653012018135,\n y: 705.0281940833071,\n },\n {\n x: 224.44408862260138,\n y: 705.0281940833071,\n },\n ],\n boundingBox: {\n left: 224.44408862260138,\n top: 661.3754045586836,\n right: 1049.3653012018135,\n bottom: 705.0281940833071,\n },\n },\n {\n id: "block_4_CMgLHk",\n type: "section_heading",\n content: "### 3.2.1 Scaled Dot-Product Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.53467593227862,\n y: 732.4767248397483,\n },\n {\n x: 549.2687448097842,\n y: 732.4767248397483,\n },\n {\n x: 549.2687448097842,\n y: 748.6887496431967,\n },\n {\n x: 223.53467593227862,\n y: 748.6887496431967,\n },\n ],\n boundingBox: {\n left: 223.53467593227862,\n top: 732.4767248397483,\n right: 549.2687448097842,\n bottom: 748.6887496431967,\n },\n },\n {\n id: "block_4_fmfLoy",\n type: "text",\n content:\n \'We call our particular attention "Scaled Dot-Product Attention" (Figure 2). The input consists of queries and keys of dimension dk, and values of dimension dy. We compute the dot products of the\\n\\nquery with all keys, divide each by Vdk, and apply a softmafunction to obtain the weights on the [x]\\n\\nvalues.\',\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.594,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 223.39593511428276,\n y: 771.1101458269851,\n },\n {\n x: 1051.4275265436104,\n y: 771.1101458269851,\n },\n {\n x: 1051.4275265436104,\n y: 856.1295272138783,\n },\n {\n x: 223.39593511428276,\n y: 856.1295272138783,\n },\n ],\n boundingBox: {\n left: 223.39593511428276,\n top: 771.1101458269851,\n right: 1051.4275265436104,\n bottom: 856.1295272138783,\n },\n },\n {\n id: "block_4_cDuW6h",\n type: "text",\n content:\n "In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix Q. The keys and values are also packed together into matrices K and V. We compute the matrix of outputs as:",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.976,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.08788778486044,\n y: 873.4355685585424,\n },\n {\n x: 1050.3812191260122,\n y: 873.4355685585424,\n },\n {\n x: 1050.3812191260122,\n y: 938.6725377821385,\n },\n {\n x: 224.08788778486044,\n y: 938.6725377821385,\n },\n ],\n boundingBox: {\n left: 224.08788778486044,\n top: 873.4355685585424,\n right: 1050.3812191260122,\n bottom: 938.6725377821385,\n },\n },\n {\n id: "block_4_VaSWNE",\n type: "text",\n content: "QKT Attention(Q, K, V) = softmax( V Vdk",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.961,\n },\n polygon: [\n {\n x: 458.52888900868214,\n y: 968.9788274549901,\n },\n {\n x: 816.6205023327013,\n y: 968.9788274549901,\n },\n {\n x: 816.6205023327013,\n y: 1021.9395890773686,\n },\n {\n x: 458.52888900868214,\n y: 1021.9395890773686,\n },\n ],\n boundingBox: {\n left: 458.52888900868214,\n top: 968.9788274549901,\n right: 816.6205023327013,\n bottom: 1021.9395890773686,\n },\n },\n {\n id: "block_4_Wtl7xI",\n type: "text",\n content: "(1)",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 1026.9459968065694,\n y: 986.4570474839747,\n },\n {\n x: 1051.0514920645387,\n y: 986.4570474839747,\n },\n {\n x: 1051.0514920645387,\n y: 1005.8566982871607,\n },\n {\n x: 1026.9459968065694,\n y: 1005.8566982871607,\n },\n ],\n boundingBox: {\n left: 1026.9459968065694,\n top: 986.4570474839747,\n right: 1051.0514920645387,\n bottom: 1005.8566982871607,\n },\n },\n {\n id: "block_4_HVInAp",\n type: "text",\n content:\n "The two most commonly used attention functions are additive attention [2], and dot-product (multi- plicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor\\n\\nof . Additive attention computes the compatibility function using a feed-forward network with [x] Vdk\\n\\na single hidden layer. While the two are similar in theoretical complexity, dot-product attention is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.098,\n avgOcrConfidence: 0.981,\n },\n polygon: [\n {\n x: 223.11696240501684,\n y: 1041.6009173859331,\n },\n {\n x: 1052.8067929901345,\n y: 1041.6009173859331,\n },\n {\n x: 1052.8067929901345,\n y: 1180.0422397699572,\n },\n {\n x: 223.11696240501684,\n y: 1180.0422397699572,\n },\n ],\n boundingBox: {\n left: 223.11696240501684,\n top: 1041.6009173859331,\n right: 1052.8067929901345,\n bottom: 1180.0422397699572,\n },\n },\n {\n id: "block_4_6NHlzf",\n type: "text",\n content:\n "While for small values of dk the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of dk [3]. We suspect that for large values of dk, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients 4. To counteract this effect, we scale the dot products by.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.58,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 223.18699551324775,\n y: 1194.0708248167111,\n },\n {\n x: 1050.8364934990875,\n y: 1194.0708248167111,\n },\n {\n x: 1050.8364934990875,\n y: 1289.5664457163416,\n },\n {\n x: 223.18699551324775,\n y: 1289.5664457163416,\n },\n ],\n boundingBox: {\n left: 223.18699551324775,\n top: 1194.0708248167111,\n right: 1050.8364934990875,\n bottom: 1289.5664457163416,\n },\n },\n {\n id: "block_4_4VWmvI",\n type: "section_heading",\n content: "### 3.2.2 Multi-Head Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.5976323594142,\n y: 1315.4335938647278,\n },\n {\n x: 479.8474026422431,\n y: 1315.4335938647278,\n },\n {\n x: 479.8474026422431,\n y: 1331.4542616650574,\n },\n {\n x: 223.5976323594142,\n y: 1331.4542616650574,\n },\n ],\n boundingBox: {\n left: 223.5976323594142,\n top: 1315.4335938647278,\n right: 479.8474026422431,\n bottom: 1331.4542616650574,\n },\n },\n {\n id: "block_4_n7aPpb",\n type: "text",\n content:\n "Instead of performing a single attention function with dmodel-dimensional keys, values and queries, we found it beneficial to linearly project the queries, keys and values h times with different, learned linear projections to dk, dk and dy dimensions, respectively. On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding dy-dimensional",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.619,\n avgOcrConfidence: 0.979,\n },\n polygon: [\n {\n x: 223.83094982509195,\n y: 1354.33461159154,\n },\n {\n x: 1052.0098498267848,\n y: 1354.33461159154,\n },\n {\n x: 1052.0098498267848,\n y: 1442.8801044664883,\n },\n {\n x: 223.83094982509195,\n y: 1442.8801044664883,\n },\n ],\n boundingBox: {\n left: 223.83094982509195,\n top: 1354.33461159154,\n right: 1052.0098498267848,\n bottom: 1442.8801044664883,\n },\n },\n {\n id: "block_4_rfqNPC",\n type: "text",\n content:\n "4To illustrate why the dot products get large, assume that the components of q and k are independent random variables with mean 0 and variance 1. Then their dot product, q \\u00b7 k = >i=1 qiki, has mean 0 and variance dk-",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.105,\n avgOcrConfidence: 0.921,\n },\n polygon: [\n {\n x: 224.42529636577967,\n y: 1459.9841341864794,\n },\n {\n x: 1049.4534401998033,\n y: 1459.9841341864794,\n },\n {\n x: 1049.4534401998033,\n y: 1506.815978659723,\n },\n {\n x: 224.42529636577967,\n y: 1506.815978659723,\n },\n ],\n boundingBox: {\n left: 224.42529636577967,\n top: 1459.9841341864794,\n right: 1049.4534401998033,\n bottom: 1506.815978659723,\n },\n },\n {\n id: "block_4_35BhDQ",\n type: "page_number",\n content: "4",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.996,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 631.2688757903385,\n y: 1548.1330857241064,\n },\n {\n x: 642.0564832478544,\n y: 1548.1330857241064,\n },\n {\n x: 642.0564832478544,\n y: 1562.0727401962854,\n },\n {\n x: 631.2688757903385,\n y: 1562.0727401962854,\n },\n ],\n boundingBox: {\n left: 631.2688757903385,\n top: 1548.1330857241064,\n right: 642.0564832478544,\n bottom: 1562.0727401962854,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_5_Zc8VSW",\n type: "text",\n content:\n "output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure 2.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.988,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.67903916853186,\n y: 155.68632458564932,\n },\n {\n x: 1049.4719957783275,\n y: 155.68632458564932,\n },\n {\n x: 1049.4719957783275,\n y: 199.30535079841326,\n },\n {\n x: 224.67903916853186,\n y: 199.30535079841326,\n },\n ],\n boundingBox: {\n left: 224.67903916853186,\n top: 155.68632458564932,\n right: 1049.4719957783275,\n bottom: 199.30535079841326,\n },\n },\n {\n id: "block_5_P72mUL",\n type: "text",\n content:\n "Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 224.58133836732293,\n y: 212.29537068990837,\n },\n {\n x: 1049.5524663994781,\n y: 212.29537068990837,\n },\n {\n x: 1049.5524663994781,\n y: 255.9039790504857,\n },\n {\n x: 224.58133836732293,\n y: 255.9039790504857,\n },\n ],\n boundingBox: {\n left: 224.58133836732293,\n top: 212.29537068990837,\n right: 1049.5524663994781,\n bottom: 255.9039790504857,\n },\n },\n {\n id: "block_5_zTpvNY",\n type: "text",\n content:\n "MultiHead(Q,K,V)=Concat(head1, ... , headh)W\\u00ba where head; = Attention(Qw?, KWK,VW)",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.581,\n avgOcrConfidence: 0.796,\n },\n polygon: [\n {\n x: 388.73733464818804,\n y: 302.5467395065422,\n },\n {\n x: 883.3280911410811,\n y: 302.5467395065422,\n },\n {\n x: 883.3280911410811,\n y: 364.6030674267532,\n },\n {\n x: 388.73733464818804,\n y: 364.6030674267532,\n },\n ],\n boundingBox: {\n left: 388.73733464818804,\n top: 302.5467395065422,\n right: 883.3280911410811,\n bottom: 364.6030674267532,\n },\n },\n {\n id: "block_5_cOSQOc",\n type: "text",\n content:\n "Where the projections are parameter matrices Wo E Rdmodel X dk , WK \\u20ac Rdmodel X dk , WY \\u20ac Rdmodel X dy and WO E Rhdy Xdmodel",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.252,\n avgOcrConfidence: 0.682,\n },\n polygon: [\n {\n x: 223.51567066498916,\n y: 424.5787134959285,\n },\n {\n x: 1047.1388211215499,\n y: 424.5787134959285,\n },\n {\n x: 1047.1388211215499,\n y: 472.1556711698833,\n },\n {\n x: 223.51567066498916,\n y: 472.1556711698833,\n },\n ],\n boundingBox: {\n left: 223.51567066498916,\n top: 424.5787134959285,\n right: 1047.1388211215499,\n bottom: 472.1556711698833,\n },\n },\n {\n id: "block_5_4oR3J2",\n type: "text",\n content:\n "In this work we employ h = 8 parallel attention layers, or heads. For each of these we use dk = dy = dmodel/h = 64. Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.557,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 223.83189653828197,\n y: 488.323372747665,\n },\n {\n x: 1049.9097559573877,\n y: 488.323372747665,\n },\n {\n x: 1049.9097559573877,\n y: 555.0531728357302,\n },\n {\n x: 223.83189653828197,\n y: 555.0531728357302,\n },\n ],\n boundingBox: {\n left: 223.83189653828197,\n top: 488.323372747665,\n right: 1049.9097559573877,\n bottom: 555.0531728357302,\n },\n },\n {\n id: "block_5_oGR7Tp",\n type: "section_heading",\n content: "### 3.2.3 Applications of Attention in our Model",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.9031130380004,\n y: 584.1135347409356,\n },\n {\n x: 629.6546824657133,\n y: 584.1135347409356,\n },\n {\n x: 629.6546824657133,\n y: 605.02614180486,\n },\n {\n x: 223.9031130380004,\n y: 605.02614180486,\n },\n ],\n boundingBox: {\n left: 223.9031130380004,\n top: 584.1135347409356,\n right: 629.6546824657133,\n bottom: 605.02614180486,\n },\n },\n {\n id: "block_5_b34egv",\n type: "text",\n content:\n "The Transformer uses multi-head attention in three different ways:",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.3985859112148,\n y: 623.9660812033746,\n },\n {\n x: 775.7513199409428,\n y: 623.9660812033746,\n },\n {\n x: 775.7513199409428,\n y: 644.7702005429376,\n },\n {\n x: 223.3985859112148,\n y: 644.7702005429376,\n },\n ],\n boundingBox: {\n left: 223.3985859112148,\n top: 623.9660812033746,\n right: 775.7513199409428,\n bottom: 644.7702005429376,\n },\n },\n {\n id: "block_5_NSYaLO",\n type: "text",\n content:\n \'\\u00b7 In "encoder-decoder attention" layers, the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder. This allows every position in the decoder to attend over all positions in the input sequence. This mimics the typical encoder-decoder attention mechanisms in sequence-to-sequence models such as [38, 2, 9].\',\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.586,\n avgOcrConfidence: 0.984,\n },\n polygon: [\n {\n x: 281.7719981618171,\n y: 667.4162908568419,\n },\n {\n x: 1052.1352893244612,\n y: 667.4162908568419,\n },\n {\n x: 1052.1352893244612,\n y: 778.3123385207098,\n },\n {\n x: 281.7719981618171,\n y: 778.3123385207098,\n },\n ],\n boundingBox: {\n left: 281.7719981618171,\n top: 667.4162908568419,\n right: 1052.1352893244612,\n bottom: 778.3123385207098,\n },\n },\n {\n id: "block_5_ZbEUX6",\n type: "text",\n content:\n "\\u00b7 The encoder contains self-attention layers. In a self-attention layer all of the keys, values and queries come from the same place, in this case, the output of the previous layer in the encoder. Each position in the encoder can attend to all positions in the previous layer of the encoder.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.407,\n avgOcrConfidence: 0.983,\n },\n polygon: [\n {\n x: 282.1731915439132,\n y: 791.5420637202442,\n },\n {\n x: 1049.6795153095775,\n y: 791.5420637202442,\n },\n {\n x: 1049.6795153095775,\n y: 876.9418387735697,\n },\n {\n x: 282.1731915439132,\n y: 876.9418387735697,\n },\n ],\n boundingBox: {\n left: 282.1731915439132,\n top: 791.5420637202442,\n right: 1049.6795153095775,\n bottom: 876.9418387735697,\n },\n },\n {\n id: "block_5_wkxEH8",\n type: "text",\n content:\n "\\u00b7 Similarly, self-attention layers in the decoder allow each position in the decoder to attend to all positions in the decoder up to and including that position. We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to -oo) all values in the input of the softmax which correspond to illegal connections. See Figure 2.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.543,\n avgOcrConfidence: 0.985,\n },\n polygon: [\n {\n x: 281.12820952478114,\n y: 893.687589086088,\n },\n {\n x: 1049.8325041610829,\n y: 893.687589086088,\n },\n {\n x: 1049.8325041610829,\n y: 1005.0602061336201,\n },\n {\n x: 281.12820952478114,\n y: 1005.0602061336201,\n },\n ],\n boundingBox: {\n left: 281.12820952478114,\n top: 893.687589086088,\n right: 1049.8325041610829,\n bottom: 1005.0602061336201,\n },\n },\n {\n id: "block_5_vVMF0e",\n type: "section_heading",\n content: "### 3.3 Position-wise Feed-Forward Networks",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.59919443617773,\n y: 1037.180243872162,\n },\n {\n x: 609.3837069768975,\n y: 1037.180243872162,\n },\n {\n x: 609.3837069768975,\n y: 1053.935843790384,\n },\n {\n x: 223.59919443617773,\n y: 1053.935843790384,\n },\n ],\n boundingBox: {\n left: 223.59919443617773,\n top: 1037.180243872162,\n right: 609.3837069768975,\n bottom: 1053.935843790384,\n },\n },\n {\n id: "block_5_WtW3Xc",\n type: "text",\n content:\n "In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forward network, which is applied to each position separately and identically. This consists of two linear transformations with a ReLU activation in between.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.986,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.937928415563,\n y: 1079.1571798109471,\n },\n {\n x: 1049.736412772297,\n y: 1079.1571798109471,\n },\n {\n x: 1049.736412772297,\n y: 1142.9025967246607,\n },\n {\n x: 223.937928415563,\n y: 1142.9025967246607,\n },\n ],\n boundingBox: {\n left: 223.937928415563,\n top: 1079.1571798109471,\n right: 1049.736412772297,\n bottom: 1142.9025967246607,\n },\n },\n {\n id: "block_5_TCB4QK",\n type: "text",\n content: "FFN(x)=max(0,xW1+b1)W2+b2",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.668,\n avgOcrConfidence: 0.668,\n },\n polygon: [\n {\n x: 471.6477776965956,\n y: 1184.1576702146604,\n },\n {\n x: 801.1487473536581,\n y: 1184.1576702146604,\n },\n {\n x: 801.1487473536581,\n y: 1206.444581397494,\n },\n {\n x: 471.6477776965956,\n y: 1206.444581397494,\n },\n ],\n boundingBox: {\n left: 471.6477776965956,\n top: 1184.1576702146604,\n right: 801.1487473536581,\n bottom: 1206.444581397494,\n },\n },\n {\n id: "block_5_olGJjx",\n type: "text",\n content: "(2)",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.997,\n avgOcrConfidence: 0.997,\n },\n polygon: [\n {\n x: 1026.9936164800267,\n y: 1185.5856736262042,\n },\n {\n x: 1051.1806237436558,\n y: 1185.5856736262042,\n },\n {\n x: 1051.1806237436558,\n y: 1204.3962422421102,\n },\n {\n x: 1026.9936164800267,\n y: 1204.3962422421102,\n },\n ],\n boundingBox: {\n left: 1026.9936164800267,\n top: 1185.5856736262042,\n right: 1051.1806237436558,\n bottom: 1204.3962422421102,\n },\n },\n {\n id: "block_5_KTjDsL",\n type: "text",\n content:\n "While the linear transformations are the same across different positions, they use different parameters from layer to layer. Another way of describing this is as two convolutions with kernel size 1. The dimensionality of input and output is dmodel = 512, and the inner-layer has dimensionality dff =2048.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.881,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 222.78797957148865,\n y: 1230.1093008858818,\n },\n {\n x: 1052.541145269018,\n y: 1230.1093008858818,\n },\n {\n x: 1052.541145269018,\n y: 1320.3967533541802,\n },\n {\n x: 222.78797957148865,\n y: 1320.3967533541802,\n },\n ],\n boundingBox: {\n left: 222.78797957148865,\n top: 1230.1093008858818,\n right: 1052.541145269018,\n bottom: 1320.3967533541802,\n },\n },\n {\n id: "block_5_Pwzvu2",\n type: "section_heading",\n content: "### 3.4 Embeddings and Softmax",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.997,\n },\n polygon: [\n {\n x: 223.80512822283447,\n y: 1351.0096120045598,\n },\n {\n x: 499.655388045485,\n y: 1351.0096120045598,\n },\n {\n x: 499.655388045485,\n y: 1371.2419333206979,\n },\n {\n x: 223.80512822283447,\n y: 1371.2419333206979,\n },\n ],\n boundingBox: {\n left: 223.80512822283447,\n top: 1351.0096120045598,\n right: 499.655388045485,\n bottom: 1371.2419333206979,\n },\n },\n {\n id: "block_5_6y9ZGB",\n type: "text",\n content:\n "Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension dmodel. We also use the usual learned linear transfor- mation and softmax function to convert the decoder output to predicted next-token probabilities. In our model, we share the same weight matrix between the two embedding layers and the pre-softmax linear transformation, similar to [30]. In the embedding layers, we multiply those weights by Vdmodel -",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.275,\n avgOcrConfidence: 0.983,\n },\n polygon: [\n {\n x: 224.49331770848184,\n y: 1394.318801822519,\n },\n {\n x: 1052.2855327077154,\n y: 1394.318801822519,\n },\n {\n x: 1052.2855327077154,\n y: 1505.8341434450076,\n },\n {\n x: 224.49331770848184,\n y: 1505.8341434450076,\n },\n ],\n boundingBox: {\n left: 224.49331770848184,\n top: 1394.318801822519,\n right: 1052.2855327077154,\n bottom: 1505.8341434450076,\n },\n },\n {\n id: "block_5_o8MKrc",\n type: "page_number",\n content: "5",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 631.5606054598397,\n y: 1547.4356578740858,\n },\n {\n x: 641.9868998283888,\n y: 1547.4356578740858,\n },\n {\n x: 641.9868998283888,\n y: 1563.1716341864794,\n },\n {\n x: 631.5606054598397,\n y: 1563.1716341864794,\n },\n ],\n boundingBox: {\n left: 631.5606054598397,\n top: 1547.4356578740858,\n right: 641.9868998283888,\n bottom: 1563.1716341864794,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_6_YmUPFZ",\n type: "text",\n content:\n "Table 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations for different layer types. n is the sequence length, d is the representation dimension, k is the kernel size of convolutions and r the size of the neighborhood in restricted self-attention.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.977,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.7798615058843,\n y: 148.2273318355245,\n },\n {\n x: 1048.906618661254,\n y: 148.2273318355245,\n },\n {\n x: 1048.906618661254,\n y: 214.40370720311216,\n },\n {\n x: 222.7798615058843,\n y: 214.40370720311216,\n },\n ],\n boundingBox: {\n left: 222.7798615058843,\n top: 148.2273318355245,\n right: 1048.906618661254,\n bottom: 214.40370720311216,\n },\n },\n {\n id: "block_6_kibLxu",\n type: "table",\n content:\n "| Layer Type | Complexity per Layer | Sequential Operations | Maximum Path Length |\\n| --- | --- | --- | --- |\\n| Self-Attention | O(n2 \\u00b7 d) | O(1) | O(1) |\\n| Recurrent | O(n \\u00b7 d2) | O(n) | O(n) |\\n| Convolutional | O(k \\u00b7 n \\u00b7 d2) | O(1) | O(logk(n)) |\\n| Self-Attention (restricted) | O(r . n . d) [ ] | O(1) | O(n/r) [ ] |",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.256,\n avgOcrConfidence: 0.856,\n },\n polygon: [\n {\n x: 246.08119491243013,\n y: 233.8958637983279,\n },\n {\n x: 1028.2713006012632,\n y: 233.8958637983279,\n },\n {\n x: 1028.2713006012632,\n y: 389.94297754674926,\n },\n {\n x: 246.08119491243013,\n y: 389.94297754674926,\n },\n ],\n boundingBox: {\n left: 246.08119491243013,\n top: 233.8958637983279,\n right: 1028.2713006012632,\n bottom: 389.94297754674926,\n },\n },\n {\n id: "block_6_tUIpoY",\n type: "section_heading",\n content: "### 3.5 Positional Encoding",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.00651778617916,\n y: 445.9595083078944,\n },\n {\n x: 448.20427163674015,\n y: 445.9595083078944,\n },\n {\n x: 448.20427163674015,\n y: 466.69903696390026,\n },\n {\n x: 224.00651778617916,\n y: 466.69903696390026,\n },\n ],\n boundingBox: {\n left: 224.00651778617916,\n top: 445.9595083078944,\n right: 448.20427163674015,\n bottom: 466.69903696390026,\n },\n },\n {\n id: "block_6_mmxGrc",\n type: "text",\n content:\n \'Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence. To this end, we add "positional encodings" to the input embeddings at the bottoms of the encoder and decoder stacks. The positional encodings have the same dimension dmodel as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [9].\',\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.83698512167825,\n y: 487.3354288832586,\n },\n {\n x: 1050.4121766473256,\n y: 487.3354288832586,\n },\n {\n x: 1050.4121766473256,\n y: 620.7750930786133,\n },\n {\n x: 223.83698512167825,\n y: 620.7750930786133,\n },\n ],\n boundingBox: {\n left: 223.83698512167825,\n top: 487.3354288832586,\n right: 1050.4121766473256,\n bottom: 620.7750930786133,\n },\n },\n {\n id: "block_6_NG2aN8",\n type: "text",\n content:\n "In this work, we use sine and cosine functions of different frequencies:",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.39521455416715,\n y: 635.0555533789154,\n },\n {\n x: 810.5588871197108,\n y: 635.0555533789154,\n },\n {\n x: 810.5588871197108,\n y: 655.9754529393705,\n },\n {\n x: 224.39521455416715,\n y: 655.9754529393705,\n },\n ],\n boundingBox: {\n left: 224.39521455416715,\n top: 635.0555533789154,\n right: 810.5588871197108,\n bottom: 655.9754529393705,\n },\n },\n {\n id: "block_6_ktOzAP",\n type: "text",\n content:\n "PE(pos,2i) = sin(pos/100002i/dmodel ) PE(pos,2i+1) = cos(pos/100002i/dmodel) )",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.646,\n avgOcrConfidence: 0.856,\n },\n polygon: [\n {\n x: 470.62755222738224,\n y: 700.6432727440855,\n },\n {\n x: 804.2361684089159,\n y: 700.6432727440855,\n },\n {\n x: 804.2361684089159,\n y: 763.5065343469606,\n },\n {\n x: 470.62755222738224,\n y: 763.5065343469606,\n },\n ],\n boundingBox: {\n left: 470.62755222738224,\n top: 700.6432727440855,\n right: 804.2361684089159,\n bottom: 763.5065343469606,\n },\n },\n {\n id: "block_6_L0vHNu",\n type: "text",\n content:\n "where pos is the position and i is the dimension. That is, each dimension of the positional encoding corresponds to a sinusoid. The wavelengths form a geometric progression from 27 to 10000 . 27. We chose this function because we hypothesized it would allow the model to easily learn to attend by relative positions, since for any fixed offset k, PEpos+k can be represented as a linear function of PEpos.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.291,\n avgOcrConfidence: 0.967,\n },\n polygon: [\n {\n x: 223.63699196028884,\n y: 787.3148307800293,\n },\n {\n x: 1050.8335586881985,\n y: 787.3148307800293,\n },\n {\n x: 1050.8335586881985,\n y: 900.202535012611,\n },\n {\n x: 223.63699196028884,\n y: 900.202535012611,\n },\n ],\n boundingBox: {\n left: 223.63699196028884,\n top: 787.3148307800293,\n right: 1050.8335586881985,\n bottom: 900.202535012611,\n },\n },\n {\n id: "block_6_Sai49H",\n type: "text",\n content:\n "We also experimented with using learned positional embeddings [9] instead, and found that the two versions produced nearly identical results (see Table 3 row (E)). We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.868,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 223.15007369883736,\n y: 912.2991767252298,\n },\n {\n x: 1049.522644933993,\n y: 912.2991767252298,\n },\n {\n x: 1049.522644933993,\n y: 1000.5864015736975,\n },\n {\n x: 223.15007369883736,\n y: 1000.5864015736975,\n },\n ],\n boundingBox: {\n left: 223.15007369883736,\n top: 912.2991767252298,\n right: 1049.522644933993,\n bottom: 1000.5864015736975,\n },\n },\n {\n id: "block_6_545oKE",\n type: "section_heading",\n content: "### 4 Why Self-Attention",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.44270274586924,\n y: 1036.185907234823,\n },\n {\n x: 468.14631162768734,\n y: 1036.185907234823,\n },\n {\n x: 468.14631162768734,\n y: 1059.806398205291,\n },\n {\n x: 223.44270274586924,\n y: 1059.806398205291,\n },\n ],\n boundingBox: {\n left: 223.44270274586924,\n top: 1036.185907234823,\n right: 468.14631162768734,\n bottom: 1059.806398205291,\n },\n },\n {\n id: "block_6_rdkytl",\n type: "text",\n content:\n "In this section we compare various aspects of self-attention layers to the recurrent and convolu- tional layers commonly used for mapping one variable-length sequence of symbol representations (x1, ... , In) to another sequence of equal length (21, ... , Zn), with xi, Zi E Rd, such as a hidden layer in a typical sequence transduction encoder or decoder. Motivating our use of self-attention we consider three desiderata.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.298,\n avgOcrConfidence: 0.936,\n },\n polygon: [\n {\n x: 222.55295802206888,\n y: 1087.3066867455505,\n },\n {\n x: 1052.7677884067061,\n y: 1087.3066867455505,\n },\n {\n x: 1052.7677884067061,\n y: 1195.3768446499244,\n },\n {\n x: 222.55295802206888,\n y: 1195.3768446499244,\n },\n ],\n boundingBox: {\n left: 222.55295802206888,\n top: 1087.3066867455505,\n right: 1052.7677884067061,\n bottom: 1195.3768446499244,\n },\n },\n {\n id: "block_6_y2UJTk",\n type: "text",\n content:\n "One is the total computational complexity per layer. Another is the amount of computation that can be parallelized, as measured by the minimum number of sequential operations required.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.43593374656064,\n y: 1212.4905345601246,\n },\n {\n x: 1048.7435946499345,\n y: 1212.4905345601246,\n },\n {\n x: 1048.7435946499345,\n y: 1255.7911059730932,\n },\n {\n x: 223.43593374656064,\n y: 1255.7911059730932,\n },\n ],\n boundingBox: {\n left: 223.43593374656064,\n top: 1212.4905345601246,\n right: 1048.7435946499345,\n bottom: 1255.7911059730932,\n },\n },\n {\n id: "block_6_OGHshO",\n type: "text",\n content:\n "The third is the path length between long-range dependencies in the network. Learning long-range dependencies is a key challenge in many sequence transduction tasks. One key factor affecting the ability to learn such dependencies is the length of the paths forward and backward signals have to traverse in the network. The shorter these paths between any combination of positions in the input and output sequences, the easier it is to learn long-range dependencies [12]. Hence we also compare the maximum path length between any two input and output positions in networks composed of the different layer types.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.983,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.87737296445525,\n y: 1268.8657945905413,\n },\n {\n x: 1049.749950770914,\n y: 1268.8657945905413,\n },\n {\n x: 1049.749950770914,\n y: 1426.1352065236945,\n },\n {\n x: 222.87737296445525,\n y: 1426.1352065236945,\n },\n ],\n boundingBox: {\n left: 222.87737296445525,\n top: 1268.8657945905413,\n right: 1049.749950770914,\n bottom: 1426.1352065236945,\n },\n },\n {\n id: "block_6_zgN3wO",\n type: "text",\n content:\n "As noted in Table 1, a self-attention layer connects all positions with a constant number of sequentially executed operations, whereas a recurrent layer requires O(n) sequential operations. In terms of computational complexity, self-attention layers are faster than recurrent layers when the sequence",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.4352473794979,\n y: 1439.235182109632,\n },\n {\n x: 1051.6017217705719,\n y: 1439.235182109632,\n },\n {\n x: 1051.6017217705719,\n y: 1506.1062388025728,\n },\n {\n x: 223.4352473794979,\n y: 1506.1062388025728,\n },\n ],\n boundingBox: {\n left: 223.4352473794979,\n top: 1439.235182109632,\n right: 1051.6017217705719,\n bottom: 1506.1062388025728,\n },\n },\n {\n id: "block_6_aNgpKT",\n type: "page_number",\n content: "6",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 631.7702550957673,\n y: 1548.2886905526757,\n },\n {\n x: 642.7105200551722,\n y: 1548.2886905526757,\n },\n {\n x: 642.7105200551722,\n y: 1563.5418467700931,\n },\n {\n x: 631.7702550957673,\n y: 1563.5418467700931,\n },\n ],\n boundingBox: {\n left: 631.7702550957673,\n top: 1548.2886905526757,\n right: 642.7105200551722,\n bottom: 1563.5418467700931,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_7_u723hy",\n type: "text",\n content:\n "length n is smaller than the representation dimensionality d, which is most often the case with sentence representations used by state-of-the-art models in machine translations, such as word-piece [38] and byte-pair [31] representations. To improve computational performance for tasks involving very long sequences, self-attention could be restricted to considering only a neighborhood of size r in the input sequence centered around the respective output position. This would increase the maximum path length to O(n/r). We plan to investigate this approach further in future work.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.909,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.89144479793353,\n y: 155.39061148363845,\n },\n {\n x: 1050.0338700565978,\n y: 155.39061148363845,\n },\n {\n x: 1050.0338700565978,\n y: 290.11272512163436,\n },\n {\n x: 223.89144479793353,\n y: 290.11272512163436,\n },\n ],\n boundingBox: {\n left: 223.89144479793353,\n top: 155.39061148363845,\n right: 1050.0338700565978,\n bottom: 290.11272512163436,\n },\n },\n {\n id: "block_7_SLgoxa",\n type: "text",\n content:\n "A single convolutional layer with kernel width k < n does not connect all pairs of input and output positions. Doing so requires a stack of O(n/k) convolutional layers in the case of contiguous kernels, or O(logk(n)) in the case of dilated convolutions [18], increasing the length of the longest paths between any two positions in the network. Convolutional layers are generally more expensive than recurrent layers, by a factor of k. Separable convolutions [6], however, decrease the complexity considerably, to O(k . n . d + n . d2). Even with k = n, however, the complexity of a separable convolution is equal to the combination of a self-attention layer and a point-wise feed-forward layer, the approach we take in our model.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.525,\n avgOcrConfidence: 0.977,\n },\n polygon: [\n {\n x: 223.84822734080961,\n y: 303.4973448416344,\n },\n {\n x: 1051.7048188369638,\n y: 303.4973448416344,\n },\n {\n x: 1051.7048188369638,\n y: 482.7421505003047,\n },\n {\n x: 223.84822734080961,\n y: 482.7421505003047,\n },\n ],\n boundingBox: {\n left: 223.84822734080961,\n top: 303.4973448416344,\n right: 1051.7048188369638,\n bottom: 482.7421505003047,\n },\n },\n {\n id: "block_7_lGN5L0",\n type: "text",\n content:\n "As side benefit, self-attention could yield more interpretable models. We inspect attention distributions from our models and present and discuss examples in the appendix. Not only do individual attention heads clearly learn to perform different tasks, many appear to exhibit behavior related to the syntactic and semantic structure of the sentences.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.94,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.7218884656029,\n y: 496.4417208334557,\n },\n {\n x: 1049.5183847246378,\n y: 496.4417208334557,\n },\n {\n x: 1049.5183847246378,\n y: 581.3287481437052,\n },\n {\n x: 223.7218884656029,\n y: 581.3287481437052,\n },\n ],\n boundingBox: {\n left: 223.7218884656029,\n top: 496.4417208334557,\n right: 1049.5183847246378,\n bottom: 581.3287481437052,\n },\n },\n {\n id: "block_7_FOtl5B",\n type: "heading",\n content: "# 5 Training",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.4122553915873,\n y: 625.3390120599503,\n },\n {\n x: 354.91415984439146,\n y: 625.3390120599503,\n },\n {\n x: 354.91415984439146,\n y: 649.7166914688913,\n },\n {\n x: 224.4122553915873,\n y: 649.7166914688913,\n },\n ],\n boundingBox: {\n left: 224.4122553915873,\n top: 625.3390120599503,\n right: 354.91415984439146,\n bottom: 649.7166914688913,\n },\n },\n {\n id: "block_7_3jYBCf",\n type: "text",\n content: "This section describes the training regime for our models.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.4527957665659,\n y: 679.1303132709704,\n },\n {\n x: 701.988161741382,\n y: 679.1303132709704,\n },\n {\n x: 701.988161741382,\n y: 699.7081758025894,\n },\n {\n x: 222.4527957665659,\n y: 699.7081758025894,\n },\n ],\n boundingBox: {\n left: 222.4527957665659,\n top: 679.1303132709704,\n right: 701.988161741382,\n bottom: 699.7081758025894,\n },\n },\n {\n id: "block_7_PIafds",\n type: "section_heading",\n content: "### 5.1 Training Data and Batching",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.68002007477475,\n y: 735.0401794318866,\n },\n {\n x: 519.6398407873446,\n y: 735.0401794318866,\n },\n {\n x: 519.6398407873446,\n y: 755.8565634247055,\n },\n {\n x: 223.68002007477475,\n y: 755.8565634247055,\n },\n ],\n boundingBox: {\n left: 223.68002007477475,\n top: 735.0401794318866,\n right: 519.6398407873446,\n bottom: 755.8565634247055,\n },\n },\n {\n id: "block_7_8RhsHH",\n type: "text",\n content:\n "We trained on the standard WMT 2014 English-German dataset consisting of about 4.5 million sentence pairs. Sentences were encoded using byte-pair encoding [3], which has a shared source- target vocabulary of about 37000 tokens. For English-French, we used the significantly larger WMT 2014 English-French dataset consisting of 36M sentences and split tokens into a 32000 word-piece vocabulary [38]. Sentence pairs were batched together by approximate sequence length. Each training batch contained a set of sentence pairs containing approximately 25000 source tokens and 25000 target tokens.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.911,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.70165247116648,\n y: 778.8621643467953,\n },\n {\n x: 1052.1871692072737,\n y: 778.8621643467953,\n },\n {\n x: 1052.1871692072737,\n y: 935.23512009929,\n },\n {\n x: 223.70165247116648,\n y: 935.23512009929,\n },\n ],\n boundingBox: {\n left: 223.70165247116648,\n top: 778.8621643467953,\n right: 1052.1871692072737,\n bottom: 935.23512009929,\n },\n },\n {\n id: "block_7_2fOgoW",\n type: "section_heading",\n content: "### 5.2 Hardware and Schedule",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.9209349138023,\n y: 971.4598863071069,\n },\n {\n x: 484.7486314982394,\n y: 971.4598863071069,\n },\n {\n x: 484.7486314982394,\n y: 987.6652342143811,\n },\n {\n x: 223.9209349138023,\n y: 987.6652342143811,\n },\n ],\n boundingBox: {\n left: 223.9209349138023,\n top: 971.4598863071069,\n right: 484.7486314982394,\n bottom: 987.6652342143811,\n },\n },\n {\n id: "block_7_7vykWe",\n type: "text",\n content:\n "We trained our models on one machine with 8 NVIDIA P100 GPUs. For our base models using the hyperparameters described throughout the paper, each training step took about 0.4 seconds. We trained the base models for a total of 100,000 steps or 12 hours. For our big models,(described on the bottom line of table 3), step time was 1.0 seconds. The big models were trained for 300,000 steps (3.5 days).",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.961,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.2459757449853,\n y: 1014.9955223485043,\n },\n {\n x: 1049.3973947789548,\n y: 1014.9955223485043,\n },\n {\n x: 1049.3973947789548,\n y: 1126.7015106660083,\n },\n {\n x: 223.2459757449853,\n y: 1126.7015106660083,\n },\n ],\n boundingBox: {\n left: 223.2459757449853,\n top: 1014.9955223485043,\n right: 1049.3973947789548,\n bottom: 1126.7015106660083,\n },\n },\n {\n id: "block_7_Xjy6qb",\n type: "section_heading",\n content: "### 5.3 Optimizer",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.84361211400832,\n y: 1161.1210525053784,\n },\n {\n x: 361.9454223744191,\n y: 1161.1210525053784,\n },\n {\n x: 361.9454223744191,\n y: 1181.9203891037102,\n },\n {\n x: 223.84361211400832,\n y: 1181.9203891037102,\n },\n ],\n boundingBox: {\n left: 223.84361211400832,\n top: 1161.1210525053784,\n right: 361.9454223744191,\n bottom: 1181.9203891037102,\n },\n },\n {\n id: "block_7_uZS3FC",\n type: "text",\n content:\n "We used the Adam optimizer [20] with 31 = 0.9, 32 = 0.98 and \\u20ac = 10-9. We varied the learning rate over the course of training, according to the formula:",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.472,\n avgOcrConfidence: 0.947,\n },\n polygon: [\n {\n x: 223.18536243299496,\n y: 1203.7906809068263,\n },\n {\n x: 1049.5936484232436,\n y: 1203.7906809068263,\n },\n {\n x: 1049.5936484232436,\n y: 1249.0720648514596,\n },\n {\n x: 223.18536243299496,\n y: 1249.0720648514596,\n },\n ],\n boundingBox: {\n left: 223.18536243299496,\n top: 1203.7906809068263,\n right: 1049.5936484232436,\n bottom: 1249.0720648514596,\n },\n },\n {\n id: "block_7_qvJczg",\n type: "text",\n content:\n "lrate = dmodel . min(step_num-0.5, step_num . warmup_steps-1.5)",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.563,\n avgOcrConfidence: 0.786,\n },\n polygon: [\n {\n x: 338.51696905428474,\n y: 1286.921258338412,\n },\n {\n x: 933.735361586522,\n y: 1286.921258338412,\n },\n {\n x: 933.735361586522,\n y: 1314.0637410099346,\n },\n {\n x: 338.51696905428474,\n y: 1314.0637410099346,\n },\n ],\n boundingBox: {\n left: 338.51696905428474,\n top: 1286.921258338412,\n right: 933.735361586522,\n bottom: 1314.0637410099346,\n },\n },\n {\n id: "block_7_ZRnl1T",\n type: "text",\n content: "(3)",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 1026.6387883764114,\n y: 1291.0368781986094,\n },\n {\n x: 1051.2767151324417,\n y: 1291.0368781986094,\n },\n {\n x: 1051.2767151324417,\n y: 1311.080825805664,\n },\n {\n x: 1026.6387883764114,\n y: 1311.080825805664,\n },\n ],\n boundingBox: {\n left: 1026.6387883764114,\n top: 1291.0368781986094,\n right: 1051.2767151324417,\n bottom: 1311.080825805664,\n },\n },\n {\n id: "block_7_M71nL9",\n type: "text",\n content:\n "This corresponds to increasing the learning rate linearly for the first warmup_steps training steps, and decreasing it thereafter proportionally to the inverse square root of the step number. We used warmup_steps = 4000.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.916,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 222.72840764400732,\n y: 1340.2761936044335,\n },\n {\n x: 1052.0266066502481,\n y: 1340.2761936044335,\n },\n {\n x: 1052.0266066502481,\n y: 1406.6737115616188,\n },\n {\n x: 222.72840764400732,\n y: 1406.6737115616188,\n },\n ],\n boundingBox: {\n left: 222.72840764400732,\n top: 1340.2761936044335,\n right: 1052.0266066502481,\n bottom: 1406.6737115616188,\n },\n },\n {\n id: "block_7_ACakMa",\n type: "section_heading",\n content: "### 5.4 Regularization",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.81116351942077,\n y: 1441.41800626597,\n },\n {\n x: 402.1996435457773,\n y: 1441.41800626597,\n },\n {\n x: 402.1996435457773,\n y: 1461.9926013803124,\n },\n {\n x: 223.81116351942077,\n y: 1461.9926013803124,\n },\n ],\n boundingBox: {\n left: 223.81116351942077,\n top: 1441.41800626597,\n right: 402.1996435457773,\n bottom: 1461.9926013803124,\n },\n },\n {\n id: "block_7_rR8JeL",\n type: "text",\n content: "We employ three types of regularization during training:",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.88627206844134,\n y: 1484.7892296583134,\n },\n {\n x: 690.987449144795,\n y: 1484.7892296583134,\n },\n {\n x: 690.987449144795,\n y: 1505.950728681751,\n },\n {\n x: 222.88627206844134,\n y: 1505.950728681751,\n },\n ],\n boundingBox: {\n left: 222.88627206844134,\n top: 1484.7892296583134,\n right: 690.987449144795,\n bottom: 1505.950728681751,\n },\n },\n {\n id: "block_7_I7j7Uy",\n type: "page_number",\n content: "7",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.996,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 631.8865114755004,\n y: 1547.4189893105872,\n },\n {\n x: 642.4512153124288,\n y: 1547.4189893105872,\n },\n {\n x: 642.4512153124288,\n y: 1562.541448836936,\n },\n {\n x: 631.8865114755004,\n y: 1562.541448836936,\n },\n ],\n boundingBox: {\n left: 631.8865114755004,\n top: 1547.4189893105872,\n right: 642.4512153124288,\n bottom: 1562.541448836936,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_8_8rtbBp",\n type: "text",\n content:\n "Table 2: The Transformer achieves better BLEU scores than previous state-of-the-art models on the English-to-German and English-to-French newstest2014 tests at a fraction of the training cost.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 222.40285664579295,\n y: 148.11078211418666,\n },\n {\n x: 1048.695596291201,\n y: 148.11078211418666,\n },\n {\n x: 1048.695596291201,\n y: 191.8824890538266,\n },\n {\n x: 222.40285664579295,\n y: 191.8824890538266,\n },\n ],\n boundingBox: {\n left: 222.40285664579295,\n top: 148.11078211418666,\n right: 1048.695596291201,\n bottom: 191.8824890538266,\n },\n },\n {\n id: "block_8_M3V7h9",\n type: "table",\n content:\n "| Model | BLEU | | Training Cost (FLOPs) | |\\n| --- | --- | --- | --- | --- |\\n| | EN-DE | EN-FR | EN-DE | EN-FR |\\n| ByteNet [18] | 23.75 | | | |\\n| Deep-Att + PosUnk [39] | | 39.2 | | 1.0 . 1020 |\\n| GNMT + RL [38] | 24.6 | 39.92 | 2.3 . 1019 | 1.4 . 1020 |\\n| ConvS2S [9] | 25.16 | 40.46 | 9.6 . 1018 | 1.5 . 1020 |\\n| MoE [32] | 26.03 | 40.56 | 2.0 \\u00b7 1019 | 1.2 . 1020 |\\n| Deep-Att + PosUnk Ensemble [39] | | 40.4 | | 8.0 . 1020 |\\n| GNMT + RL Ensemble [38] | 26.30 | 41.16 | 1.8 . 1020 | 1.1 . 1021 |\\n| ConvS2S Ensemble [9] | 26.36 | 41.29 | 7.7 . 1019 | 1.2 . 1021 |\\n| Transformer (base model) | 27.3 | 38.1 | 3.3 . | 1018 |\\n| Transformer (big) | 28.4 | 41.8 | 2.3. 1019 | |",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.141,\n avgOcrConfidence: 0.893,\n },\n polygon: [\n {\n x: 271.150136516042,\n y: 195.3426247575229,\n },\n {\n x: 1004.1704442379248,\n y: 195.3426247575229,\n },\n {\n x: 1004.1704442379248,\n y: 508.6132290201976,\n },\n {\n x: 271.150136516042,\n y: 508.6132290201976,\n },\n ],\n boundingBox: {\n left: 271.150136516042,\n top: 195.3426247575229,\n right: 1004.1704442379248,\n bottom: 508.6132290201976,\n },\n },\n {\n id: "block_8_Wl0xmI",\n type: "text",\n content:\n "Residual Dropout We apply dropout [33] to the output of each sub-layer, before it is added to the sub-layer input and normalized. In addition, we apply dropout to the sums of the embeddings and the positional encodings in both the encoder and decoder stacks. For the base model, we use a rate of Pdrop =0.1.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.893,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 223.9333605244212,\n y: 569.1121117154458,\n },\n {\n x: 1051.605887308608,\n y: 569.1121117154458,\n },\n {\n x: 1051.605887308608,\n y: 660.0886577520155,\n },\n {\n x: 223.9333605244212,\n y: 660.0886577520155,\n },\n ],\n boundingBox: {\n left: 223.9333605244212,\n top: 569.1121117154458,\n right: 1051.605887308608,\n bottom: 660.0886577520155,\n },\n },\n {\n id: "block_8_CtqTnb",\n type: "text",\n content:\n "Label Smoothing During training, we employed label smoothing of value Els = 0.1 [36]. This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.518,\n avgOcrConfidence: 0.977,\n },\n polygon: [\n {\n x: 223.52019122047145,\n y: 690.790115499855,\n },\n {\n x: 1049.6801780088103,\n y: 690.790115499855,\n },\n {\n x: 1049.6801780088103,\n y: 734.1354363233523,\n },\n {\n x: 223.52019122047145,\n y: 734.1354363233523,\n },\n ],\n boundingBox: {\n left: 223.52019122047145,\n top: 690.790115499855,\n right: 1049.6801780088103,\n bottom: 734.1354363233523,\n },\n },\n {\n id: "block_8_KA1kZT",\n type: "heading",\n content: "# 6 Results",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.16400352533717,\n y: 774.585115131579,\n },\n {\n x: 339.42863018843383,\n y: 774.585115131579,\n },\n {\n x: 339.42863018843383,\n y: 793.809935433524,\n },\n {\n x: 224.16400352533717,\n y: 793.809935433524,\n },\n ],\n boundingBox: {\n left: 224.16400352533717,\n top: 774.585115131579,\n right: 339.42863018843383,\n bottom: 793.809935433524,\n },\n },\n {\n id: "block_8_LYkEL8",\n type: "section_heading",\n content: "### 6.1 Machine Translation",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 224.2968510537252,\n y: 828.3471990026029,\n },\n {\n x: 455.2866330111984,\n y: 828.3471990026029,\n },\n {\n x: 455.2866330111984,\n y: 844.3720339438072,\n },\n {\n x: 224.2968510537252,\n y: 844.3720339438072,\n },\n ],\n boundingBox: {\n left: 224.2968510537252,\n top: 828.3471990026029,\n right: 455.2866330111984,\n bottom: 844.3720339438072,\n },\n },\n {\n id: "block_8_UnI1Ea",\n type: "text",\n content:\n "On the WMT 2014 English-to-German translation task, the big transformer model (Transformer (big) in Table 2) outperforms the best previously reported models (including ensembles) by more than 2.0 BLEU, establishing a new state-of-the-art BLEU score of 28.4. The configuration of this model is listed in the bottom line of Table 3. Training took 3.5 days on 8 P100 GPUs. Even our base model surpasses all previously published models and ensembles, at a fraction of the training cost of any of the competitive models.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.973,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.56291165317063,\n y: 872.0711140453367,\n },\n {\n x: 1050.5385628581919,\n y: 872.0711140453367,\n },\n {\n x: 1050.5385628581919,\n y: 1006.0390107004266,\n },\n {\n x: 223.56291165317063,\n y: 1006.0390107004266,\n },\n ],\n boundingBox: {\n left: 223.56291165317063,\n top: 872.0711140453367,\n right: 1050.5385628581919,\n bottom: 1006.0390107004266,\n },\n },\n {\n id: "block_8_pkBARc",\n type: "text",\n content:\n "On the WMT 2014 English-to-French translation task, our big model achieves a BLEU score of 41.0, outperforming all of the previously published single models, at less than 1/4 the training cost of the previous state-of-the-art model. The Transformer (big) model trained for English-to-French used dropout rate Pdrop = 0.1, instead of 0.3.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.945,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.05139199138557,\n y: 1019.1086798072756,\n },\n {\n x: 1052.2523977460653,\n y: 1019.1086798072756,\n },\n {\n x: 1052.2523977460653,\n y: 1109.5784446888401,\n },\n {\n x: 224.05139199138557,\n y: 1109.5784446888401,\n },\n ],\n boundingBox: {\n left: 224.05139199138557,\n top: 1019.1086798072756,\n right: 1052.2523977460653,\n bottom: 1109.5784446888401,\n },\n },\n {\n id: "block_8_vKs7Yg",\n type: "text",\n content:\n "For the base models, we used a single model obtained by averaging the last 5 checkpoints, which were written at 10-minute intervals. For the big models, we averaged the last 20 checkpoints. We used beam search with a beam size of 4 and length penalty & = 0.6 [38]. These hyperparameters were chosen after experimentation on the development set. We set the maximum output length during inference to input length + 50, but terminate early when possible [38].",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.099,\n avgOcrConfidence: 0.983,\n },\n polygon: [\n {\n x: 223.50279536560504,\n y: 1122.2645474197273,\n },\n {\n x: 1050.043905216412,\n y: 1122.2645474197273,\n },\n {\n x: 1050.043905216412,\n y: 1233.5787297872673,\n },\n {\n x: 223.50279536560504,\n y: 1233.5787297872673,\n },\n ],\n boundingBox: {\n left: 223.50279536560504,\n top: 1122.2645474197273,\n right: 1050.043905216412,\n bottom: 1233.5787297872673,\n },\n },\n {\n id: "block_8_42PSVl",\n type: "text",\n content:\n "Table 2 summarizes our results and compares our translation quality and training costs to other model architectures from the literature. We estimate the number of floating point operations used to train a model by multiplying the training time, the number of GPUs used, and an estimate of the sustained single-precision floating-point capacity of each GPU 5.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.975,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 222.3879459130503,\n y: 1247.2785842436597,\n },\n {\n x: 1049.63284234931,\n y: 1247.2785842436597,\n },\n {\n x: 1049.63284234931,\n y: 1336.1913537620603,\n },\n {\n x: 222.3879459130503,\n y: 1336.1913537620603,\n },\n ],\n boundingBox: {\n left: 222.3879459130503,\n top: 1247.2785842436597,\n right: 1049.63284234931,\n bottom: 1336.1913537620603,\n },\n },\n {\n id: "block_8_pDx0nB",\n type: "section_heading",\n content: "### 6.2 Model Variations",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.05955739264942,\n y: 1370.9984397027727,\n },\n {\n x: 424.93188398597886,\n y: 1370.9984397027727,\n },\n {\n x: 424.93188398597886,\n y: 1387.4261614003576,\n },\n {\n x: 224.05955739264942,\n y: 1387.4261614003576,\n },\n ],\n boundingBox: {\n left: 224.05955739264942,\n top: 1370.9984397027727,\n right: 424.93188398597886,\n bottom: 1387.4261614003576,\n },\n },\n {\n id: "block_8_XCLvsN",\n type: "text",\n content:\n "To evaluate the importance of different components of the Transformer, we varied our base model in different ways, measuring the change in performance on English-to-German translation on the",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.6526705888066,\n y: 1413.835037862448,\n },\n {\n x: 1049.9819901737853,\n y: 1413.835037862448,\n },\n {\n x: 1049.9819901737853,\n y: 1458.0598621798638,\n },\n {\n x: 222.6526705888066,\n y: 1458.0598621798638,\n },\n ],\n boundingBox: {\n left: 222.6526705888066,\n top: 1413.835037862448,\n right: 1049.9819901737853,\n bottom: 1458.0598621798638,\n },\n },\n {\n id: "block_8_6e9VRc",\n type: "text",\n content:\n "5We used values of 2.8, 3.7, 6.0 and 9.5 TFLOPS for K80, K40, M40 and P100, respectively.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.976,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 249.0640041601919,\n y: 1482.8447849015545,\n },\n {\n x: 944.2274051861172,\n y: 1482.8447849015545,\n },\n {\n x: 944.2274051861172,\n y: 1505.4603319670025,\n },\n {\n x: 249.0640041601919,\n y: 1505.4603319670025,\n },\n ],\n boundingBox: {\n left: 249.0640041601919,\n top: 1482.8447849015545,\n right: 944.2274051861172,\n bottom: 1505.4603319670025,\n },\n },\n {\n id: "block_8_HHxEh9",\n type: "page_number",\n content: "8",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.996,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 631.7743259624843,\n y: 1547.954182789738,\n },\n {\n x: 642.6607229413778,\n y: 1547.954182789738,\n },\n {\n x: 642.6607229413778,\n y: 1563.2957013352473,\n },\n {\n x: 631.7743259624843,\n y: 1563.2957013352473,\n },\n ],\n boundingBox: {\n left: 631.7743259624843,\n top: 1547.954182789738,\n right: 642.6607229413778,\n bottom: 1563.2957013352473,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_9_2CG18E",\n type: "text",\n content:\n "Table 3: Variations on the Transformer architecture. Unlisted values are identical to those of the base model. All metrics are on the English-to-German translation development set, newstest2013. Listed perplexities are per-wordpiece, according to our byte-pair encoding, and should not be compared to per-word perplexities.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 222.6654748847015,\n y: 147.86792777355453,\n },\n {\n x: 1049.6700481776775,\n y: 147.86792777355453,\n },\n {\n x: 1049.6700481776775,\n y: 237.19010704442076,\n },\n {\n x: 222.6654748847015,\n y: 237.19010704442076,\n },\n ],\n boundingBox: {\n left: 222.6654748847015,\n top: 147.86792777355453,\n right: 1049.6700481776775,\n bottom: 237.19010704442076,\n },\n },\n {\n id: "block_9_0WToWH",\n type: "table",\n content:\n "| | N | dmodel | dff | h | dk | dv | Pdrop | Els | train steps | PPL (dev) | BLEU (dev) | params \\u00d7106 |\\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\\n| base | 6 | 512 | 2048 | 8 | 64 | 64 | 0.1 | 0.1 | 100K | 4.92 | 25.8 | 65 |\\n| (A) | | | | 1 | 512 | 512 | | | | 5.29 | 24.9 | |\\n| | | | | 4 | 128 | 128 | | | | 5.00 | 25.5 | |\\n| | | | | 16 | 32 | 32 | | | | 4.91 | 25.8 | |\\n| | | | | 32 | 16 | 16 | | | | 5.01 | 25.4 | |\\n| (B) | | | | | 16 | | | | | 5.16 | 25.1 | 58 |\\n| | | | | | 32 | | | | | 5.01 | 25.4 | 60 |\\n| (C) | 2 | | | | | | | | | 6.11 | 23.7 | 36 |\\n| | 4 | | | | | | | | | 5.19 | 25.3 | 50 |\\n| | 8 | | | | | | | | | 4.88 | 25.5 | 80 |\\n| | | 256 | | | 32 | 32 | | | | 5.75 | 24.5 | 28 |\\n| | | 1024 | | | 128 | 128 | | | | 4.66 | 26.0 | 168 |\\n| | | | 1024 | | | | | | | 5.12 | 25.4 | 53 |\\n| | | | 4096 | | | | | | | 4.75 | 26.2 | 90 |\\n| (D) | | | | | | | 0.0 | | | 5.77 | 24.6 | |\\n| | | | | | | | 0.2 | | | 4.95 | 25.5 | |\\n| | | | | | | | | 0.0 | | 4.67 | 25.3 | |\\n| | | | | | | | | 0.2 | | 5.47 | 25.7 | |\\n| (E) | positional embedding | | | | | instead of | sinusoids | | | 4.92 | 25.7 | |\\n| big | 6 | 1024 | 4096 | 16 | | | 0.3 | | 300K | 4.33 | 26.4 | 213 |",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.612,\n avgOcrConfidence: 0.986,\n },\n polygon: [\n {\n x: 224.84461930546448,\n y: 268.65403318763674,\n },\n {\n x: 1060.6742636130673,\n y: 268.65403318763674,\n },\n {\n x: 1060.6742636130673,\n y: 801.2216690178204,\n },\n {\n x: 224.84461930546448,\n y: 801.2216690178204,\n },\n ],\n boundingBox: {\n left: 224.84461930546448,\n top: 268.65403318763674,\n right: 1060.6742636130673,\n bottom: 801.2216690178204,\n },\n },\n {\n id: "block_9_p8WB9c",\n type: "text",\n content:\n "development set, newstest2013. We used beam search as described in the previous section, but no checkpoint averaging. We present these results in Table 3.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.42882287241247,\n y: 862.6040329323675,\n },\n {\n x: 1049.5265264580719,\n y: 862.6040329323675,\n },\n {\n x: 1049.5265264580719,\n y: 905.6541023541213,\n },\n {\n x: 224.42882287241247,\n y: 905.6541023541213,\n },\n ],\n boundingBox: {\n left: 224.42882287241247,\n top: 862.6040329323675,\n right: 1049.5265264580719,\n bottom: 905.6541023541213,\n },\n },\n {\n id: "block_9_XvsIA2",\n type: "text",\n content:\n "In Table 3 rows (A), we vary the number of attention heads and the attention key and value dimensions, keeping the amount of computation constant, as described in Section 3.2.2. While single-head attention is 0.9 BLEU worse than the best setting, quality also drops off with too many heads.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.967,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.23600106343736,\n y: 918.8913094656807,\n },\n {\n x: 1052.034559041044,\n y: 918.8913094656807,\n },\n {\n x: 1052.034559041044,\n y: 986.1080494357232,\n },\n {\n x: 224.23600106343736,\n y: 986.1080494357232,\n },\n ],\n boundingBox: {\n left: 224.23600106343736,\n top: 918.8913094656807,\n right: 1052.034559041044,\n bottom: 986.1080494357232,\n },\n },\n {\n id: "block_9_lFHLbG",\n type: "text",\n content:\n "In Table 3 rows (B), we observe that reducing the attention key size dk hurts model quality. This suggests that determining compatibility is not easy and that a more sophisticated compatibility function than dot product may be beneficial. We further observe in rows (C) and (D) that, as expected, bigger models are better, and dropout is very helpful in avoiding over-fitting. In row (E) we replace our sinusoidal positional encoding with learned positional embeddings [9], and observe nearly identical results to the base model.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.881,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.0262804240206,\n y: 998.9746651326803,\n },\n {\n x: 1052.338643317675,\n y: 998.9746651326803,\n },\n {\n x: 1052.338643317675,\n y: 1130.1984048140678,\n },\n {\n x: 224.0262804240206,\n y: 1130.1984048140678,\n },\n ],\n boundingBox: {\n left: 224.0262804240206,\n top: 998.9746651326803,\n right: 1052.338643317675,\n bottom: 1130.1984048140678,\n },\n },\n {\n id: "block_9_nnE2Kn",\n type: "section_heading",\n content: "### 6.3 English Constituency Parsing",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.00199723069687,\n y: 1168.0604785546325,\n },\n {\n x: 533.1579584274849,\n y: 1168.0604785546325,\n },\n {\n x: 533.1579584274849,\n y: 1188.5333575485345,\n },\n {\n x: 224.00199723069687,\n y: 1188.5333575485345,\n },\n ],\n boundingBox: {\n left: 224.00199723069687,\n top: 1168.0604785546325,\n right: 533.1579584274849,\n bottom: 1188.5333575485345,\n },\n },\n {\n id: "block_9_UvLm1J",\n type: "text",\n content:\n "To evaluate if the Transformer can generalize to other tasks we performed experiments on English constituency parsing. This task presents specific challenges: the output is subject to strong structural constraints and is significantly longer than the input. Furthermore, RNN sequence-to-sequence models have not been able to attain state-of-the-art results in small-data regimes [37].",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.0787388599702,\n y: 1212.099580979885,\n },\n {\n x: 1049.9080518736457,\n y: 1212.099580979885,\n },\n {\n x: 1049.9080518736457,\n y: 1300.6617424183323,\n },\n {\n x: 223.0787388599702,\n y: 1300.6617424183323,\n },\n ],\n boundingBox: {\n left: 223.0787388599702,\n top: 1212.099580979885,\n right: 1049.9080518736457,\n bottom: 1300.6617424183323,\n },\n },\n {\n id: "block_9_nmNLPf",\n type: "text",\n content:\n "We trained a 4-layer transformer with dmodel = 1024 on the Wall Street Journal (WSJ) portion of the Penn Treebank [25], about 40K training sentences. We also trained it in a semi-supervised setting, using the larger high-confidence and BerkleyParser corpora from with approximately 17M sentences [37]. We used a vocabulary of 16K tokens for the WSJ only setting and a vocabulary of 32K tokens for the semi-supervised setting.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 223.08401678600453,\n y: 1314.1105266370273,\n },\n {\n x: 1051.1732393807738,\n y: 1314.1105266370273,\n },\n {\n x: 1051.1732393807738,\n y: 1425.9921031177494,\n },\n {\n x: 223.08401678600453,\n y: 1425.9921031177494,\n },\n ],\n boundingBox: {\n left: 223.08401678600453,\n top: 1314.1105266370273,\n right: 1051.1732393807738,\n bottom: 1425.9921031177494,\n },\n },\n {\n id: "block_9_kQhH3x",\n type: "text",\n content:\n "We performed only a small number of experiments to select the dropout, both attention and residual (section 5.4), learning rates and beam size on the Section 22 development set, all other parameters remained unchanged from the English-to-German base translation model. During inference, we",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.1762739863709,\n y: 1439.0945411051127,\n },\n {\n x: 1050.7557388639798,\n y: 1439.0945411051127,\n },\n {\n x: 1050.7557388639798,\n y: 1505.8386894168711,\n },\n {\n x: 223.1762739863709,\n y: 1505.8386894168711,\n },\n ],\n boundingBox: {\n left: 223.1762739863709,\n top: 1439.0945411051127,\n right: 1050.7557388639798,\n bottom: 1505.8386894168711,\n },\n },\n {\n id: "block_9_C4QuNg",\n type: "page_number",\n content: "9",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 631.6446262554531,\n y: 1547.2787271370566,\n },\n {\n x: 642.3550765879834,\n y: 1547.2787271370566,\n },\n {\n x: 642.3550765879834,\n y: 1562.906831325445,\n },\n {\n x: 631.6446262554531,\n y: 1562.906831325445,\n },\n ],\n boundingBox: {\n left: 631.6446262554531,\n top: 1547.2787271370566,\n right: 642.3550765879834,\n bottom: 1562.906831325445,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_10_Whfo1k",\n type: "text",\n content:\n "Table 4: The Transformer generalizes well to English constituency parsing (Results are on Section 23 of WSJ)",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.988,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.60232911492787,\n y: 147.913837353986,\n },\n {\n x: 1049.0453121435903,\n y: 147.913837353986,\n },\n {\n x: 1049.0453121435903,\n y: 190.50408882485297,\n },\n {\n x: 222.60232911492787,\n y: 190.50408882485297,\n },\n ],\n boundingBox: {\n left: 222.60232911492787,\n top: 147.913837353986,\n right: 1049.0453121435903,\n bottom: 190.50408882485297,\n },\n },\n {\n id: "block_10_Oq0boE",\n type: "table",\n content:\n "| Parser | Training | WSJ 23 F1 |\\n| --- | --- | --- |\\n| Vinyals & Kaiser el al. (2014) [37] | WSJ only, discriminative | 88.3 |\\n| Petrov et al. (2006) [29] | WSJ only, discriminative | 90.4 |\\n| Zhu et al. (2013) [40] | WSJ only, discriminative | 90.4 |\\n| Dyer et al. (2016) [8] | WSJ only, discriminative | 91.7 |\\n| Transformer (4 layers) | WSJ only, discriminative | 91.3 |\\n| Zhu et al. (2013) [40] | semi-supervised | 91.3 |\\n| Huang & Harper (2009) [14] | semi-supervised | 91.3 |\\n| McClosky et al. (2006) [26] | semi-supervised | 92.1 |\\n| Vinyals & Kaiser el al. (2014) [37] | semi-supervised | 92.1 |\\n| Transformer (4 layers) | semi-supervised | 92.7 |\\n| Luong et al. (2015) [23] | multi-task | 93.0 |\\n| Dyer et al. (2016) [8] | generative | 93.3 |",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.926,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 300.48226962124346,\n y: 193.81453893417702,\n },\n {\n x: 974.1206315312072,\n y: 193.81453893417702,\n },\n {\n x: 974.1206315312072,\n y: 493.68785631567016,\n },\n {\n x: 300.48226962124346,\n y: 493.68785631567016,\n },\n ],\n boundingBox: {\n left: 300.48226962124346,\n top: 193.81453893417702,\n right: 974.1206315312072,\n bottom: 493.68785631567016,\n },\n },\n {\n id: "block_10_wSUPzw",\n type: "text",\n content:\n "increased the maximum output length to input length + 300. We used a beam size of 21 and & = 0.3 for both WSJ only and the semi-supervised setting.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.117,\n avgOcrConfidence: 0.964,\n },\n polygon: [\n {\n x: 223.84354111051908,\n y: 546.3992524398001,\n },\n {\n x: 1049.2353174808252,\n y: 546.3992524398001,\n },\n {\n x: 1049.2353174808252,\n y: 589.787902057619,\n },\n {\n x: 223.84354111051908,\n y: 589.787902057619,\n },\n ],\n boundingBox: {\n left: 223.84354111051908,\n top: 546.3992524398001,\n right: 1049.2353174808252,\n bottom: 589.787902057619,\n },\n },\n {\n id: "block_10_KdYXbX",\n type: "text",\n content:\n "Our results in Table 4 show that despite the lack of task-specific tuning our model performs sur- prisingly well, yielding better results than all previously reported models with the exception of the Recurrent Neural Network Grammar [8].",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.917,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.34470740548016,\n y: 603.5821801379211,\n },\n {\n x: 1052.1757139776746,\n y: 603.5821801379211,\n },\n {\n x: 1052.1757139776746,\n y: 667.7562916691143,\n },\n {\n x: 224.34470740548016,\n y: 667.7562916691143,\n },\n ],\n boundingBox: {\n left: 224.34470740548016,\n top: 603.5821801379211,\n right: 1052.1757139776746,\n bottom: 667.7562916691143,\n },\n },\n {\n id: "block_10_spL6f1",\n type: "text",\n content:\n "In contrast to RNN sequence-to-sequence models [37], the Transformer outperforms the Berkeley- Parser [29] even when training only on the WSJ training set of 40K sentences.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.907,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.93137242672216,\n y: 683.4819921909419,\n },\n {\n x: 1052.021589070341,\n y: 683.4819921909419,\n },\n {\n x: 1052.021589070341,\n y: 725.8283830513632,\n },\n {\n x: 223.93137242672216,\n y: 725.8283830513632,\n },\n ],\n boundingBox: {\n left: 223.93137242672216,\n top: 683.4819921909419,\n right: 1052.021589070341,\n bottom: 725.8283830513632,\n },\n },\n {\n id: "block_10_FpxS4M",\n type: "section_heading",\n content: "### 7 Conclusion",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.87968188654767,\n y: 760.911873552136,\n },\n {\n x: 380.37754949862074,\n y: 760.911873552136,\n },\n {\n x: 380.37754949862074,\n y: 780.8896204439321,\n },\n {\n x: 223.87968188654767,\n y: 780.8896204439321,\n },\n ],\n boundingBox: {\n left: 223.87968188654767,\n top: 760.911873552136,\n right: 380.37754949862074,\n bottom: 780.8896204439321,\n },\n },\n {\n id: "block_10_06Cxhy",\n type: "text",\n content:\n "In this work, we presented the Transformer, the first sequence transduction model based entirely on attention, replacing the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.7800876589587,\n y: 811.1846398948727,\n },\n {\n x: 1049.4503160462762,\n y: 811.1846398948727,\n },\n {\n x: 1049.4503160462762,\n y: 872.951422555106,\n },\n {\n x: 223.7800876589587,\n y: 872.951422555106,\n },\n ],\n boundingBox: {\n left: 223.7800876589587,\n top: 811.1846398948727,\n right: 1049.4503160462762,\n bottom: 872.951422555106,\n },\n },\n {\n id: "block_10_4PqBx5",\n type: "text",\n content:\n "For translation tasks, the Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers. On both WMT 2014 English-to-German and WMT 2014 English-to-French translation tasks, we achieve a new state of the art. In the former task our best model outperforms even all previously reported ensembles.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.91187013500797,\n y: 890.9364237390963,\n },\n {\n x: 1049.8108244290318,\n y: 890.9364237390963,\n },\n {\n x: 1049.8108244290318,\n y: 980.2941302536126,\n },\n {\n x: 223.91187013500797,\n y: 980.2941302536126,\n },\n ],\n boundingBox: {\n left: 223.91187013500797,\n top: 890.9364237390963,\n right: 1049.8108244290318,\n bottom: 980.2941302536126,\n },\n },\n {\n id: "block_10_9Aa2OZ",\n type: "text",\n content:\n "We are excited about the future of attention-based models and plan to apply them to other tasks. We plan to extend the Transformer to problems involving input and output modalities other than text and to investigate local, restricted attention mechanisms to efficiently handle large inputs and outputs such as images, audio and video. Making generation less sequential is another research goals of ours.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.985,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.4691397117002,\n y: 993.4156992059005,\n },\n {\n x: 1051.09778633953,\n y: 993.4156992059005,\n },\n {\n x: 1051.09778633953,\n y: 1081.8706514745727,\n },\n {\n x: 223.4691397117002,\n y: 1081.8706514745727,\n },\n ],\n boundingBox: {\n left: 223.4691397117002,\n top: 993.4156992059005,\n right: 1051.09778633953,\n bottom: 1081.8706514745727,\n },\n },\n {\n id: "block_10_eXUU9v",\n type: "text",\n content:\n "The code we used to train and evaluate our models is available at https://github.com/ tensorflow/tensor2tensor.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.94,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 222.4288912585182,\n y: 1095.2490678371344,\n },\n {\n x: 1050.6089983195284,\n y: 1095.2490678371344,\n },\n {\n x: 1050.6089983195284,\n y: 1136.225321719521,\n },\n {\n x: 222.4288912585182,\n y: 1136.225321719521,\n },\n ],\n boundingBox: {\n left: 222.4288912585182,\n top: 1095.2490678371344,\n right: 1050.6089983195284,\n bottom: 1136.225321719521,\n },\n },\n {\n id: "block_10_HbnFiy",\n type: "text",\n content:\n "Acknowledgements We are grateful to Nal Kalchbrenner and Stephan Gouws for their fruitful comments, corrections and inspiration.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.74068072242457,\n y: 1165.530171673997,\n },\n {\n x: 1049.9162882783987,\n y: 1165.530171673997,\n },\n {\n x: 1049.9162882783987,\n y: 1209.6124608319503,\n },\n {\n x: 223.74068072242457,\n y: 1209.6124608319503,\n },\n ],\n boundingBox: {\n left: 223.74068072242457,\n top: 1165.530171673997,\n right: 1049.9162882783987,\n bottom: 1209.6124608319503,\n },\n },\n {\n id: "block_10_FqHFgA",\n type: "section_heading",\n content: "### References",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.3401158465086,\n y: 1243.4205694557131,\n },\n {\n x: 340.41243086766156,\n y: 1243.4205694557131,\n },\n {\n x: 340.41243086766156,\n y: 1263.1433630921786,\n },\n {\n x: 224.3401158465086,\n y: 1263.1433630921786,\n },\n ],\n boundingBox: {\n left: 224.3401158465086,\n top: 1243.4205694557131,\n right: 340.41243086766156,\n bottom: 1263.1433630921786,\n },\n },\n {\n id: "block_10_PnBCYC",\n type: "text",\n content:\n "[1] Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint arXiv: 1607.06450, 2016.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 234.62492392881074,\n y: 1281.5349446346884,\n },\n {\n x: 1049.520940850251,\n y: 1281.5349446346884,\n },\n {\n x: 1049.520940850251,\n y: 1323.6168167573169,\n },\n {\n x: 234.62492392881074,\n y: 1323.6168167573169,\n },\n ],\n boundingBox: {\n left: 234.62492392881074,\n top: 1281.5349446346884,\n right: 1049.520940850251,\n bottom: 1323.6168167573169,\n },\n },\n {\n id: "block_10_sUAYRJ",\n type: "text",\n content:\n "[2] Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly learning to align and translate. CoRR, abs/1409.0473, 2014.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 233.7351792050104,\n y: 1342.1247941210754,\n },\n {\n x: 1048.5688313950586,\n y: 1342.1247941210754,\n },\n {\n x: 1048.5688313950586,\n y: 1385.6842018070079,\n },\n {\n x: 233.7351792050104,\n y: 1385.6842018070079,\n },\n ],\n boundingBox: {\n left: 233.7351792050104,\n top: 1342.1247941210754,\n right: 1048.5688313950586,\n bottom: 1385.6842018070079,\n },\n },\n {\n id: "block_10_cYNyCb",\n type: "text",\n content:\n "[3] Denny Britz, Anna Goldie, Minh-Thang Luong, and Quoc V. Le. Massive exploration of neural machine translation architectures. CoRR, abs/1703.03906, 2017.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.914,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 234.47555625525703,\n y: 1401.96474766552,\n },\n {\n x: 1050.0915248898693,\n y: 1401.96474766552,\n },\n {\n x: 1050.0915248898693,\n y: 1443.4021335687853,\n },\n {\n x: 234.47555625525703,\n y: 1443.4021335687853,\n },\n ],\n boundingBox: {\n left: 234.47555625525703,\n top: 1401.96474766552,\n right: 1050.0915248898693,\n bottom: 1443.4021335687853,\n },\n },\n {\n id: "block_10_akeHB3",\n type: "text",\n content:\n "[4] Jianpeng Cheng, Li Dong, and Mirella Lapata. Long short-term memory-networks for machine reading. arXiv preprint arXiv: 1601.06733, 2016.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.91,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 235.1935672063897,\n y: 1461.8473196961825,\n },\n {\n x: 1049.3358584216041,\n y: 1461.8473196961825,\n },\n {\n x: 1049.3358584216041,\n y: 1505.7106445427228,\n },\n {\n x: 235.1935672063897,\n y: 1505.7106445427228,\n },\n ],\n boundingBox: {\n left: 235.1935672063897,\n top: 1461.8473196961825,\n right: 1049.3358584216041,\n bottom: 1505.7106445427228,\n },\n },\n {\n id: "block_10_sJYSgt",\n type: "page_number",\n content: "10",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.999,\n avgOcrConfidence: 0.999,\n },\n polygon: [\n {\n x: 628.4902252420022,\n y: 1547.7831405983832,\n },\n {\n x: 647.7796484954166,\n y: 1547.7831405983832,\n },\n {\n x: 647.7796484954166,\n y: 1563.3856736950409,\n },\n {\n x: 628.4902252420022,\n y: 1563.3856736950409,\n },\n ],\n boundingBox: {\n left: 628.4902252420022,\n top: 1547.7831405983832,\n right: 647.7796484954166,\n bottom: 1563.3856736950409,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_11_VBbBwR",\n type: "text",\n content:\n "[5] Kyunghyun Cho, Bart van Merrienboer, Caglar Gulcehre, Fethi Bougares, Holger Schwenk, and Yoshua Bengio. Learning phrase representations using rnn encoder-decoder for statistical machine translation. CoRR, abs/1406.1078, 2014.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.932,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 234.95565818174043,\n y: 155.04768656967278,\n },\n {\n x: 1051.617910566121,\n y: 155.04768656967278,\n },\n {\n x: 1051.617910566121,\n y: 219.22101676195186,\n },\n {\n x: 234.95565818174043,\n y: 219.22101676195186,\n },\n ],\n boundingBox: {\n left: 234.95565818174043,\n top: 155.04768656967278,\n right: 1051.617910566121,\n bottom: 219.22101676195186,\n },\n },\n {\n id: "block_11_fZULb0",\n type: "text",\n content:\n "[6] Francois Chollet. Xception: Deep learning with depthwise separable convolutions. arXiv preprint arXiv: 1610.02357, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.916,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 234.37082610861228,\n y: 242.1581676597882,\n },\n {\n x: 1050.1136779785156,\n y: 242.1581676597882,\n },\n {\n x: 1050.1136779785156,\n y: 284.96119192309845,\n },\n {\n x: 234.37082610861228,\n y: 284.96119192309845,\n },\n ],\n boundingBox: {\n left: 234.37082610861228,\n top: 242.1581676597882,\n right: 1050.1136779785156,\n bottom: 284.96119192309845,\n },\n },\n {\n id: "block_11_KQxaZG",\n type: "text",\n content:\n "[7] Junyoung Chung, \\u00c7aglar G\\u00fcl\\u00e7ehre, Kyunghyun Cho, and Yoshua Bengio. Empirical evaluation of gated recurrent neural networks on sequence modeling. CoRR, abs/1412.3555, 2014.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.937,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 234.59709056102446,\n y: 305.8525607747243,\n },\n {\n x: 1050.252182118214,\n y: 305.8525607747243,\n },\n {\n x: 1050.252182118214,\n y: 348.70033444856347,\n },\n {\n x: 234.59709056102446,\n y: 348.70033444856347,\n },\n ],\n boundingBox: {\n left: 234.59709056102446,\n top: 305.8525607747243,\n right: 1050.252182118214,\n bottom: 348.70033444856347,\n },\n },\n {\n id: "block_11_lSxX1m",\n type: "text",\n content:\n "[8] Chris Dyer, Adhiguna Kuncoro, Miguel Ballesteros, and Noah A. Smith. Recurrent neural network grammars. In Proc. of NAACL, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.92,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 234.54393261540545,\n y: 369.88837531814,\n },\n {\n x: 1049.7648141679972,\n y: 369.88837531814,\n },\n {\n x: 1049.7648141679972,\n y: 412.63161531606113,\n },\n {\n x: 234.54393261540545,\n y: 412.63161531606113,\n },\n ],\n boundingBox: {\n left: 234.54393261540545,\n top: 369.88837531814,\n right: 1049.7648141679972,\n bottom: 412.63161531606113,\n },\n },\n {\n id: "block_11_3YLXoz",\n type: "text",\n content:\n "[9] Jonas Gehring, Michael Auli, David Grangier, Denis Yarats, and Yann N. Dauphin. Convolu- tional sequence to sequence learning. arXiv preprint arXiv: 1705.03122v2, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.927,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 233.81299902922916,\n y: 434.3302966813395,\n },\n {\n x: 1052.8067929901345,\n y: 434.3302966813395,\n },\n {\n x: 1052.8067929901345,\n y: 476.945989020785,\n },\n {\n x: 233.81299902922916,\n y: 476.945989020785,\n },\n ],\n boundingBox: {\n left: 233.81299902922916,\n top: 434.3302966813395,\n right: 1052.8067929901345,\n bottom: 476.945989020785,\n },\n },\n {\n id: "block_11_OkxRaO",\n type: "text",\n content:\n "[10] Alex Graves. Generating sequences with recurrent neural networks. arXiv preprint arXiv: 1308.0850, 2013.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.904,\n avgOcrConfidence: 0.986,\n },\n polygon: [\n {\n x: 224.38643378932983,\n y: 498.1091927836712,\n },\n {\n x: 1050.5877919440723,\n y: 498.1091927836712,\n },\n {\n x: 1050.5877919440723,\n y: 539.0395607625632,\n },\n {\n x: 224.38643378932983,\n y: 539.0395607625632,\n },\n ],\n boundingBox: {\n left: 224.38643378932983,\n top: 498.1091927836712,\n right: 1050.5877919440723,\n bottom: 539.0395607625632,\n },\n },\n {\n id: "block_11_RVnHcs",\n type: "text",\n content:\n "[11] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for im- age recognition. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 770-778, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.919,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.3475475450502,\n y: 561.9494121522832,\n },\n {\n x: 1053.1976908662893,\n y: 561.9494121522832,\n },\n {\n x: 1053.1976908662893,\n y: 627.2271530610278,\n },\n {\n x: 224.3475475450502,\n y: 627.2271530610278,\n },\n ],\n boundingBox: {\n left: 224.3475475450502,\n top: 561.9494121522832,\n right: 1053.1976908662893,\n bottom: 627.2271530610278,\n },\n },\n {\n id: "block_11_s96TQd",\n type: "text",\n content:\n "[12] Sepp Hochreiter, Yoshua Bengio, Paolo Frasconi, and J\\u00fcrgen Schmidhuber. Gradient flow in recurrent nets: the difficulty of learning long-term dependencies, 2001.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.892,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 224.27874516396628,\n y: 647.9830188034173,\n },\n {\n x: 1048.8635432111087,\n y: 647.9830188034173,\n },\n {\n x: 1048.8635432111087,\n y: 692.1669293740639,\n },\n {\n x: 224.27874516396628,\n y: 692.1669293740639,\n },\n ],\n boundingBox: {\n left: 224.27874516396628,\n top: 647.9830188034173,\n right: 1048.8635432111087,\n bottom: 692.1669293740639,\n },\n },\n {\n id: "block_11_bKrlBK",\n type: "text",\n content:\n "[13] Sepp Hochreiter and J\\u00fcrgen Schmidhuber. Long short-term memory. Neural computation, 9(8):1735-1780, 1997.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.903,\n avgOcrConfidence: 0.984,\n },\n polygon: [\n {\n x: 224.36335765532334,\n y: 712.3709330738038,\n },\n {\n x: 1051.7104044447851,\n y: 712.3709330738038,\n },\n {\n x: 1051.7104044447851,\n y: 754.2910917181719,\n },\n {\n x: 224.36335765532334,\n y: 754.2910917181719,\n },\n ],\n boundingBox: {\n left: 224.36335765532334,\n top: 712.3709330738038,\n right: 1051.7104044447851,\n bottom: 754.2910917181719,\n },\n },\n {\n id: "block_11_c3sQ7S",\n type: "text",\n content:\n "[14] Zhongqiang Huang and Mary Harper. Self-training PCFG grammars with latent annotations across languages. In Proceedings of the 2009 Conference on Empirical Methods in Natural Language Processing, pages 832-841. ACL, August 2009.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.70277800177138,\n y: 777.0990849258308,\n },\n {\n x: 1050.1772024335653,\n y: 777.0990849258308,\n },\n {\n x: 1050.1772024335653,\n y: 842.7015786995565,\n },\n {\n x: 224.70277800177138,\n y: 842.7015786995565,\n },\n ],\n boundingBox: {\n left: 224.70277800177138,\n top: 777.0990849258308,\n right: 1050.1772024335653,\n bottom: 842.7015786995565,\n },\n },\n {\n id: "block_11_HmSxMA",\n type: "text",\n content:\n "[15] Rafal Jozefowicz, Oriol Vinyals, Mike Schuster, Noam Shazeer, and Yonghui Wu. Exploring the limits of language modeling. arXiv preprint arXiv: 1602.02410, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.906,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 223.96287430811972,\n y: 863.015632801486,\n },\n {\n x: 1049.822942357864,\n y: 863.015632801486,\n },\n {\n x: 1049.822942357864,\n y: 907.0369301702743,\n },\n {\n x: 223.96287430811972,\n y: 907.0369301702743,\n },\n ],\n boundingBox: {\n left: 223.96287430811972,\n top: 863.015632801486,\n right: 1049.822942357864,\n bottom: 907.0369301702743,\n },\n },\n {\n id: "block_11_XlCObz",\n type: "text",\n content:\n "[16] \\u0141ukasz Kaiser and Samy Bengio. Can active memory replace attention? In Advances in Neural Information Processing Systems, (NIPS), 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.902,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.17545875493627,\n y: 927.1137413655905,\n },\n {\n x: 1050.2528448174469,\n y: 927.1137413655905,\n },\n {\n x: 1050.2528448174469,\n y: 970.5487977795134,\n },\n {\n x: 224.17545875493627,\n y: 970.5487977795134,\n },\n ],\n boundingBox: {\n left: 224.17545875493627,\n top: 927.1137413655905,\n right: 1050.2528448174469,\n bottom: 970.5487977795134,\n },\n },\n {\n id: "block_11_48mMcn",\n type: "text",\n content:\n "[17] \\u0141ukasz Kaiser and Ilya Sutskever. Neural GPUs learn algorithms. In International Conference on Learning Representations (ICLR), 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.903,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 224.42198286961465,\n y: 991.1752927392946,\n },\n {\n x: 1049.7810976348653,\n y: 991.1752927392946,\n },\n {\n x: 1049.7810976348653,\n y: 1034.8329123590227,\n },\n {\n x: 224.42198286961465,\n y: 1034.8329123590227,\n },\n ],\n boundingBox: {\n left: 224.42198286961465,\n top: 991.1752927392946,\n right: 1049.7810976348653,\n bottom: 1034.8329123590227,\n },\n },\n {\n id: "block_11_lBImir",\n type: "text",\n content:\n "[18] Nal Kalchbrenner, Lasse Espeholt, Karen Simonyan, Aaron van den Oord, Alex Graves, and Ko- ray Kavukcuoglu. Neural machine translation in linear time. arXiv preprint arXiv: 1610.10099v2, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.934,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.23202486803933,\n y: 1055.1385374714557,\n },\n {\n x: 1052.4190192675069,\n y: 1055.1385374714557,\n },\n {\n x: 1052.4190192675069,\n y: 1117.975328259002,\n },\n {\n x: 224.23202486803933,\n y: 1117.975328259002,\n },\n ],\n boundingBox: {\n left: 224.23202486803933,\n top: 1055.1385374714557,\n right: 1052.4190192675069,\n bottom: 1117.975328259002,\n },\n },\n {\n id: "block_11_Y0ddKF",\n type: "text",\n content:\n "[19] Yoon Kim, Carl Denton, Luong Hoang, and Alexander M. Rush. Structured attention networks. In International Conference on Learning Representations, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.974,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.29036606837366,\n y: 1142.1438929622334,\n },\n {\n x: 1052.7023705252766,\n y: 1142.1438929622334,\n },\n {\n x: 1052.7023705252766,\n y: 1185.793178300212,\n },\n {\n x: 224.29036606837366,\n y: 1185.793178300212,\n },\n ],\n boundingBox: {\n left: 224.29036606837366,\n top: 1142.1438929622334,\n right: 1052.7023705252766,\n bottom: 1185.793178300212,\n },\n },\n {\n id: "block_11_nehypx",\n type: "text",\n content:\n "[20] Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In ICLR, 2015.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 223.92950266817192,\n y: 1205.8213097134928,\n },\n {\n x: 1052.7550077786411,\n y: 1205.8213097134928,\n },\n {\n x: 1052.7550077786411,\n y: 1227.2851158658366,\n },\n {\n x: 223.92950266817192,\n y: 1227.2851158658366,\n },\n ],\n boundingBox: {\n left: 223.92950266817192,\n top: 1205.8213097134928,\n right: 1052.7550077786411,\n bottom: 1227.2851158658366,\n },\n },\n {\n id: "block_11_af7MVz",\n type: "text",\n content:\n "[21] Oleksii Kuchaiev and Boris Ginsburg. Factorization tricks for LSTM networks. arXiv preprint arXiv: 1703.10722, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.925,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 223.78512890669552,\n y: 1247.11833873548,\n },\n {\n x: 1050.4177622551465,\n y: 1247.11833873548,\n },\n {\n x: 1050.4177622551465,\n y: 1289.109575544085,\n },\n {\n x: 223.78512890669552,\n y: 1289.109575544085,\n },\n ],\n boundingBox: {\n left: 223.78512890669552,\n top: 1247.11833873548,\n right: 1050.4177622551465,\n bottom: 1289.109575544085,\n },\n },\n {\n id: "block_11_vnPlfZ",\n type: "text",\n content:\n "[22] Zhouhan Lin, Minwei Feng, Cicero Nogueira dos Santos, Mo Yu, Bing Xiang, Bowen Zhou, and Yoshua Bengio. A structured self-attentive sentence embedding. arXiv preprint arXiv: 1703.03130, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.74063338676507,\n y: 1311.0246641116034,\n },\n {\n x: 1050.2205618976677,\n y: 1311.0246641116034,\n },\n {\n x: 1050.2205618976677,\n y: 1375.8748468958345,\n },\n {\n x: 223.74063338676507,\n y: 1375.8748468958345,\n },\n ],\n boundingBox: {\n left: 223.74063338676507,\n top: 1311.0246641116034,\n right: 1050.2205618976677,\n bottom: 1375.8748468958345,\n },\n },\n {\n id: "block_11_g0SHxO",\n type: "text",\n content:\n "[23] Minh-Thang Luong, Quoc V. Le, Ilya Sutskever, Oriol Vinyals, and Lukasz Kaiser. Multi-task sequence to sequence learning. arXiv preprint arXiv: 1511.06114, 2015.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.355428932357,\n y: 1397.7982697451025,\n },\n {\n x: 1050.4997476174015,\n y: 1397.7982697451025,\n },\n {\n x: 1050.4997476174015,\n y: 1441.9434448471643,\n },\n {\n x: 224.355428932357,\n y: 1441.9434448471643,\n },\n ],\n boundingBox: {\n left: 224.355428932357,\n top: 1397.7982697451025,\n right: 1050.4997476174015,\n bottom: 1441.9434448471643,\n },\n },\n {\n id: "block_11_gDtqYI",\n type: "text",\n content:\n "[24] Minh-Thang Luong, Hieu Pham, and Christopher D Manning. Effective approaches to attention- based neural machine translation. arXiv preprint arXiv: 1508.04025, 2015.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.927,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 224.7064228475529,\n y: 1461.612349775501,\n },\n {\n x: 1052.9802308465444,\n y: 1461.612349775501,\n },\n {\n x: 1052.9802308465444,\n y: 1506.2439438669305,\n },\n {\n x: 224.7064228475529,\n y: 1506.2439438669305,\n },\n ],\n boundingBox: {\n left: 224.7064228475529,\n top: 1461.612349775501,\n right: 1052.9802308465444,\n bottom: 1506.2439438669305,\n },\n },\n {\n id: "block_11_JWTkzE",\n type: "page_number",\n content: "11",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 629.039650241824,\n y: 1547.854550239735,\n },\n {\n x: 645.38100862155,\n y: 1547.854550239735,\n },\n {\n x: 645.38100862155,\n y: 1563.4467601919532,\n },\n {\n x: 629.039650241824,\n y: 1563.4467601919532,\n },\n ],\n boundingBox: {\n left: 629.039650241824,\n top: 1547.854550239735,\n right: 645.38100862155,\n bottom: 1563.4467601919532,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_12_TQ4Lbe",\n type: "text",\n content:\n "[25] Mitchell P Marcus, Mary Ann Marcinkiewicz, and Beatrice Santorini. Building a large annotated corpus of english: The penn treebank. Computational linguistics, 19(2):313-330, 1993.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.94512343580706,\n y: 154.85743054411464,\n },\n {\n x: 1050.2930801280222,\n y: 154.85743054411464,\n },\n {\n x: 1050.2930801280222,\n y: 198.76930494953817,\n },\n {\n x: 223.94512343580706,\n y: 198.76930494953817,\n },\n ],\n boundingBox: {\n left: 223.94512343580706,\n top: 154.85743054411464,\n right: 1050.2930801280222,\n bottom: 198.76930494953817,\n },\n },\n {\n id: "block_12_LvCkff",\n type: "text",\n content:\n "[26] David McClosky, Eugene Charniak, and Mark Johnson. Effective self-training for parsing. In Proceedings of the Human Language Technology Conference of the NAACL, Main Conference, pages 152-159. ACL, June 2006.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.907,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.21323261121762,\n y: 226.782506971431,\n },\n {\n x: 1051.9384676522582,\n y: 226.782506971431,\n },\n {\n x: 1051.9384676522582,\n y: 292.8687442406676,\n },\n {\n x: 224.21323261121762,\n y: 292.8687442406676,\n },\n ],\n boundingBox: {\n left: 224.21323261121762,\n top: 226.782506971431,\n right: 1051.9384676522582,\n bottom: 292.8687442406676,\n },\n },\n {\n id: "block_12_Rm8AFL",\n type: "text",\n content:\n "[27] Ankur Parikh, Oscar T\\u00e4ckstr\\u00f6m, Dipanjan Das, and Jakob Uszkoreit. A decomposable attention model. In Empirical Methods in Natural Language Processing, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.916,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.08847948060418,\n y: 321.2656073462694,\n },\n {\n x: 1048.8436622341185,\n y: 321.2656073462694,\n },\n {\n x: 1048.8436622341185,\n y: 364.85913349811295,\n },\n {\n x: 224.08847948060418,\n y: 364.85913349811295,\n },\n ],\n boundingBox: {\n left: 224.08847948060418,\n top: 321.2656073462694,\n right: 1048.8436622341185,\n bottom: 364.85913349811295,\n },\n },\n {\n id: "block_12_cqas9e",\n type: "text",\n content:\n "[28] Romain Paulus, Caiming Xiong, and Richard Socher. A deep reinforced model for abstractive summarization. arXiv preprint arXiv: 1705.04304, 2017.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.67392691730583,\n y: 392.7383714116606,\n },\n {\n x: 1049.3349117084142,\n y: 392.7383714116606,\n },\n {\n x: 1049.3349117084142,\n y: 435.42904860991285,\n },\n {\n x: 224.67392691730583,\n y: 435.42904860991285,\n },\n ],\n boundingBox: {\n left: 224.67392691730583,\n top: 392.7383714116606,\n right: 1049.3349117084142,\n bottom: 435.42904860991285,\n },\n },\n {\n id: "block_12_hfa5dB",\n type: "text",\n content:\n "[29] Slav Petrov, Leon Barrett, Romain Thibaux, and Dan Klein. Learning accurate, compact, and interpretable tree annotation. In Proceedings of the 21st International Conference on Computational Linguistics and 44th Annual Meeting of the ACL, pages 433-440. ACL, July 2006.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.899,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.91392923619625,\n y: 463.67279296530813,\n },\n {\n x: 1051.5214404920591,\n y: 463.67279296530813,\n },\n {\n x: 1051.5214404920591,\n y: 549.7230681799408,\n },\n {\n x: 223.91392923619625,\n y: 549.7230681799408,\n },\n ],\n boundingBox: {\n left: 223.91392923619625,\n top: 463.67279296530813,\n right: 1051.5214404920591,\n bottom: 549.7230681799408,\n },\n },\n {\n id: "block_12_H2k7w4",\n type: "text",\n content:\n "[30] Ofir Press and Lior Wolf. Using the output embedding to improve language models. arXiv preprint arXiv: 1608.05859, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.898,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 224.29183347381814,\n y: 581.8894180068396,\n },\n {\n x: 1049.7876299558764,\n y: 581.8894180068396,\n },\n {\n x: 1049.7876299558764,\n y: 624.918793785841,\n },\n {\n x: 224.29183347381814,\n y: 624.918793785841,\n },\n ],\n boundingBox: {\n left: 224.29183347381814,\n top: 581.8894180068396,\n right: 1049.7876299558764,\n bottom: 624.918793785841,\n },\n },\n {\n id: "block_12_UrZIEK",\n type: "text",\n content:\n "[31] Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words with subword units. arXiv preprint arXiv: 1508.07909, 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.925,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.35140540129947,\n y: 653.3260510666926,\n },\n {\n x: 1049.4855337769445,\n y: 653.3260510666926,\n },\n {\n x: 1049.4855337769445,\n y: 696.2955715494944,\n },\n {\n x: 224.35140540129947,\n y: 696.2955715494944,\n },\n ],\n boundingBox: {\n left: 224.35140540129947,\n top: 653.3260510666926,\n right: 1049.4855337769445,\n bottom: 696.2955715494944,\n },\n },\n {\n id: "block_12_IIwlxZ",\n type: "text",\n content:\n "[32] Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz, Andy Davis, Quoc Le, Geoffrey Hinton, and Jeff Dean. Outrageously large neural networks: The sparsely-gated mixture-of-experts layer. arXiv preprint arXiv: 1701.06538, 2017.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.88,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.15238262092979,\n y: 724.7319041087216,\n },\n {\n x: 1051.274348349467,\n y: 724.7319041087216,\n },\n {\n x: 1051.274348349467,\n y: 791.0497254966793,\n },\n {\n x: 224.15238262092979,\n y: 791.0497254966793,\n },\n ],\n boundingBox: {\n left: 224.15238262092979,\n top: 724.7319041087216,\n right: 1051.274348349467,\n bottom: 791.0497254966793,\n },\n },\n {\n id: "block_12_pGLzhM",\n type: "text",\n content:\n "[33] Nitish Srivastava, Geoffrey E Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdi- nov. Dropout: a simple way to prevent neural networks from overfitting. Journal of Machine Learning Research, 15(1):1929-1958, 2014.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.938,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.4417928431156,\n y: 819.0001126052741,\n },\n {\n x: 1053.3042907714844,\n y: 819.0001126052741,\n },\n {\n x: 1053.3042907714844,\n y: 885.2761205228649,\n },\n {\n x: 224.4417928431156,\n y: 885.2761205228649,\n },\n ],\n boundingBox: {\n left: 224.4417928431156,\n top: 819.0001126052741,\n right: 1053.3042907714844,\n bottom: 885.2761205228649,\n },\n },\n {\n id: "block_12_Bz8MfK",\n type: "text",\n content:\n "[34] Sainbayar Sukhbaatar, Arthur Szlam, Jason Weston, and Rob Fergus. End-to-end memory networks. In C. Cortes, N. D. Lawrence, D. D. Lee, M. Sugiyama, and R. Garnett, editors, Advances in Neural Information Processing Systems 28, pages 2440-2448. Curran Associates, Inc., 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.897,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.0948934624665,\n y: 913.8373252467105,\n },\n {\n x: 1051.823347328353,\n y: 913.8373252467105,\n },\n {\n x: 1051.823347328353,\n y: 1000.8878563328793,\n },\n {\n x: 224.0948934624665,\n y: 1000.8878563328793,\n },\n ],\n boundingBox: {\n left: 224.0948934624665,\n top: 913.8373252467105,\n right: 1051.823347328353,\n bottom: 1000.8878563328793,\n },\n },\n {\n id: "block_12_m0nnSr",\n type: "text",\n content:\n "[35] Ilya Sutskever, Oriol Vinyals, and Quoc VV Le. Sequence to sequence learning with neural networks. In Advances in Neural Information Processing Systems, pages 3104-3112, 2014.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.899,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.52872478178818,\n y: 1030.965426796361,\n },\n {\n x: 1050.1110271815835,\n y: 1030.965426796361,\n },\n {\n x: 1050.1110271815835,\n y: 1074.9609636579241,\n },\n {\n x: 224.52872478178818,\n y: 1074.9609636579241,\n },\n ],\n boundingBox: {\n left: 224.52872478178818,\n top: 1030.965426796361,\n right: 1050.1110271815835,\n bottom: 1074.9609636579241,\n },\n },\n {\n id: "block_12_C1nzdD",\n type: "text",\n content:\n "[36] Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, and Zbigniew Wojna. Rethinking the inception architecture for computer vision. CoRR, abs/1512.00567, 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.939,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.60145602261062,\n y: 1102.9526906981505,\n },\n {\n x: 1051.9790816481095,\n y: 1102.9526906981505,\n },\n {\n x: 1051.9790816481095,\n y: 1146.15116715969,\n },\n {\n x: 224.60145602261062,\n y: 1146.15116715969,\n },\n ],\n boundingBox: {\n left: 224.60145602261062,\n top: 1102.9526906981505,\n right: 1051.9790816481095,\n bottom: 1146.15116715969,\n },\n },\n {\n id: "block_12_smJ629",\n type: "text",\n content:\n "[37] Vinyals & Kaiser, Koo, Petrov, Sutskever, and Hinton. Grammar as a foreign language. In Advances in Neural Information Processing Systems, 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.70363004364236,\n y: 1173.716330506748,\n },\n {\n x: 1049.93891472364,\n y: 1173.716330506748,\n },\n {\n x: 1049.93891472364,\n y: 1218.0808487512115,\n },\n {\n x: 224.70363004364236,\n y: 1218.0808487512115,\n },\n ],\n boundingBox: {\n left: 224.70363004364236,\n top: 1173.716330506748,\n right: 1049.93891472364,\n bottom: 1218.0808487512115,\n },\n },\n {\n id: "block_12_oKrqzS",\n type: "text",\n content:\n "[38] Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. Google\'s neural machine translation system: Bridging the gap between human and machine translation. arXiv preprint arXiv: 1609.08144, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.935,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.222865417926,\n y: 1246.0137622804568,\n },\n {\n x: 1050.4285547855127,\n y: 1246.0137622804568,\n },\n {\n x: 1050.4285547855127,\n y: 1332.3901636224045,\n },\n {\n x: 224.222865417926,\n y: 1332.3901636224045,\n },\n ],\n boundingBox: {\n left: 224.222865417926,\n top: 1246.0137622804568,\n right: 1050.4285547855127,\n bottom: 1332.3901636224045,\n },\n },\n {\n id: "block_12_5hQUgX",\n type: "text",\n content:\n "[39] Jie Zhou, Ying Cao, Xuguang Wang, Peng Li, and Wei Xu. Deep recurrent models with fast-forward connections for neural machine translation. CoRR, abs/1606.04199, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.977,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.40534438530025,\n y: 1362.7727877394598,\n },\n {\n x: 1049.6643678985372,\n y: 1362.7727877394598,\n },\n {\n x: 1049.6643678985372,\n y: 1404.796982844073,\n },\n {\n x: 224.40534438530025,\n y: 1404.796982844073,\n },\n ],\n boundingBox: {\n left: 224.40534438530025,\n top: 1362.7727877394598,\n right: 1049.6643678985372,\n bottom: 1404.796982844073,\n },\n },\n {\n id: "block_12_7qyMnf",\n type: "text",\n content:\n "[40] Muhua Zhu, Yue Zhang, Wenliang Chen, Min Zhang, and Jingbo Zhu. Fast and accurate shift-reduce constituent parsing. In Proceedings of the 51st Annual Meeting of the ACL (Volume 1: Long Papers), pages 434-443. ACL, August 2013.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.905,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.04902520841057,\n y: 1434.5126750056904,\n },\n {\n x: 1049.9945814592124,\n y: 1434.5126750056904,\n },\n {\n x: 1049.9945814592124,\n y: 1501.148572362455,\n },\n {\n x: 224.04902520841057,\n y: 1501.148572362455,\n },\n ],\n boundingBox: {\n left: 224.04902520841057,\n top: 1434.5126750056904,\n right: 1049.9945814592124,\n bottom: 1501.148572362455,\n },\n },\n {\n id: "block_12_6o6JUd",\n type: "page_number",\n content: "12",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.998,\n avgOcrConfidence: 0.998,\n },\n polygon: [\n {\n x: 628.997000812614,\n y: 1547.789391309695,\n },\n {\n x: 647.0427269483133,\n y: 1547.789391309695,\n },\n {\n x: 647.0427269483133,\n y: 1563.398364533159,\n },\n {\n x: 628.997000812614,\n y: 1563.398364533159,\n },\n ],\n boundingBox: {\n left: 628.997000812614,\n top: 1547.789391309695,\n right: 647.0427269483133,\n bottom: 1563.398364533159,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_13_KlKk5h",\n type: "page_number",\n content: "13",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.999,\n avgOcrConfidence: 0.999,\n },\n polygon: [\n {\n x: 103.29433033878627,\n y: 628.7723457726248,\n },\n {\n x: 103.29433033878627,\n y: 646.9001519418981,\n },\n {\n x: 87.59273293860883,\n y: 646.9001519418981,\n },\n {\n x: 87.59273293860883,\n y: 628.7723457726248,\n },\n ],\n boundingBox: {\n left: 87.59273293860883,\n top: 628.7723457726248,\n right: 103.29433033878627,\n bottom: 646.9001519418981,\n },\n },\n {\n id: "block_13_PkaOm5",\n type: "text",\n content:\n "the word \'making\'. Different colors represent different heads. Best viewed in color. the verb \'making\', completing the phrase \'making ... more difficult\'. Attentions here shown only for encoder self-attention in layer 5 of 6. Many of the attention heads attend to a distant dependency of Figure 3: An example of the attention mechanism following long-distance dependencies in the",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.937,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 999.8870322148603,\n y: 224.33585563715354,\n },\n {\n x: 999.8870322148603,\n y: 1052.0067256732577,\n },\n {\n x: 911.037953656419,\n y: 1052.0067256732577,\n },\n {\n x: 911.037953656419,\n y: 224.33585563715354,\n },\n ],\n boundingBox: {\n left: 911.037953656419,\n top: 224.33585563715354,\n right: 999.8870322148603,\n bottom: 1052.0067256732577,\n },\n },\n {\n id: "block_13_xamkHQ",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nIt It is is in in this this spirit spirit that that a a majority majority of of American American governments governments have have passed passed new new laws laws since since 2009 2009 making making the the registration registration or or voting voting process process more more difficult difficult\\n\\n. . <EOS> <EOS> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad>\\n<caption>Diagram showing attention mechanism or word alignment between two identical sequences of text. The word \'making\' in the right column is highlighted in gray and acts as the target for connections from the left column. Connections originate from the words \'laws\', \'2009\', \'making\', \'more\', and \'difficult\' in the left column and point to \'making\' in the right column. The sequence of text is: \'It is in this spirit that a majority of American governments have passed new laws since 2009 making the registration or voting process more difficult. <EOS> <pad> <pad> <pad> <pad> <pad> <pad> <pad>\'</caption>\\n</figure>",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.717,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 1444.0009233001479,\n y: 252.8656019781628,\n },\n {\n x: 1444.0009233001479,\n y: 1047.5539548553688,\n },\n {\n x: 1022.9538143416097,\n y: 1047.5539548553688,\n },\n {\n x: 1022.9538143416097,\n y: 252.8656019781628,\n },\n ],\n boundingBox: {\n left: 1022.9538143416097,\n top: 252.8656019781628,\n right: 1444.0009233001479,\n bottom: 1047.5539548553688,\n },\n },\n {\n id: "block_13_5eYqPZ",\n type: "heading",\n content: "# Attention Visualizations",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 1498.6412794643775,\n y: 224.94428453654268,\n },\n {\n x: 1498.6412794643775,\n y: 480.8453803514912,\n },\n {\n x: 1479.199057528847,\n y: 480.8453803514912,\n },\n {\n x: 1479.199057528847,\n y: 224.94428453654268,\n },\n ],\n boundingBox: {\n left: 1479.199057528847,\n top: 224.94428453654268,\n right: 1498.6412794643775,\n bottom: 480.8453803514912,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_14_DaAuYi",\n type: "page_number",\n content: "14",\n metadata: {\n page: {\n number: 14,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.998,\n avgOcrConfidence: 0.998,\n },\n polygon: [\n {\n x: 103.12243577770732,\n y: 628.7327731612825,\n },\n {\n x: 103.12243577770732,\n y: 647.0026336447166,\n },\n {\n x: 87.74237117910752,\n y: 647.0026336447166,\n },\n {\n x: 87.74237117910752,\n y: 628.7327731612825,\n },\n ],\n boundingBox: {\n left: 87.74237117910752,\n top: 628.7327731612825,\n right: 103.12243577770732,\n bottom: 647.0026336447166,\n },\n },\n {\n id: "block_14_VDKMys",\n type: "text",\n content:\n "and 6. Note that the attentions are very sharp for this word. Full attentions for head 5. Bottom: Isolated attentions from just the word \'its\' for attention heads 5 Figure 4: Two attention heads, also in layer 5 of 6, apparently involved in anaphora resolution. Top:",\n metadata: {\n page: {\n number: 14,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.972,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 370.4634644357782,\n y: 224.1528559775248,\n },\n {\n x: 370.4634644357782,\n y: 1051.3102287793681,\n },\n {\n x: 303.81733864232115,\n y: 1051.3102287793681,\n },\n {\n x: 303.81733864232115,\n y: 224.1528559775248,\n },\n ],\n boundingBox: {\n left: 303.81733864232115,\n top: 224.1528559775248,\n right: 370.4634644357782,\n bottom: 1051.3102287793681,\n },\n },\n {\n id: "block_14_QRz2LE",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nThe The The The Law Law Law Law will will will will never never never never be be be be perfect perfect perfect perfect , , , , but but but but its its its its application application application application should should should should be be be be just just just just - - - - this this this this is is is is what what what what we we we we are are are are missing missing missing missing , , , , in in in in my my my my opinion opinion opinion opinion . . . . <EOS> <EOS> <EOS> <EOS> <pad> <pad> <pad> <pad>\\n<caption>Attention weight visualization diagram showing alignment between two sequences of text tokens. The diagram consists of three columns of text, with lines connecting tokens between the columns to represent attention strength. Thicker, more opaque lines indicate higher attention weights. The text sequence is: \'The\', \'Law\', \'will\', \'never\', \'be\', \'perfect\', \',\', \'but\', \'its\', \'application\', \'should\', \'be\', \'just\', \'-\', \'this\', \'is\', \'what\', \'we\', \'are\', \'missing\', \',\', \'in\', \'my\', \'opinion\', \'.\', \'<EOS>\', \'<pad>\'. Specific highlights are present: the word \'Law\' in the first column and \'its\' in the second column are highlighted with a purple/grey background, and lines connect these highlighted tokens to corresponding tokens in the third column.</caption>\\n</figure>",\n metadata: {\n page: {\n number: 14,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.379,\n avgOcrConfidence: 0.963,\n },\n polygon: [\n {\n x: 1294.7974623916741,\n y: 255.12043611846704,\n },\n {\n x: 1294.7974623916741,\n y: 1044.444475382784,\n },\n {\n x: 388.9633916410289,\n y: 1044.444475382784,\n },\n {\n x: 388.9633916410289,\n y: 255.12043611846704,\n },\n ],\n boundingBox: {\n left: 388.9633916410289,\n top: 255.12043611846704,\n right: 1294.7974623916741,\n bottom: 1044.444475382784,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_15_pV91a2",\n type: "page_number",\n content: "15",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.998,\n avgOcrConfidence: 0.998,\n },\n polygon: [\n {\n x: 103.26014084206486,\n y: 628.7008215911197,\n },\n {\n x: 103.26014084206486,\n y: 647.1549124613296,\n },\n {\n x: 87.58487219559515,\n y: 647.1549124613296,\n },\n {\n x: 87.58487219559515,\n y: 628.7008215911197,\n },\n ],\n boundingBox: {\n left: 87.58487219559515,\n top: 628.7008215911197,\n right: 103.26014084206486,\n bottom: 647.1549124613296,\n },\n },\n {\n id: "block_15_2igWoi",\n type: "text",\n content:\n "at layer 5 of 6. The heads clearly learned to perform different tasks. sentence. We give two such examples above, from two different heads from the encoder self-attention Figure 5: Many of the attention heads exhibit behaviour that seems related to the structure of the",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.976,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 394.6980404387739,\n y: 223.74716570777616,\n },\n {\n x: 394.6980404387739,\n y: 1049.736980800211,\n },\n {\n x: 328.87227315113955,\n y: 1049.736980800211,\n },\n {\n x: 328.87227315113955,\n y: 223.74716570777616,\n },\n ],\n boundingBox: {\n left: 328.87227315113955,\n top: 223.74716570777616,\n right: 394.6980404387739,\n bottom: 1049.736980800211,\n },\n },\n {\n id: "block_15_OqCqJD",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nThe The Law Law will will never never be be perfect perfect , , but but its its application application should should be be just just - - this this is is what what we we are are missing missing , , in in my my opinion opinion\\n\\n. . <EOS> <EOS> <pad> <pad>\\n<caption>Attention weight visualization showing connections between two identical sequences of text: \'The Law will never be perfect , but its application should be just - this is what we are missing , in my opinion . <EOS> <pad>\'. The diagram uses lines of varying thickness and red color intensity to indicate the strength of attention between words in the left sequence and words in the right sequence. Stronger connections are represented by thicker, more opaque red lines, while weaker connections are represented by thinner, more transparent red lines.</caption>\\n</figure>",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.651,\n avgOcrConfidence: 0.969,\n },\n polygon: [\n {\n x: 810.314180990807,\n y: 253.4944325467966,\n },\n {\n x: 810.314180990807,\n y: 1035.3522419059364,\n },\n {\n x: 421.96601087527165,\n y: 1035.3522419059364,\n },\n {\n x: 421.96601087527165,\n y: 253.4944325467966,\n },\n ],\n boundingBox: {\n left: 421.96601087527165,\n top: 253.4944325467966,\n right: 810.314180990807,\n bottom: 1035.3522419059364,\n },\n },\n {\n id: "block_15_sK8Nre",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nThe The Law Law will will never never be be perfect perfect , , but but its its application application should should be be just just - - this this is is what what we we are are missing missing , , in in my my opinion opinion\\n\\n. . <EOS> <EOS> <pad> <pad>\\n<caption>Attention weight visualization diagram showing connections between two identical sequences of text: \'The\', \'Law\', \'will\', \'never\', \'be\', \'perfect\', \',\', \'but\', \'its\', \'application\', \'should\', \'be\', \'just\', \'-\', \'this\', \'is\', \'what\', \'we\', \'are\', \'missing\', \',\', \'in\', \'my\', \'opinion\', \'.\', \'<EOS>\', \'<pad>\'. The diagram displays lines connecting tokens from the left sequence to the right sequence, where line thickness and opacity represent the strength of the attention weight. Notable high-attention connections include: \'Law\' to \'Law\', \'application\' to \'application\', \'missing\' to \'missing\', \'opinion\' to \'opinion\', and \'<pad>\' to \'<pad>\'.</caption>\\n</figure>",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.6,\n avgOcrConfidence: 0.968,\n },\n polygon: [\n {\n x: 1255.9501913113702,\n y: 254.50874105857238,\n },\n {\n x: 1255.9501913113702,\n y: 1034.3072598868043,\n },\n {\n x: 882.2701913360366,\n y: 1034.3072598868043,\n },\n {\n x: 882.2701913360366,\n y: 254.50874105857238,\n },\n ],\n boundingBox: {\n left: 882.2701913360366,\n top: 254.50874105857238,\n right: 1255.9501913113702,\n bottom: 1034.3072598868043,\n },\n },\n ],\n },\n ],\n} satisfies ParsedOcrOutput\n\nconst BLOCK_STYLES: Record<\n OcrBlockType,\n {\n label: string\n icon: React.ComponentType<React.ComponentProps<"svg">>\n overlay: string\n mutedOverlay: string\n ring: string\n badge: string\n }\n> = {\n heading: {\n label: "Heading",\n icon: Heading01Glyph,\n overlay: "border-violet-500/70 bg-violet-500/10",\n mutedOverlay: "border-violet-500/35 bg-violet-500/5",\n ring: "border-violet-500/60 bg-violet-500/5 text-violet-600",\n badge:\n "bg-violet-50 text-violet-600 dark:bg-violet-300/10 dark:text-violet-300",\n },\n paragraph: {\n label: "Paragraph",\n icon: ParagraphGlyph,\n overlay: "border-blue-500/70 bg-blue-500/10",\n mutedOverlay: "border-blue-500/35 bg-blue-500/5",\n ring: "border-blue-500/60 bg-blue-500/5 text-blue-600",\n badge: "bg-blue-50 text-blue-600 dark:bg-blue-300/10 dark:text-blue-300",\n },\n list: {\n label: "List",\n icon: LeftToRightListBulletGlyph,\n overlay: "border-emerald-500/70 bg-emerald-500/10",\n mutedOverlay: "border-emerald-500/35 bg-emerald-500/5",\n ring: "border-emerald-500/60 bg-emerald-500/5 text-emerald-600",\n badge:\n "bg-emerald-50 text-emerald-600 dark:bg-emerald-300/10 dark:text-emerald-300",\n },\n table: {\n label: "Table",\n icon: Table01Glyph,\n overlay: "border-amber-500/70 bg-amber-500/10",\n mutedOverlay: "border-amber-500/35 bg-amber-500/5",\n ring: "border-amber-500/60 bg-amber-500/5 text-amber-700",\n badge:\n "bg-amber-50 text-amber-600 dark:bg-amber-300/10 dark:text-amber-300",\n },\n figure: {\n label: "Figure",\n icon: ImageCompositionGlyph,\n overlay: "border-rose-500/70 bg-rose-500/10",\n mutedOverlay: "border-rose-500/35 bg-rose-500/5",\n ring: "border-rose-500/60 bg-rose-500/5 text-rose-600",\n badge: "bg-rose-50 text-rose-600 dark:bg-rose-300/10 dark:text-rose-300",\n },\n header: {\n label: "Header",\n icon: TextCenterlineCenterTopGlyph,\n overlay: "border-cyan-500/70 bg-cyan-500/10",\n mutedOverlay: "border-cyan-500/35 bg-cyan-500/5",\n ring: "border-cyan-500/60 bg-cyan-500/5 text-cyan-700",\n badge: "bg-cyan-50 text-cyan-600 dark:bg-cyan-300/10 dark:text-cyan-300",\n },\n footer: {\n label: "Footer",\n icon: AlignBoxBottomCenterGlyph,\n overlay: "border-slate-500/70 bg-slate-500/10",\n mutedOverlay: "border-slate-500/35 bg-slate-500/5",\n ring: "border-slate-500/60 bg-slate-500/5 text-slate-700",\n badge:\n "bg-slate-50 text-slate-600 dark:bg-slate-300/10 dark:text-slate-300",\n },\n page_number: {\n label: "Page number",\n icon: TextNumberSignGlyph,\n overlay: "border-zinc-500/70 bg-zinc-500/10",\n mutedOverlay: "border-zinc-500/35 bg-zinc-500/5",\n ring: "border-zinc-500/60 bg-zinc-500/5 text-zinc-700",\n badge: "bg-zinc-50 text-zinc-600 dark:bg-zinc-300/10 dark:text-zinc-300",\n },\n}\n\nfunction getBlockType(block: ParsedOcrBlock): OcrBlockType | undefined {\n if (block.type === "heading" || block.type === "section_heading") {\n return "heading"\n }\n\n if (block.type === "header") {\n return "header"\n }\n\n if (block.type === "footer") {\n return "footer"\n }\n\n if (block.type === "page_number") {\n return "page_number"\n }\n\n if (block.type === "figure" || block.type === "image") {\n return "figure"\n }\n\n if (block.type === "table") {\n return "table"\n }\n\n if (block.metadata.layoutClass === "List Item") {\n return "list"\n }\n\n if (block.type === "text") {\n return "paragraph"\n }\n}\n\nexport function getOcrBlocks(output: ParsedOcrOutput): OcrBlock[] {\n return output.chunks.flatMap((chunk) =>\n chunk.blocks.flatMap((block) => {\n const type = getBlockType(block)\n const { page } = block.metadata\n\n if (!type || page.width <= 0 || page.height <= 0) {\n return []\n }\n\n return {\n id: block.id,\n type,\n text: block.content,\n page: page.number,\n pageWidth: page.width,\n pageHeight: page.height,\n confidence:\n block.metadata.avgOcrConfidence ??\n block.metadata.minOcrConfidence ??\n 1,\n polygon: block.polygon,\n boundingBox: block.boundingBox,\n }\n })\n )\n}\n\nfunction getBoundingBox(block: OcrBlock): BoundingBox {\n if (block.boundingBox) {\n return block.boundingBox\n }\n\n const polygon = block.polygon ?? []\n const xValues = polygon.map((point) => point.x)\n const yValues = polygon.map((point) => point.y)\n const left = Math.min(...xValues)\n const right = Math.max(...xValues)\n const top = Math.min(...yValues)\n const bottom = Math.max(...yValues)\n\n return { left, top, right, bottom }\n}\n\nfunction getBlockCoordinateRotation(\n block: OcrBlock,\n pageSize?: { width: number; height: number }\n) {\n const blockIsLandscape = block.pageWidth > block.pageHeight\n\n if (!pageSize) return blockIsLandscape ? 1 : 0\n\n const pageIsLandscape = pageSize.width > pageSize.height\n\n if (blockIsLandscape && !pageIsLandscape) return 1\n if (!blockIsLandscape && pageIsLandscape) return 3\n\n return 0\n}\n\nfunction normalizeHighlightAreaForRotation(\n area: HighlightArea,\n rotation: number\n): HighlightArea {\n if (rotation === 1) {\n return {\n left: area.top,\n top: 100 - area.left - area.width,\n width: area.height,\n height: area.width,\n }\n }\n\n if (rotation === 3) {\n return {\n left: 100 - area.top - area.height,\n top: area.left,\n width: area.height,\n height: area.width,\n }\n }\n\n return area\n}\n\nexport function blockToHighlightArea(\n block: OcrBlock,\n pageSize?: { width: number; height: number }\n): HighlightArea {\n const { left, top, right, bottom } = getBoundingBox(block)\n\n const area = {\n left: (left / block.pageWidth) * 100,\n top: (top / block.pageHeight) * 100,\n width: ((right - left) / block.pageWidth) * 100,\n height: ((bottom - top) / block.pageHeight) * 100,\n }\n\n return normalizeHighlightAreaForRotation(\n area,\n getBlockCoordinateRotation(block, pageSize)\n )\n}\n\nexport function blockToArea(\n block: OcrBlock,\n pageSize?: { width: number; height: number }\n): React.CSSProperties {\n const area = blockToHighlightArea(block, pageSize)\n\n return {\n left: `${area.left}%`,\n top: `${area.top}%`,\n width: `${area.width}%`,\n height: `${area.height}%`,\n }\n}\n\nconst OcrBlockMarkdown = React.memo(function OcrBlockMarkdown({\n text,\n}: {\n text: string\n}) {\n const markdown = text.replace(OCR_MARKDOWN_FIGURE_CAPTION_PATTERN, (tag) =>\n tag.startsWith("</") ? "</figcaption>" : "<figcaption>"\n )\n\n return (\n <div className="space-y-1 text-sm leading-5 text-foreground/90">\n <ReactMarkdown\n rehypePlugins={OCR_MARKDOWN_REHYPE_PLUGINS}\n remarkPlugins={OCR_MARKDOWN_REMARK_PLUGINS}\n components={{\n h1: ({ node: _node, ...props }) => (\n <h1\n className="my-0 text-base leading-5 font-semibold text-foreground"\n {...props}\n />\n ),\n p: ({ node: _node, ...props }) => (\n <p className="my-0 text-[13px] leading-5" {...props} />\n ),\n ol: ({ node: _node, ...props }) => (\n <ol className="my-0 list-decimal space-y-0.5 pl-4" {...props} />\n ),\n table: ({ node: _node, ...props }) => (\n <div className="overflow-hidden rounded-md border bg-background">\n <table className="w-full border-collapse text-xs" {...props} />\n </div>\n ),\n figure: ({ node: _node, ...props }) => (\n <figure\n className="my-0 space-y-2 rounded-md border bg-muted/20 p-2 text-[13px]"\n {...props}\n />\n ),\n figcaption: ({ node: _node, ...props }) => (\n <figcaption\n className="border-t pt-2 text-xs leading-5 text-muted-foreground"\n {...props}\n />\n ),\n caption: ({ node: _node, ...props }) => (\n <figcaption\n className="block border-t pt-2 text-xs leading-5 text-muted-foreground"\n {...props}\n />\n ),\n th: ({ node: _node, ...props }) => (\n <th className="border-b bg-muted px-2 py-1 text-left" {...props} />\n ),\n td: ({ node: _node, ...props }) => (\n <td className="border-t px-2 py-1" {...props} />\n ),\n }}\n >\n {markdown}\n </ReactMarkdown>\n </div>\n )\n})\n\nconst OcrBlockButton = React.memo(function OcrBlockButton({\n block,\n isActive,\n onFocusBlock,\n}: {\n block: OcrBlock\n isActive: boolean\n onFocusBlock: (block: OcrBlock) => void\n}) {\n const style = BLOCK_STYLES[block.type]\n\n return (\n <button\n type="button"\n onMouseEnter={() => onFocusBlock(block)}\n onFocus={() => onFocusBlock(block)}\n className={cn(\n "w-full rounded-lg border bg-background p-3 text-left hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",\n isActive && style.ring\n )}\n >\n <div className="min-w-0">\n <div className="flex items-center justify-between gap-2">\n <div className="flex min-w-0 items-center gap-2">\n <div\n className={cn(\n "inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium",\n style.badge\n )}\n >\n <style.icon className="size-3.5" />\n {style.label}\n </div>\n <div className="truncate text-xs text-muted-foreground">\n {Math.round(block.confidence * 100)}%\n </div>\n </div>\n <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">\n p. {block.page}\n </div>\n </div>\n <div className="mt-2 text-sm text-foreground/90">\n <OcrBlockMarkdown text={block.text} />\n </div>\n </div>\n </button>\n )\n})\n\nexport const OcrBlockOverlay = React.memo(function OcrBlockOverlay({\n block,\n isActive,\n pageHeight,\n pageWidth,\n}: {\n block: OcrBlock\n isActive?: boolean\n pageHeight?: number\n pageWidth?: number\n}) {\n const style = BLOCK_STYLES[block.type]\n\n return (\n <div\n className={cn(\n "pointer-events-none absolute z-10 border",\n isActive ? style.overlay : style.mutedOverlay\n )}\n style={blockToArea(\n block,\n pageWidth && pageHeight\n ? { width: pageWidth, height: pageHeight }\n : undefined\n )}\n />\n )\n})\n\nexport function OcrBlocksPanel({\n activeBlockId,\n blocks,\n className,\n onBlockFocus,\n}: {\n activeBlockId?: string\n blocks: OcrBlock[]\n className?: string\n onBlockFocus?: (block: OcrBlock) => void\n}) {\n const scrollViewportRef = React.useRef<HTMLDivElement | null>(null)\n const [localActiveBlockId, setLocalActiveBlockId] = React.useState(\n activeBlockId ?? blocks[0]?.id\n )\n const firstBlock = blocks[0]\n const focusedBlockId = activeBlockId ?? localActiveBlockId\n const activeBlock =\n blocks.find((block) => block.id === focusedBlockId) ?? firstBlock\n const focusedBlockIdRef = React.useRef(focusedBlockId)\n\n React.useEffect(() => {\n focusedBlockIdRef.current = focusedBlockId\n }, [focusedBlockId])\n\n const estimateBlockSize = React.useCallback(\n (index: number) => {\n const block = blocks[index]\n return block\n ? getEstimatedOcrBlockRowHeight(block)\n : OCR_BLOCK_ROW_MIN_ESTIMATE\n },\n [blocks]\n )\n const virtualizer = useVirtualizer({\n count: blocks.length,\n estimateSize: estimateBlockSize,\n getItemKey: (index) => blocks[index]?.id ?? index,\n getScrollElement: () => scrollViewportRef.current,\n overscan: 6,\n })\n\n const focusBlock = React.useCallback(\n (block: OcrBlock) => {\n if (block.id === focusedBlockIdRef.current) return\n\n focusedBlockIdRef.current = block.id\n setLocalActiveBlockId(block.id)\n onBlockFocus?.(block)\n },\n [onBlockFocus]\n )\n\n React.useEffect(() => {\n if (!firstBlock) return\n if (\n activeBlockId ||\n blocks.some((block) => block.id === localActiveBlockId)\n ) {\n return\n }\n\n setLocalActiveBlockId(firstBlock.id)\n }, [activeBlockId, blocks, firstBlock, localActiveBlockId])\n\n return (\n <aside\n className={cn("flex h-[420px] min-h-0 flex-col bg-background", className)}\n >\n <ScrollArea\n className="min-h-0 flex-1"\n scrollFade\n viewportRef={scrollViewportRef}\n >\n {blocks.length ? (\n <div\n className="relative"\n style={{\n height: virtualizer.getTotalSize() + OCR_BLOCK_LIST_PADDING * 2,\n }}\n >\n {virtualizer.getVirtualItems().map((virtualRow) => {\n const block = blocks[virtualRow.index]\n if (!block) return null\n\n return (\n <div\n key={virtualRow.key}\n ref={virtualizer.measureElement}\n data-index={virtualRow.index}\n className="absolute top-0 right-3 left-3 pb-2 [contain:layout_paint]"\n style={{\n transform: `translateY(${\n virtualRow.start + OCR_BLOCK_LIST_PADDING\n }px)`,\n }}\n >\n <OcrBlockButton\n block={block}\n isActive={block.id === activeBlock?.id}\n onFocusBlock={focusBlock}\n />\n </div>\n )\n })}\n </div>\n ) : (\n <div className="p-3">\n <div className="rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground">\n No layout blocks found.\n </div>\n </div>\n )}\n </ScrollArea>\n </aside>\n )\n}\n\nexport function OcrBlocks() {\n return (\n <OcrBlocksPanel blocks={getOcrBlocks(ATTENTION_OCR_OUTPUT).slice(0, 12)} />\n )\n}\n'export function OcrBlocksSource() {return (diff --git a/apps/v4/components/pdf-viewer-source-code.tsx b/apps/v4/components/pdf-viewer-source-code.tsxindex 641c443..57189a3 100644--- a/apps/v4/components/pdf-viewer-source-code.tsx+++ b/apps/v4/components/pdf-viewer-source-code.tsx@@ -5,7 +5,7 @@ import { DocsSourceCodeBlock } from "@/components/docs-code-block"// Generated from components/extend/pdf-viewer.tsx - keep in sync when the// component changes.export const pdfViewerSourceCode =- '"use client"\n\nimport * as React from "react"\nimport { createPluginRegistration, refreshPages } from "@embedpdf/core"\nimport { EmbedPDF, useRegistry } from "@embedpdf/core/react"\nimport type {\n PdfDocumentObject,\n PdfEngine,\n Rect,\n Rotation,\n} from "@embedpdf/models"\nimport {\n DocumentManagerPluginPackage,\n useActiveDocument,\n useDocumentManagerCapability,\n} from "@embedpdf/plugin-document-manager/react"\nimport {\n GlobalPointerProvider,\n InteractionManagerPluginPackage,\n PagePointerProvider,\n} from "@embedpdf/plugin-interaction-manager/react"\nimport { RenderLayer, RenderPluginPackage } from "@embedpdf/plugin-render/react"\nimport { Rotate, RotatePluginPackage } from "@embedpdf/plugin-rotate/react"\nimport {\n ScrollPluginPackage,\n ScrollStrategy,\n useScroll,\n useScrollPlugin,\n type PageLayout,\n type ScrollerLayout,\n type VirtualItem,\n} from "@embedpdf/plugin-scroll/react"\nimport {\n SearchLayer,\n SearchPluginPackage,\n useSearch,\n} from "@embedpdf/plugin-search/react"\nimport {\n CopyToClipboard,\n SelectionPluginPackage,\n useSelectionCapability,\n useSelectionPlugin,\n} from "@embedpdf/plugin-selection/react"\nimport {\n ThumbImg,\n ThumbnailPluginPackage,\n useThumbnailCapability,\n useThumbnailPlugin,\n type ThumbMeta,\n} from "@embedpdf/plugin-thumbnail/react"\nimport { TilingLayer, TilingPluginPackage } from "@embedpdf/plugin-tiling/react"\nimport {\n useIsViewportGated,\n useViewportCapability,\n useViewportElement,\n useViewportRef,\n ViewportElementContext,\n ViewportPluginPackage,\n} from "@embedpdf/plugin-viewport/react"\nimport { useZoom, ZoomPluginPackage } from "@embedpdf/plugin-zoom/react"\nimport {\n ArrowLeft01Icon,\n ArrowRight01Icon,\n Download01Icon,\n MinusSignCircleIcon,\n MoreHorizontalIcon,\n PlusSignCircleIcon,\n RotateClockwiseIcon,\n Search01Icon,\n SidebarLeftIcon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { flushSync } from "react-dom"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerSidebarSkeleton,\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/extend/document-viewer-sidebar"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { Input } from "@/components/ui/input"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from "@/components/ui/popover"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport { loadSharedPdfEngine } from "@/lib/pdf-thumbnail-utils"\n\nexport type PDFViewerPageOverlayProps = {\n pageNumber: number\n pageWidth: number\n pageHeight: number\n scale: number\n rotation: number\n}\n\nexport type PDFViewerHandle = {\n scrollToPage: (pageNumber: number, options?: ScrollIntoViewOptions) => void\n scrollToPageArea: (\n pageNumber: number,\n area: { top: number; left?: number; width?: number; height?: number },\n options?: ScrollToOptions\n ) => void\n getViewportElement: () => HTMLDivElement | null\n}\n\nexport type PDFViewerScrollAreaViewportResolver = (\n container: HTMLDivElement\n) => HTMLDivElement | null\n\nexport type PDFViewerProps = {\n className?: string\n defaultZoom?: number\n fileName?: string\n resolveScrollAreaViewport?: PDFViewerScrollAreaViewportResolver\n showDownload?: boolean\n showToolbar?: boolean\n showRotateControls?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onActivePageChange?: (pageNumber: number) => void\n onDocumentLoadSuccess?: (numPages: number) => void\n onPdfUpload?: (file: File) => void\n onPagePointerDown?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerMove?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerUp?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerCancel?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n}\n\nconst DEFAULT_ZOOM = 1\nconst ZOOM_OPTIONS = [0.1, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2]\nconst PAGE_GAP = 24\nconst THUMBNAIL_PAGE_WIDTH = 92\nconst THUMBNAIL_IMAGE_PADDING = 8\nconst THUMBNAIL_WIDTH = THUMBNAIL_PAGE_WIDTH + THUMBNAIL_IMAGE_PADDING * 2\nconst THUMBNAIL_LABEL_HEIGHT = 24\nconst THUMBNAIL_GAP = 12\nconst THUMBNAIL_PANE_PADDING_Y = 16\nconst THUMBNAIL_SIDEBAR_WIDTH_CLASS = "w-40"\nconst THUMBNAIL_SIDEBAR_CLOSED_CLASS = "-ml-40"\nconst PAGE_BASE_RENDER_MAX_SCALE = 1\nconst PAGE_BASE_RENDER_DPR = 1\nconst PDF_SEARCH_DEBOUNCE_MS = 300\nconst TEXT_SELECTION_BACKGROUND = "rgba(59, 130, 246, 0.14)"\nconst THUMBNAIL_FOCUS_RING_CLASS =\n "group-focus-visible/pdf-thumbnail-sidebar:ring-2 group-focus-visible/pdf-thumbnail-sidebar:ring-ring group-focus-visible/pdf-thumbnail-sidebar:ring-offset-1 group-focus-visible/pdf-thumbnail-sidebar:ring-offset-background"\nconst DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR =\n \'[data-slot="scroll-area-viewport"]\'\n\nfunction resolveDefaultScrollAreaViewport(container: HTMLDivElement) {\n return container.querySelector<HTMLDivElement>(\n DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR\n )\n}\n\nconst PDFViewerScrollAreaResolverContext =\n React.createContext<PDFViewerScrollAreaViewportResolver>(\n resolveDefaultScrollAreaViewport\n )\n\ntype PageRotationDeltas = Map<number, Rotation>\ntype ThumbnailSelectionMode = "replace" | "toggle" | "range"\n\nfunction getPageIndexRange(from: number, to: number): Set<number> {\n const start = Math.min(from, to)\n const end = Math.max(from, to)\n const range = new Set<number>()\n\n for (let pageIndex = start; pageIndex <= end; pageIndex += 1) {\n range.add(pageIndex)\n }\n\n return range\n}\n\nfunction arePageIndexSetsEqual(left: Set<number>, right: Set<number>) {\n if (left.size !== right.size) return false\n\n for (const value of left) {\n if (!right.has(value)) return false\n }\n\n return true\n}\n\nfunction normalizeRotation(rotation: number): Rotation {\n return (((rotation % 4) + 4) % 4) as Rotation\n}\n\nfunction useSharedPdfEngine() {\n const [engine, setEngine] = React.useState<PdfEngine | null>(null)\n const [error, setError] = React.useState<Error | null>(null)\n\n React.useEffect(() => {\n let cancelled = false\n\n loadSharedPdfEngine().then(\n (loadedEngine) => {\n if (!cancelled) setEngine(loadedEngine)\n },\n (loadError: Error) => {\n if (!cancelled) setError(loadError)\n }\n )\n\n return () => {\n cancelled = true\n }\n }, [])\n\n return { engine, error }\n}\n\nfunction rotationToDegrees(rotation: Rotation) {\n return (rotation as number) * 90\n}\n\nfunction normalizeDegrees(rotation: number) {\n return ((rotation % 360) + 360) % 360\n}\n\nfunction ensurePdfExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(".pdf") ? fileName : `${fileName}.pdf`\n}\n\nfunction getPdfDownloadFileName(fileName: string | undefined, src: string) {\n if (fileName?.trim()) return ensurePdfExtension(fileName.trim())\n\n const pathname = src.split(/[?#]/)[0] ?? ""\n const rawName = pathname.split("/").pop() || "document.pdf"\n\n try {\n return ensurePdfExtension(decodeURIComponent(rawName))\n } catch {\n return ensurePdfExtension(rawName)\n }\n}\n\nfunction getRotatedPdfDownloadFileName(fileName: string) {\n return fileName.replace(/\\.pdf$/i, "-rotated.pdf")\n}\n\nfunction downloadBlob(blob: Blob, fileName: string) {\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = fileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nasync function downloadPdfWithPageRotations({\n fileName,\n pageRotationDeltas,\n src,\n}: {\n fileName: string\n pageRotationDeltas: PageRotationDeltas\n src: string\n}) {\n const response = await fetch(src)\n\n if (!response.ok) {\n throw new Error(`Failed to download PDF (${response.status})`)\n }\n\n if (pageRotationDeltas.size === 0) {\n downloadBlob(await response.blob(), fileName)\n return\n }\n\n const [{ PDFDocument, degrees }, pdfBytes] = await Promise.all([\n import("pdf-lib"),\n response.arrayBuffer(),\n ])\n const pdfDocument = await PDFDocument.load(pdfBytes)\n\n pdfDocument.getPages().forEach((page, pageIndex) => {\n const rotationDelta = pageRotationDeltas.get(pageIndex)\n\n if (!rotationDelta) return\n\n page.setRotation(\n degrees(\n normalizeDegrees(\n page.getRotation().angle + rotationToDegrees(rotationDelta)\n )\n )\n )\n })\n\n const nextPdfBytes = await pdfDocument.save()\n const nextPdfBuffer = new ArrayBuffer(nextPdfBytes.byteLength)\n new Uint8Array(nextPdfBuffer).set(nextPdfBytes)\n\n downloadBlob(\n new Blob([nextPdfBuffer], { type: "application/pdf" }),\n getRotatedPdfDownloadFileName(fileName)\n )\n}\n\nfunction getThumbnailMetaForPage({\n page,\n pageIndex,\n rotation,\n width,\n imagePadding,\n labelHeight,\n top,\n}: {\n page: PdfDocumentObject["pages"][number]\n pageIndex: number\n rotation: Rotation\n width: number\n imagePadding: number\n labelHeight: number\n top: number\n}): ThumbMeta {\n const innerWidth = Math.max(1, width - imagePadding * 2)\n const pageWidth = rotation % 2 === 1 ? page.size.height : page.size.width\n const pageHeight = rotation % 2 === 1 ? page.size.width : page.size.height\n const imageHeight = Math.round(innerWidth * (pageHeight / pageWidth))\n const wrapperHeight = imagePadding + imageHeight + imagePadding + labelHeight\n\n return {\n pageIndex,\n width: innerWidth,\n height: imageHeight,\n wrapperHeight,\n top,\n labelHeight,\n padding: imagePadding,\n }\n}\n\nfunction buildThumbnailLayout({\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n width,\n gap,\n imagePadding,\n labelHeight,\n paddingY,\n}: {\n basePageRotations: Rotation[]\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n width: number\n gap: number\n imagePadding: number\n labelHeight: number\n paddingY: number\n}) {\n if (!pdfDocument) return null\n\n let top = paddingY\n const items = pdfDocument.pages.map((page, pageIndex) => {\n const basePageRotation =\n basePageRotations[pageIndex] ?? normalizeRotation(page.rotation)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(pageIndex) ?? 0)\n )\n const meta = getThumbnailMetaForPage({\n page,\n pageIndex,\n rotation: pageRotation,\n width,\n imagePadding,\n labelHeight,\n top,\n })\n\n top += meta.wrapperHeight + gap\n return meta\n })\n\n return {\n items,\n totalHeight: items.length ? top - gap + paddingY : paddingY * 2,\n }\n}\n\nfunction getVisibleThumbnailItems({\n buffer,\n clientHeight,\n items,\n scrollTop,\n}: {\n buffer: number\n clientHeight: number\n items: ThumbMeta[]\n scrollTop: number\n}) {\n if (items.length === 0) return []\n if (clientHeight <= 0)\n return items.slice(0, Math.min(items.length, buffer * 2))\n\n const viewportBottom = scrollTop + clientHeight\n let start = items.findIndex(\n (item) => item.top + item.wrapperHeight >= scrollTop\n )\n\n if (start === -1) start = items.length - 1\n\n let end = start\n while (end < items.length && items[end].top <= viewportBottom) {\n end += 1\n }\n\n return items.slice(\n Math.max(0, start - buffer),\n Math.min(items.length, end + buffer)\n )\n}\n\nfunction PDFViewerLoadingSkeleton({\n sidebarOpen,\n sidebarInline,\n}: {\n sidebarOpen: boolean\n sidebarInline: boolean\n}) {\n return (\n <div className="absolute inset-0 z-20 flex bg-muted/30">\n {sidebarOpen ? (\n <DocumentViewerSidebarSkeleton\n className={THUMBNAIL_SIDEBAR_WIDTH_CLASS}\n inline={sidebarInline}\n />\n ) : null}\n <div className="grid min-w-0 flex-1 place-items-center">\n <Spinner className="size-4" />\n </div>\n </div>\n )\n}\n\n// Rendered while the engine or document is not ready: same frame and controls\n// as the full viewer, with document-dependent controls disabled.\nfunction PDFViewerFallbackShell({\n className,\n defaultZoom,\n errorMessage = "Unable to load the PDF preview.",\n showDownload,\n showRotateControls,\n showToolbar,\n showUpload,\n sidebarOpen,\n state,\n toolbarActions,\n onUploadFile,\n}: {\n className?: string\n defaultZoom: number\n errorMessage?: string\n showDownload: boolean\n showRotateControls: boolean\n showToolbar: boolean\n showUpload: boolean\n sidebarOpen: boolean\n state: "loading" | "error" | "empty"\n toolbarActions?: React.ReactNode\n onUploadFile?: (file: File) => void\n}) {\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n {showToolbar ? (\n <PDFViewerToolbar\n activePage={1}\n controlsDisabled\n currentZoomLevel={defaultZoom}\n numPages={0}\n searchControl={\n <ToolbarTooltip label="Search text">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search text"\n disabled\n >\n <HugeiconsIcon icon={Search01Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n }\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n onPageChange={() => undefined}\n onRotate={() => undefined}\n onToggleSidebar={() => undefined}\n onUploadFile={onUploadFile}\n onZoomChange={() => undefined}\n />\n ) : null}\n <div className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30">\n {state === "loading" ? (\n <PDFViewerLoadingSkeleton sidebarInline sidebarOpen={sidebarOpen} />\n ) : null}\n {state === "error" ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-sm text-muted-foreground">\n {errorMessage}\n </div>\n ) : null}\n {state === "empty" ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-center text-sm text-muted-foreground">\n <div className="max-w-sm space-y-3">\n <div className="font-medium text-foreground">\n Upload a PDF to preview\n </div>\n <div>\n Pass a PDF URL with the <code>src</code> prop or use the upload\n control.\n </div>\n </div>\n </div>\n ) : null}\n </div>\n </div>\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 PDFViewerFileActionsMenu({\n downloadDisabled,\n isPreparingDownload = false,\n onDownload,\n onUploadFile,\n showDownload = false,\n showUpload = false,\n}: {\n downloadDisabled?: boolean\n isPreparingDownload?: boolean\n onDownload?: () => void\n onUploadFile?: (file: File) => void\n showDownload?: boolean\n showUpload?: boolean\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n\n if (!showDownload && !showUpload) return null\n\n return (\n <>\n {showUpload && onUploadFile ? (\n <input\n ref={inputRef}\n type="file"\n accept="application/pdf,.pdf"\n className="sr-only"\n tabIndex={-1}\n onChange={(event) => {\n const nextFile = event.target.files?.[0]\n\n if (nextFile) {\n onUploadFile(nextFile)\n event.currentTarget.value = ""\n }\n }}\n />\n ) : null}\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open PDF actions"\n >\n <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-40">\n {showDownload ? (\n <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>\n {isPreparingDownload ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n )}\n Download\n </DropdownMenuItem>\n ) : null}\n {showUpload && onUploadFile ? (\n <DropdownMenuItem onClick={() => inputRef.current?.click()}>\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n </>\n )\n}\n\nfunction PDFViewerPageNumberControl({\n activePage,\n controlsDisabled,\n numPages,\n onPageChange,\n}: {\n activePage: number\n controlsDisabled: boolean\n numPages: number\n onPageChange: (pageNumber: number) => void\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n const displayPage = numPages ? activePage : 1\n const [isEditing, setIsEditing] = React.useState(false)\n const [draftPage, setDraftPage] = React.useState(() => String(displayPage))\n\n React.useEffect(() => {\n if (!isEditing) return\n\n inputRef.current?.focus()\n inputRef.current?.select()\n }, [isEditing])\n\n const applyPageDraft = React.useCallback(\n (value: string) => {\n const trimmedValue = value.trim()\n\n if (!trimmedValue) return\n\n const parsedPage = Number(trimmedValue)\n\n if (!Number.isInteger(parsedPage)) return\n\n onPageChange(Math.min(Math.max(parsedPage, 1), Math.max(numPages, 1)))\n },\n [numPages, onPageChange]\n )\n\n return (\n <div className="flex items-center text-sm whitespace-nowrap text-primary">\n <span>Page</span>\n {isEditing ? (\n <Input\n ref={inputRef}\n aria-label="Page number"\n inputMode="numeric"\n pattern="[0-9]*"\n size="sm"\n value={draftPage}\n className="mx-1 w-14 min-w-14 rounded-md [&_[data-slot=input]]:text-center"\n onBlur={() => setIsEditing(false)}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) => {\n const nextValue = event.target.value\n\n setDraftPage(nextValue)\n applyPageDraft(nextValue)\n }}\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === "Enter" || event.key === "Escape") {\n event.currentTarget.blur()\n }\n }}\n />\n ) : (\n <Button\n type="button"\n variant="ghost"\n size="sm"\n className="font-normal"\n aria-label={`Current page ${displayPage}. Edit page number`}\n disabled={controlsDisabled || !numPages}\n onClick={() => {\n setDraftPage(String(displayPage))\n setIsEditing(true)\n }}\n >\n {displayPage}\n </Button>\n )}\n <span>of {numPages || "–"}</span>\n </div>\n )\n}\n\nfunction PDFViewerSearchControl({\n documentId,\n controlsDisabled,\n}: {\n documentId: string\n controlsDisabled: boolean\n}) {\n const { state, provides } = useSearch(documentId)\n const { provides: scroll } = useScroll(documentId)\n const [searchDraft, setSearchDraft] = React.useState("")\n const [searchQuery, setSearchQuery] = React.useState("")\n const [isSearching, setIsSearching] = React.useState(false)\n const providesRef = React.useRef(provides)\n const scrollRef = React.useRef(scroll)\n const searchRequestIdRef = React.useRef(0)\n const hasActiveQuery = Boolean(searchQuery.trim())\n const resultLabel = isSearching\n ? "Searching"\n : !hasActiveQuery\n ? "No search"\n : state.total\n ? `${state.activeResultIndex + 1} / ${state.total}`\n : "No results"\n\n const scrollToResult = React.useCallback(\n (index: number) => {\n const result = state.results[index]\n\n if (!result || !scroll) return\n\n const firstRect = result.rects[0]\n\n scroll.scrollToPage({\n pageNumber: result.pageIndex + 1,\n ...(firstRect\n ? {\n pageCoordinates: {\n x: firstRect.origin.x,\n y: firstRect.origin.y,\n },\n alignY: 30,\n }\n : {}),\n behavior: "auto",\n })\n },\n [scroll, state.results]\n )\n\n React.useEffect(() => {\n providesRef.current = provides\n scrollRef.current = scroll\n }, [provides, scroll])\n\n const runSearch = React.useCallback((rawQuery: string) => {\n const query = rawQuery.trim()\n const requestId = searchRequestIdRef.current + 1\n searchRequestIdRef.current = requestId\n setSearchQuery(query)\n\n const searchProvider = providesRef.current\n const scrollProvider = scrollRef.current\n\n if (!searchProvider) {\n setIsSearching(false)\n return\n }\n\n if (!query) {\n searchProvider.stopSearch()\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n searchProvider.startSearch()\n searchProvider.searchAllPages(query).wait(\n (result) => {\n if (searchRequestIdRef.current !== requestId) return\n\n const firstResult = result.results[0]\n\n if (firstResult && scrollProvider) {\n searchProvider.goToResult(0)\n const firstRect = firstResult.rects[0]\n\n scrollProvider.scrollToPage({\n pageNumber: firstResult.pageIndex + 1,\n ...(firstRect\n ? {\n pageCoordinates: {\n x: firstRect.origin.x,\n y: firstRect.origin.y,\n },\n alignY: 30,\n }\n : {}),\n behavior: "auto",\n })\n }\n setIsSearching(false)\n },\n () => {\n if (searchRequestIdRef.current !== requestId) return\n setIsSearching(false)\n }\n )\n }, [])\n\n React.useEffect(() => {\n if (!searchDraft.trim()) return\n\n const timeoutId = window.setTimeout(() => {\n runSearch(searchDraft)\n }, PDF_SEARCH_DEBOUNCE_MS)\n\n return () => window.clearTimeout(timeoutId)\n }, [runSearch, searchDraft])\n\n const handleSearchDraftChange = React.useCallback(\n (event: React.ChangeEvent<HTMLInputElement>) => {\n const nextDraft = event.target.value\n\n setSearchDraft(nextDraft)\n\n if (nextDraft.trim()) {\n setIsSearching(true)\n return\n }\n\n searchRequestIdRef.current += 1\n setSearchQuery("")\n setIsSearching(false)\n provides?.stopSearch()\n },\n [provides]\n )\n\n const clearSearch = React.useCallback(() => {\n searchRequestIdRef.current += 1\n setSearchDraft("")\n setSearchQuery("")\n setIsSearching(false)\n provides?.stopSearch()\n }, [provides])\n\n const navigate = React.useCallback(\n (direction: 1 | -1) => {\n if (!provides || state.total === 0) return\n\n const index =\n direction === 1 ? provides.nextResult() : provides.previousResult()\n\n scrollToResult(index)\n },\n [provides, scrollToResult, state.total]\n )\n\n return (\n <Popover>\n <ToolbarTooltip label="Search text">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search text"\n disabled={controlsDisabled}\n >\n <HugeiconsIcon icon={Search01Icon} className="size-4" />\n </Button>\n </PopoverTrigger>\n </ToolbarTooltip>\n <PopoverContent align="end" className="w-72">\n <div className="space-y-3">\n <Input\n placeholder="Search text"\n value={searchDraft}\n onChange={handleSearchDraftChange}\n onKeyDown={(event) => {\n if (event.key !== "Enter") return\n\n event.preventDefault()\n if (event.shiftKey && state.total) {\n navigate(-1)\n } else if (state.total) {\n navigate(1)\n } else if (searchDraft.trim()) {\n runSearch(searchDraft)\n }\n }}\n />\n <div className="flex items-center justify-between gap-2">\n <div className="min-w-0 text-xs text-muted-foreground">\n <div className="truncate">\n {state.total ? (\n <>\n <span className="text-primary">\n {state.activeResultIndex + 1}\n </span>\n {` / ${state.total}`}\n </>\n ) : (\n resultLabel\n )}\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-1">\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Previous result"\n disabled={isSearching || state.total === 0}\n onClick={() => navigate(-1)}\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />\n </Button>\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Next result"\n disabled={isSearching || state.total === 0}\n onClick={() => navigate(1)}\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-4" />\n </Button>\n </div>\n </div>\n <div className="flex justify-end">\n <Button\n type="button"\n variant="outline"\n size="sm"\n onClick={clearSearch}\n >\n Clear\n </Button>\n </div>\n </div>\n </PopoverContent>\n </Popover>\n )\n}\n\nfunction PDFViewerToolbar({\n activePage,\n controlsDisabled,\n currentZoomLevel,\n downloadDisabled = controlsDisabled,\n isPreparingDownload = false,\n numPages,\n searchControl,\n showDownload,\n showRotateControls,\n showUpload,\n toolbarActions,\n onDownload,\n onPageChange,\n onRotate,\n onToggleSidebar,\n onUploadFile,\n onZoomChange,\n}: {\n activePage: number\n controlsDisabled: boolean\n currentZoomLevel: number\n downloadDisabled?: boolean\n isPreparingDownload?: boolean\n numPages: number\n searchControl: React.ReactNode\n showDownload: boolean\n showRotateControls: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n onDownload?: () => void\n onPageChange: (pageNumber: number) => void\n onRotate: (direction: 1 | -1) => void\n onToggleSidebar: () => void\n onUploadFile?: (file: File) => void\n onZoomChange: (zoomLevel: number) => void\n}) {\n return (\n <div className="flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2">\n <div className="flex min-w-0 flex-wrap items-center gap-2">\n <TooltipProvider>\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 </TooltipProvider>\n <PDFViewerPageNumberControl\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n numPages={numPages}\n onPageChange={onPageChange}\n />\n </div>\n <TooltipProvider>\n <div className="flex min-w-0 flex-wrap items-center justify-end gap-1">\n {showRotateControls ? (\n <>\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Rotate counterclockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate counterclockwise"\n disabled={controlsDisabled}\n onClick={() => onRotate(-1)}\n >\n <HugeiconsIcon\n icon={RotateClockwiseIcon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Rotate clockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate clockwise"\n disabled={controlsDisabled}\n onClick={() => onRotate(1)}\n >\n <HugeiconsIcon\n icon={RotateClockwiseIcon}\n className="size-4 -scale-x-100"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom out"\n disabled={\n controlsDisabled || currentZoomLevel <= ZOOM_OPTIONS[0]\n }\n onClick={() => {\n const nextZoom = [...ZOOM_OPTIONS]\n .reverse()\n .find((option) => option < currentZoomLevel)\n\n onZoomChange(nextZoom ?? ZOOM_OPTIONS[0])\n }}\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(currentZoomLevel)}\n onValueChange={(value) => onZoomChange(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger size="sm" className="w-[84px] min-w-[84px]">\n <SelectValue placeholder="Zoom">\n {Math.round(currentZoomLevel * 100)}%\n </SelectValue>\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((option) => (\n <SelectItem key={option} value={String(option)}>\n {Math.round(option * 100)}%\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 aria-label="Zoom in"\n disabled={\n controlsDisabled ||\n currentZoomLevel >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n }\n onClick={() => {\n const nextZoom = ZOOM_OPTIONS.find(\n (option) => option > currentZoomLevel\n )\n\n onZoomChange(\n nextZoom ?? ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n )\n }}\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n {searchControl}\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n {showDownload || showUpload ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <PDFViewerFileActionsMenu\n downloadDisabled={downloadDisabled}\n isPreparingDownload={isPreparingDownload}\n onDownload={onDownload}\n onUploadFile={onUploadFile}\n showDownload={showDownload}\n showUpload={showUpload}\n />\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction setPdfViewerRef<T>(ref: React.Ref<T> | undefined, value: T | null) {\n if (!ref) return\n\n if (typeof ref === "function") {\n ref(value)\n } else {\n ref.current = value\n }\n}\n\nfunction PDFViewerScrollArea({\n children,\n className,\n viewportClassName,\n viewportProps,\n viewportRef,\n}: {\n children: React.ReactNode\n className?: string\n viewportClassName?: string\n viewportProps?: React.HTMLAttributes<HTMLDivElement>\n viewportRef?: React.Ref<HTMLDivElement>\n}) {\n const resolveScrollAreaViewport = React.useContext(\n PDFViewerScrollAreaResolverContext\n )\n const containerRef = React.useRef<HTMLDivElement | null>(null)\n const { className: viewportPropsClassName, ...resolvedViewportProps } =\n viewportProps ?? {}\n\n const setViewportRef = React.useCallback(\n (viewport: HTMLDivElement | null) => {\n setPdfViewerRef(viewportRef, viewport)\n },\n [viewportRef]\n )\n\n React.useLayoutEffect(() => {\n const container = containerRef.current\n if (!container) return\n\n const viewport = resolveScrollAreaViewport(container)\n\n if (!viewport) {\n console.error(\n `PDFViewer could not resolve the scroll viewport. Add ${DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR} to your ScrollArea viewport or pass resolveScrollAreaViewport.`\n )\n return\n }\n\n setViewportRef(viewport)\n\n return () => setViewportRef(null)\n }, [resolveScrollAreaViewport, setViewportRef])\n\n return (\n <div\n ref={containerRef}\n data-slot="pdf-viewer-scroll-area"\n className={cn("size-full min-h-0", className)}\n >\n <ScrollArea className="size-full min-h-0">\n <div\n {...resolvedViewportProps}\n data-slot="pdf-viewer-scroll-content"\n className={cn(\n "min-h-full",\n viewportPropsClassName,\n viewportClassName\n )}\n >\n {children}\n </div>\n </ScrollArea>\n </div>\n )\n}\n\nfunction PDFViewerThumbnails({\n basePageRotations,\n documentId,\n activePage,\n pageCount,\n pageRotationDeltas,\n pdfDocument,\n selectedPageIndexes,\n onSelectPage,\n}: {\n basePageRotations: Rotation[]\n documentId: string\n activePage: number\n pageCount: number\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n selectedPageIndexes: Set<number>\n onSelectPage: (pageNumber: number, mode: ThumbnailSelectionMode) => void\n}) {\n const thumbnailListboxId = React.useId()\n const activeDescendantId =\n activePage > 0 ? `${thumbnailListboxId}-page-${activePage}` : undefined\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (pageCount < 1) return\n\n const currentPage = activePage > 0 ? activePage : 1\n let nextPage: number | null = null\n\n if (event.key === "ArrowDown") {\n nextPage = Math.min(pageCount, currentPage + 1)\n } else if (event.key === "ArrowUp") {\n nextPage = Math.max(1, currentPage - 1)\n } else if (event.key === "Home") {\n nextPage = 1\n } else if (event.key === "End") {\n nextPage = pageCount\n } else if (event.key === " ") {\n event.preventDefault()\n onSelectPage(currentPage, "toggle")\n return\n }\n\n if (nextPage === null) return\n\n event.preventDefault()\n onSelectPage(nextPage, event.shiftKey ? "range" : "replace")\n },\n [activePage, onSelectPage, pageCount]\n )\n\n return (\n <PDFViewerThumbnailScrollArea\n activeDescendantId={activeDescendantId}\n basePageRotations={basePageRotations}\n documentId={documentId}\n onKeyDown={handleKeyDown}\n pageRotationDeltas={pageRotationDeltas}\n pdfDocument={pdfDocument}\n >\n {(meta: ThumbMeta) => {\n const pageNumber = meta.pageIndex + 1\n const isActive = pageNumber === activePage\n const isSelected = selectedPageIndexes.has(meta.pageIndex)\n const imagePadding = meta.padding ?? 0\n const pageRotationDelta = pageRotationDeltas.get(meta.pageIndex) ?? 0\n const thumbnailImageStyle: React.CSSProperties =\n pageRotationDelta % 2 === 1\n ? {\n height: meta.width,\n transform: `rotate(${rotationToDegrees(pageRotationDelta)}deg)`,\n width: meta.height,\n }\n : {\n height: meta.height,\n transform:\n pageRotationDelta === 0\n ? undefined\n : `rotate(${rotationToDegrees(pageRotationDelta)}deg)`,\n width: meta.width,\n }\n\n return (\n <div\n key={meta.pageIndex}\n data-pdf-viewer-thumbnail={pageNumber}\n className={cn(\n "absolute right-0 left-0 flex justify-center",\n isActive && "z-10"\n )}\n style={{ top: meta.top, height: meta.wrapperHeight }}\n >\n <div\n id={`${thumbnailListboxId}-page-${pageNumber}`}\n role="option"\n data-pdf-viewer-thumbnail-option={pageNumber}\n aria-current={isActive ? "page" : undefined}\n aria-label={`Page ${pageNumber}`}\n aria-posinset={pageNumber}\n aria-selected={isSelected}\n aria-setsize={pageCount}\n data-selected={isSelected ? "" : undefined}\n className={cn(\n "flex h-full w-full cursor-default flex-col items-center justify-between rounded-md px-2 py-0 text-xs transition-shadow outline-none select-none hover:bg-sidebar-accent",\n isActive || isSelected\n ? "bg-sidebar-accent text-foreground"\n : "text-muted-foreground",\n isActive && THUMBNAIL_FOCUS_RING_CLASS\n )}\n onClick={(event) => {\n const mode = event.shiftKey\n ? "range"\n : event.metaKey || event.ctrlKey\n ? "toggle"\n : "replace"\n\n onSelectPage(pageNumber, mode)\n }}\n >\n <span\n className="mt-0 flex items-center justify-center overflow-hidden rounded-md bg-transparent"\n style={{\n width: meta.width + imagePadding * 2,\n height: meta.height + imagePadding * 2,\n padding: imagePadding,\n }}\n >\n <ThumbImg\n documentId={documentId}\n meta={meta}\n className="block rounded-sm object-contain"\n style={thumbnailImageStyle}\n />\n </span>\n <span\n className="flex items-center justify-center tabular-nums"\n style={{ height: meta.labelHeight }}\n >\n <span className="flex min-w-5 items-center justify-center px-1.5 text-center leading-5">\n {pageNumber}\n </span>\n </span>\n </div>\n </div>\n )\n }}\n </PDFViewerThumbnailScrollArea>\n )\n}\n\nfunction PDFViewerThumbnailScrollArea({\n activeDescendantId,\n basePageRotations,\n children,\n documentId,\n onKeyDown,\n pageRotationDeltas,\n pdfDocument,\n}: {\n activeDescendantId?: string\n basePageRotations: Rotation[]\n children: (meta: ThumbMeta) => React.ReactNode\n documentId: string\n onKeyDown: React.KeyboardEventHandler<HTMLDivElement>\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n}) {\n const { plugin: thumbnailPlugin } = useThumbnailPlugin()\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewportMetrics, setViewportMetrics] = React.useState({\n clientHeight: 0,\n scrollTop: 0,\n })\n const thumbnailScope = React.useMemo(\n () => thumbnailPlugin?.provides().forDocument(documentId) ?? null,\n [documentId, thumbnailPlugin]\n )\n\n const windowState = React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) => {\n if (!thumbnailScope) return () => undefined\n\n return thumbnailScope.onWindow(() => onStoreChange())\n },\n [thumbnailScope]\n ),\n React.useCallback(\n () => thumbnailScope?.getWindow() ?? null,\n [thumbnailScope]\n ),\n () => null\n )\n const hasWindowState = Boolean(windowState)\n const paddingY = thumbnailPlugin?.cfg.paddingY ?? 0\n const thumbnailLayout = React.useMemo(\n () =>\n buildThumbnailLayout({\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n width: thumbnailPlugin?.cfg.width ?? THUMBNAIL_WIDTH,\n gap: thumbnailPlugin?.cfg.gap ?? THUMBNAIL_GAP,\n imagePadding: thumbnailPlugin?.cfg.imagePadding ?? 0,\n labelHeight: thumbnailPlugin?.cfg.labelHeight ?? THUMBNAIL_LABEL_HEIGHT,\n paddingY,\n }),\n [\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n paddingY,\n thumbnailPlugin,\n ]\n )\n const effectiveWindowState = React.useMemo(() => {\n if (!thumbnailLayout) return windowState\n\n const items = getVisibleThumbnailItems({\n buffer: thumbnailPlugin?.cfg.buffer ?? 3,\n clientHeight: viewportMetrics.clientHeight,\n items: thumbnailLayout.items,\n scrollTop: viewportMetrics.scrollTop,\n })\n\n return {\n start: items[0]?.pageIndex ?? -1,\n end: items.at(-1)?.pageIndex ?? -1,\n items,\n totalHeight: thumbnailLayout.totalHeight,\n }\n }, [thumbnailLayout, thumbnailPlugin, viewportMetrics, windowState])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope) return\n\n const updateWindow = () => {\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n }\n\n viewport.addEventListener("scroll", updateWindow)\n const frame = window.requestAnimationFrame(updateWindow)\n\n return () => {\n window.cancelAnimationFrame(frame)\n viewport.removeEventListener("scroll", updateWindow)\n }\n }, [thumbnailScope])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope) return\n\n const resizeObserver = new ResizeObserver(() => {\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n })\n\n resizeObserver.observe(viewport)\n\n return () => resizeObserver.disconnect()\n }, [thumbnailScope])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope) return\n\n thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n }, [thumbnailLayout, thumbnailScope, windowState])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope || !hasWindowState) return\n\n return thumbnailScope.onScrollTo(({ top, behavior }) => {\n viewport.scrollTo({ top, behavior })\n })\n }, [hasWindowState, thumbnailScope])\n\n return (\n <PDFViewerScrollArea\n className="h-full w-full"\n viewportClassName="group/pdf-thumbnail-sidebar px-4 focus-visible:ring-0 focus-visible:ring-offset-0"\n viewportProps={{\n "aria-activedescendant": activeDescendantId,\n "aria-label": "PDF pages",\n "aria-multiselectable": true,\n onKeyDown,\n onMouseDown: (event) => {\n event.currentTarget.focus({ preventScroll: true })\n },\n role: "listbox",\n style: {\n paddingBottom: paddingY,\n paddingTop: paddingY,\n },\n tabIndex: 0,\n }}\n viewportRef={viewportRef}\n >\n <div\n className="relative"\n style={{ height: effectiveWindowState?.totalHeight ?? 0 }}\n >\n {effectiveWindowState?.items.map((meta) => children(meta))}\n </div>\n </PDFViewerScrollArea>\n )\n}\n\nfunction PDFViewerScrollAreaViewport({\n children,\n className,\n documentId,\n}: {\n children: React.ReactNode\n className?: string\n documentId: string\n}) {\n const viewportRef = useViewportRef(documentId)\n const { provides: viewport } = useViewportCapability()\n const isGated = useIsViewportGated(documentId)\n const viewportGap = viewport?.getViewportGap() ?? 0\n\n return (\n <ViewportElementContext.Provider value={viewportRef}>\n <PDFViewerScrollArea\n className={className}\n viewportClassName="relative select-none selection:bg-transparent selection:text-inherit"\n viewportProps={{\n style: {\n padding: viewportGap,\n },\n }}\n viewportRef={viewportRef}\n >\n {isGated ? null : children}\n </PDFViewerScrollArea>\n </ViewportElementContext.Provider>\n )\n}\n\n// Captures the scrollable viewport element so the imperative handle can expose\n// it.\nfunction PDFViewerViewportBridge({\n viewportElementRef,\n}: {\n viewportElementRef: React.MutableRefObject<HTMLDivElement | null>\n}) {\n const elementRef = useViewportElement()\n\n React.useEffect(() => {\n viewportElementRef.current = elementRef?.current ?? null\n })\n\n return null\n}\n\nfunction PDFViewerTextSelectionLayer({\n documentId,\n pageIndex,\n scale,\n}: {\n documentId: string\n pageIndex: number\n scale: number\n}) {\n const { plugin: selectionPlugin } = useSelectionPlugin()\n const [rects, setRects] = React.useState<Rect[]>([])\n\n React.useEffect(() => {\n if (!selectionPlugin) return\n\n return selectionPlugin.registerSelectionOnPage({\n documentId,\n pageIndex,\n onRectsChange: ({ rects: nextRects }) => {\n setRects(nextRects)\n },\n })\n }, [documentId, pageIndex, selectionPlugin])\n\n if (!rects.length) return null\n\n return (\n <>\n {rects.map((rect, index) => (\n <div\n key={`${index}-${rect.origin.x}-${rect.origin.y}`}\n className="pointer-events-none absolute"\n style={{\n background: TEXT_SELECTION_BACKGROUND,\n height: rect.size.height * scale,\n left: rect.origin.x * scale,\n top: rect.origin.y * scale,\n width: rect.size.width * scale,\n }}\n />\n ))}\n </>\n )\n}\n\nfunction PDFViewerSelectionReleaseGuard({\n documentId,\n}: {\n documentId: string\n}) {\n const { plugin: selectionPlugin } = useSelectionPlugin()\n const { provides: selection } = useSelectionCapability()\n const lastSelectionModeIdRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n if (!selection) return\n\n return selection.forDocument(documentId).onBeginSelection(({ modeId }) => {\n lastSelectionModeIdRef.current = modeId\n })\n }, [documentId, selection])\n\n React.useEffect(() => {\n if (!selection) return\n\n let cleanupFrame = 0\n const finalizeIfStillSelecting = () => {\n window.cancelAnimationFrame(cleanupFrame)\n cleanupFrame = window.requestAnimationFrame(() => {\n const selectionState = selection.getState(documentId)\n\n if (!selectionState.selecting) return\n\n if (selectionState.selection && selectionPlugin) {\n const pluginWithEndSelection = selectionPlugin as unknown as {\n endSelection?: (documentId: string, modeId: string) => void\n }\n\n pluginWithEndSelection.endSelection?.(\n documentId,\n lastSelectionModeIdRef.current ?? "pointerMode"\n )\n return\n }\n\n if (!selectionState.selection) {\n selection.clear(documentId)\n }\n })\n }\n\n window.addEventListener("pointerup", finalizeIfStillSelecting)\n window.addEventListener("pointercancel", finalizeIfStillSelecting)\n window.addEventListener("blur", finalizeIfStillSelecting)\n\n return () => {\n window.cancelAnimationFrame(cleanupFrame)\n window.removeEventListener("pointerup", finalizeIfStillSelecting)\n window.removeEventListener("pointercancel", finalizeIfStillSelecting)\n window.removeEventListener("blur", finalizeIfStillSelecting)\n }\n }, [documentId, selection, selectionPlugin])\n\n return null\n}\n\nfunction isEditableCopyTarget(target: EventTarget | null) {\n if (!(target instanceof HTMLElement)) return false\n\n if (target.isContentEditable) return true\n\n return Boolean(target.closest("input, textarea, [contenteditable=\'true\']"))\n}\n\nfunction PDFViewerSelectionCopyShortcut({\n documentId,\n}: {\n documentId: string\n}) {\n const { provides: selection } = useSelectionCapability()\n\n React.useEffect(() => {\n if (!selection) return\n\n const copySelectedPdfText = (event: Event) => {\n if (isEditableCopyTarget(event.target)) return\n if (!selection.getState(documentId).selection) return\n\n event.preventDefault()\n selection.copyToClipboard(documentId)\n }\n\n const handleKeyDown = (event: KeyboardEvent) => {\n if (event.key.toLowerCase() !== "c") return\n if (!event.metaKey && !event.ctrlKey) return\n\n copySelectedPdfText(event)\n }\n\n document.addEventListener("copy", copySelectedPdfText)\n document.addEventListener("keydown", handleKeyDown)\n\n return () => {\n document.removeEventListener("copy", copySelectedPdfText)\n document.removeEventListener("keydown", handleKeyDown)\n }\n }, [documentId, selection])\n\n return null\n}\n\nfunction isQuarterTurn(rotation: Rotation) {\n return rotation % 2 === 1\n}\n\nfunction getRotatedDimensions({\n height,\n rotation,\n width,\n}: {\n height: number\n rotation: Rotation\n width: number\n}) {\n return isQuarterTurn(rotation)\n ? { height: width, width: height }\n : { height, width }\n}\n\nfunction getRotatedPageDimensions(page: PageLayout, rotation: Rotation) {\n return getRotatedDimensions({\n height: page.height,\n rotation,\n width: page.width,\n })\n}\n\nfunction applyPageRotationDeltasToScrollerLayout({\n basePageRotations,\n layout,\n pageRotationDeltas,\n}: {\n basePageRotations: Rotation[]\n layout: ScrollerLayout\n pageRotationDeltas: PageRotationDeltas\n}): ScrollerLayout {\n if (pageRotationDeltas.size === 0) return layout\n\n let maxWidth = 0\n let maxHeight = 0\n let offset = 0\n const pageGap = layout.pageGap\n let startSpacingAdjustment = 0\n const items: VirtualItem[] = layout.items.map((item, itemIndex) => {\n let pageOffset = 0\n let itemWidth = 0\n let itemHeight = 0\n const pageLayouts = item.pageLayouts.map((page) => {\n const basePageRotation =\n basePageRotations[page.pageIndex] ?? normalizeRotation(0)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(page.pageIndex) ?? 0)\n )\n const rotatedSize = getRotatedPageDimensions(page, pageRotation)\n const oldScrollAxisSize =\n layout.strategy === ScrollStrategy.Horizontal\n ? page.rotatedWidth\n : page.rotatedHeight\n const newScrollAxisSize =\n layout.strategy === ScrollStrategy.Horizontal\n ? rotatedSize.width\n : rotatedSize.height\n\n if (\n layout.startSpacing === 0 &&\n itemIndex === 0 &&\n pageOffset === 0 &&\n newScrollAxisSize < oldScrollAxisSize\n ) {\n startSpacingAdjustment = Math.max(\n startSpacingAdjustment,\n (oldScrollAxisSize - newScrollAxisSize) / 2\n )\n }\n\n const nextPageLayout = {\n ...page,\n rotatedHeight: rotatedSize.height,\n rotatedWidth: rotatedSize.width,\n x: layout.strategy === ScrollStrategy.Horizontal ? 0 : pageOffset,\n y: layout.strategy === ScrollStrategy.Horizontal ? pageOffset : 0,\n }\n\n pageOffset +=\n (layout.strategy === ScrollStrategy.Horizontal\n ? rotatedSize.height\n : rotatedSize.width) + pageGap\n itemWidth =\n layout.strategy === ScrollStrategy.Horizontal\n ? Math.max(itemWidth, rotatedSize.width)\n : itemWidth + rotatedSize.width\n itemHeight =\n layout.strategy === ScrollStrategy.Horizontal\n ? itemHeight + rotatedSize.height\n : Math.max(itemHeight, rotatedSize.height)\n\n return nextPageLayout\n })\n\n if (pageLayouts.length > 1) {\n if (layout.strategy === ScrollStrategy.Horizontal) {\n itemHeight -= pageGap\n } else {\n itemWidth -= pageGap\n }\n }\n\n const nextItem = {\n ...item,\n height: itemHeight,\n offset,\n pageLayouts,\n width: itemWidth,\n x: layout.strategy === ScrollStrategy.Horizontal ? offset : item.x,\n y: layout.strategy === ScrollStrategy.Horizontal ? item.y : offset,\n }\n\n if (layout.strategy === ScrollStrategy.Horizontal) {\n offset += itemWidth + pageGap\n maxHeight = Math.max(maxHeight, itemHeight)\n } else {\n offset += itemHeight + pageGap\n maxWidth = Math.max(maxWidth, itemWidth)\n }\n\n return nextItem\n })\n\n if (items.length > 0) {\n offset -= pageGap\n }\n\n return {\n ...layout,\n endSpacing: layout.endSpacing,\n items,\n startSpacing: layout.startSpacing + startSpacingAdjustment,\n totalHeight:\n layout.strategy === ScrollStrategy.Horizontal\n ? maxHeight\n : layout.startSpacing +\n startSpacingAdjustment +\n offset +\n layout.endSpacing,\n totalWidth:\n layout.strategy === ScrollStrategy.Horizontal\n ? layout.startSpacing +\n startSpacingAdjustment +\n offset +\n layout.endSpacing\n : maxWidth,\n }\n}\n\nfunction PDFViewerScroller({\n documentId,\n pageRotationDeltas,\n basePageRotations,\n renderPage,\n}: {\n documentId: string\n pageRotationDeltas: PageRotationDeltas\n basePageRotations: Rotation[]\n renderPage: (props: PageLayout) => React.ReactNode\n}) {\n const { plugin: scrollPlugin } = useScrollPlugin()\n const [layoutData, setLayoutData] = React.useState<{\n docId: string | null\n layout: ScrollerLayout | null\n }>({ docId: null, layout: null })\n\n React.useEffect(() => {\n if (!scrollPlugin || !documentId) return\n let frame = 0\n\n const setCurrentLayout = () => {\n try {\n setLayoutData({\n docId: documentId,\n layout: scrollPlugin.getScrollerLayout(documentId),\n })\n } catch {\n setLayoutData({ docId: documentId, layout: null })\n }\n }\n\n const unsubscribe = scrollPlugin.onScrollerData(documentId, (layout) => {\n setLayoutData({ docId: documentId, layout })\n })\n\n frame = window.requestAnimationFrame(setCurrentLayout)\n\n return () => {\n window.cancelAnimationFrame(frame)\n unsubscribe()\n setLayoutData({ docId: null, layout: null })\n scrollPlugin.clearLayoutReady(documentId)\n }\n }, [documentId, scrollPlugin])\n\n const scrollerLayout = React.useMemo(() => {\n if (layoutData.docId !== documentId || !layoutData.layout) return null\n\n return applyPageRotationDeltasToScrollerLayout({\n basePageRotations,\n layout: layoutData.layout,\n pageRotationDeltas,\n })\n }, [basePageRotations, documentId, layoutData, pageRotationDeltas])\n\n React.useLayoutEffect(() => {\n if (!scrollPlugin || !documentId || !scrollerLayout) return\n scrollPlugin.setLayoutReady(documentId)\n }, [documentId, scrollPlugin, scrollerLayout])\n\n if (!scrollerLayout) return null\n\n return (\n <div\n style={{\n width: `${scrollerLayout.totalWidth}px`,\n height: `${scrollerLayout.totalHeight}px`,\n position: "relative",\n boxSizing: "border-box",\n margin: "0 auto",\n ...(scrollerLayout.strategy === ScrollStrategy.Horizontal && {\n display: "flex",\n flexDirection: "row",\n }),\n }}\n >\n <div\n style={\n scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n width: scrollerLayout.startSpacing,\n height: "100%",\n flexShrink: 0,\n }\n : {\n height: scrollerLayout.startSpacing,\n width: "100%",\n }\n }\n />\n <div\n style={{\n gap: scrollerLayout.pageGap,\n display: "flex",\n alignItems: "center",\n position: "relative",\n boxSizing: "border-box",\n ...(scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n flexDirection: "row",\n minHeight: "100%",\n }\n : {\n flexDirection: "column",\n minWidth: "fit-content",\n }),\n }}\n >\n {scrollerLayout.items.map((item) => (\n <div\n key={item.pageNumbers[0]}\n style={{\n display: "flex",\n justifyContent: "center",\n gap: scrollerLayout.pageGap,\n }}\n >\n {item.pageLayouts.map((layout) => (\n <div\n key={layout.pageNumber}\n style={{\n width: `${layout.rotatedWidth}px`,\n height: `${layout.rotatedHeight}px`,\n position: "relative",\n zIndex: layout.elevated ? 1 : undefined,\n }}\n >\n {renderPage(layout)}\n </div>\n ))}\n </div>\n ))}\n </div>\n <div\n style={\n scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n width: scrollerLayout.endSpacing,\n height: "100%",\n flexShrink: 0,\n }\n : {\n height: scrollerLayout.endSpacing,\n width: "100%",\n }\n }\n />\n </div>\n )\n}\n\ntype PDFViewerInnerProps = {\n viewerRef: React.ForwardedRef<PDFViewerHandle>\n pdfFile: string\n documentId: string\n document: PdfDocumentObject | null\n defaultZoom: number\n className?: string\n fileName?: string\n showDownload: boolean\n showToolbar: boolean\n showRotateControls: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onActivePageChange?: (pageNumber: number) => void\n onPdfUpload?: (file: File) => void\n onPagePointerDown?: PDFViewerProps["onPagePointerDown"]\n onPagePointerMove?: PDFViewerProps["onPagePointerMove"]\n onPagePointerUp?: PDFViewerProps["onPagePointerUp"]\n onPagePointerCancel?: PDFViewerProps["onPagePointerCancel"]\n onUploadFile: (file: File) => void\n}\n\nfunction PDFViewerInner({\n viewerRef,\n pdfFile,\n documentId,\n document: pdfDocument,\n defaultZoom,\n className,\n fileName,\n showDownload,\n showToolbar,\n showRotateControls,\n showUpload,\n toolbarActions,\n pageClassName,\n renderPageOverlay,\n onActivePageChange,\n onPdfUpload,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n onUploadFile,\n}: PDFViewerInnerProps) {\n const { registry } = useRegistry()\n const { state: scrollState, provides: scroll } = useScroll(documentId)\n const { state: zoomState, provides: zoom } = useZoom(documentId)\n const { provides: thumbnails } = useThumbnailCapability()\n const { plugin: thumbnailPlugin } = useThumbnailPlugin()\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)\n const [pageRotationDeltas, setPageRotationDeltas] =\n React.useState<PageRotationDeltas>(() => new Map())\n const [selectedPageIndexes, setSelectedPageIndexes] = React.useState<\n Set<number>\n >(() => new Set())\n const basePageRotations = React.useMemo(\n () =>\n pdfDocument?.pages.map((page) => normalizeRotation(page.rotation)) ?? [],\n [pdfDocument]\n )\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewportElementRef = React.useRef<HTMLDivElement | null>(null)\n const pageRotationDeltasRef = React.useRef(pageRotationDeltas)\n const selectedPageIndexesRef = React.useRef(selectedPageIndexes)\n const selectionAnchorPageIndexRef = React.useRef<number | null>(null)\n const suppressActivePageSelectionSyncRef = React.useRef<number | null>(null)\n const initializedSelectionDocumentRef = React.useRef<string | null>(null)\n\n const activePage = scrollState.currentPage\n const numPages = pdfDocument?.pageCount ?? 0\n const isLoading = !pdfDocument\n const controlsDisabled = !numPages\n const downloadDisabled = controlsDisabled || isPreparingDownload\n const thumbnailSidebarVisible = sidebarOpen && !isLoading\n const currentZoomLevel = zoomState.currentZoomLevel\n const alignedThumbnailSidebarDocumentRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n pageRotationDeltasRef.current = pageRotationDeltas\n }, [pageRotationDeltas])\n\n React.useEffect(() => {\n selectedPageIndexesRef.current = selectedPageIndexes\n }, [selectedPageIndexes])\n\n React.useEffect(() => {\n if (activePage > 0) onActivePageChange?.(activePage)\n }, [activePage, onActivePageChange])\n\n React.useEffect(() => {\n if (activePage < 1 || numPages < 1) return\n\n const activePageIndex = activePage - 1\n const suppressedPageIndex = suppressActivePageSelectionSyncRef.current\n\n suppressActivePageSelectionSyncRef.current = null\n\n if (suppressedPageIndex === activePageIndex) return\n\n const nextSelection = new Set([activePageIndex])\n\n selectionAnchorPageIndexRef.current = activePageIndex\n selectedPageIndexesRef.current = nextSelection\n setSelectedPageIndexes((previousSelection) =>\n arePageIndexSetsEqual(previousSelection, nextSelection)\n ? previousSelection\n : nextSelection\n )\n }, [activePage, numPages])\n\n React.useEffect(() => {\n if (\n numPages < 1 ||\n initializedSelectionDocumentRef.current === documentId\n ) {\n return\n }\n\n const initialPageIndex = Math.max(0, (activePage > 0 ? activePage : 1) - 1)\n const initialSelection = new Set([initialPageIndex])\n\n initializedSelectionDocumentRef.current = documentId\n selectionAnchorPageIndexRef.current = initialPageIndex\n selectedPageIndexesRef.current = initialSelection\n setSelectedPageIndexes(initialSelection)\n }, [activePage, documentId, numPages])\n\n React.useEffect(() => {\n if (!thumbnailSidebarVisible) {\n alignedThumbnailSidebarDocumentRef.current = null\n return\n }\n\n if (\n activePage < 1 ||\n !thumbnails ||\n alignedThumbnailSidebarDocumentRef.current === documentId\n ) {\n return\n }\n\n alignedThumbnailSidebarDocumentRef.current = documentId\n const frame = window.requestAnimationFrame(() => {\n thumbnails.forDocument(documentId).scrollToThumb(activePage - 1)\n })\n\n return () => window.cancelAnimationFrame(frame)\n }, [activePage, documentId, thumbnailSidebarVisible, thumbnails])\n\n // The zoom plugin only releases its viewport gate for mode-based zoom\n // levels (automatic/fit); with a numeric default the gate would never\n // lift, so apply the initial zoom explicitly once the document loads.\n const initialZoomDocumentRef = React.useRef<string | null>(null)\n React.useEffect(() => {\n if (!pdfDocument || !zoom) return\n if (initialZoomDocumentRef.current === documentId) return\n\n initialZoomDocumentRef.current = documentId\n zoom.requestZoom(defaultZoom)\n }, [defaultZoom, documentId, pdfDocument, zoom])\n\n const scrollToPage = React.useCallback(\n (pageNumber: number, options?: ScrollIntoViewOptions) => {\n scroll?.scrollToPage({\n pageNumber,\n behavior: options?.behavior === "smooth" ? "smooth" : "auto",\n })\n },\n [scroll]\n )\n\n const selectThumbnailPage = React.useCallback(\n (pageNumber: number, mode: ThumbnailSelectionMode) => {\n const pageIndex = pageNumber - 1\n\n if (pageIndex < 0 || pageIndex >= numPages) return\n\n suppressActivePageSelectionSyncRef.current = pageIndex\n\n setSelectedPageIndexes((previousSelection) => {\n let nextSelection: Set<number>\n\n if (mode === "range") {\n const anchorPageIndex =\n selectionAnchorPageIndexRef.current ??\n (activePage > 0 ? activePage - 1 : pageIndex)\n\n nextSelection = getPageIndexRange(anchorPageIndex, pageIndex)\n } else if (mode === "toggle") {\n nextSelection = new Set(previousSelection)\n\n if (nextSelection.has(pageIndex)) {\n nextSelection.delete(pageIndex)\n } else {\n nextSelection.add(pageIndex)\n }\n\n selectionAnchorPageIndexRef.current = pageIndex\n } else {\n nextSelection = new Set([pageIndex])\n selectionAnchorPageIndexRef.current = pageIndex\n }\n\n selectedPageIndexesRef.current = nextSelection\n return nextSelection\n })\n\n scrollToPage(pageNumber)\n },\n [activePage, numPages, scrollToPage]\n )\n\n React.useImperativeHandle(\n viewerRef,\n () => ({\n scrollToPage,\n scrollToPageArea: (pageNumber, area, options) => {\n const pageSize = pdfDocument?.pages[pageNumber - 1]?.size\n\n scroll?.scrollToPage({\n pageNumber,\n ...(pageSize\n ? {\n pageCoordinates: {\n x: ((area.left ?? 0) / 100) * pageSize.width,\n y: (area.top / 100) * pageSize.height,\n },\n alignY: 25,\n }\n : {}),\n behavior: options?.behavior === "smooth" ? "smooth" : "auto",\n })\n },\n getViewportElement: () => viewportElementRef.current,\n }),\n [pdfDocument, scroll, scrollToPage]\n )\n\n const handleDownload = React.useCallback(async () => {\n if (!pdfFile || isPreparingDownload) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadPdfWithPageRotations({\n fileName: getPdfDownloadFileName(fileName, pdfFile),\n pageRotationDeltas,\n src: pdfFile,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [fileName, isPreparingDownload, pageRotationDeltas, pdfFile])\n\n const rotateSelectedPages = React.useCallback(\n (direction: -1 | 1) => {\n if (!pdfDocument || !registry || activePage < 1) return\n\n const documentState = registry.getStore().getState().core.documents[\n documentId\n ]\n const currentDocument = documentState?.document ?? pdfDocument\n const selectedTargetPageIndexes = Array.from(\n selectedPageIndexesRef.current\n ).filter((pageIndex) => currentDocument.pages[pageIndex])\n const fallbackPageIndex = activePage - 1\n const targetPageIndexes = (\n selectedTargetPageIndexes.length\n ? selectedTargetPageIndexes\n : [fallbackPageIndex]\n )\n .filter((pageIndex) => currentDocument.pages[pageIndex])\n .sort((a, b) => a - b)\n\n if (targetPageIndexes.length === 0) return\n\n const previousDeltas = pageRotationDeltasRef.current\n const nextDeltas = new Map(previousDeltas)\n const referencePageIndex =\n activePage > 0 && currentDocument.pages[activePage - 1]\n ? activePage - 1\n : targetPageIndexes[0]\n let scrollDelta = 0\n\n for (const pageIndex of targetPageIndexes) {\n const currentPage = currentDocument.pages[pageIndex]\n if (!currentPage) continue\n\n const previousDelta = previousDeltas.get(pageIndex) ?? 0\n const nextDelta = normalizeRotation(previousDelta + direction)\n const basePageRotation =\n basePageRotations[pageIndex] ??\n normalizeRotation(currentPage.rotation)\n const previousPageRotation = normalizeRotation(\n basePageRotation + previousDelta\n )\n const nextPageRotation = normalizeRotation(basePageRotation + nextDelta)\n const previousRotatedSize = getRotatedDimensions({\n height: currentPage.size.height * currentZoomLevel,\n rotation: previousPageRotation,\n width: currentPage.size.width * currentZoomLevel,\n })\n const nextRotatedSize = getRotatedDimensions({\n height: currentPage.size.height * currentZoomLevel,\n rotation: nextPageRotation,\n width: currentPage.size.width * currentZoomLevel,\n })\n const heightDelta = nextRotatedSize.height - previousRotatedSize.height\n\n if (pageIndex < referencePageIndex) {\n scrollDelta += heightDelta\n } else if (pageIndex === referencePageIndex) {\n scrollDelta += heightDelta / 2\n }\n\n if (nextDelta) {\n nextDeltas.set(pageIndex, nextDelta)\n } else {\n nextDeltas.delete(pageIndex)\n }\n }\n\n const store = registry.getStore()\n const viewport = viewportElementRef.current\n\n pageRotationDeltasRef.current = nextDeltas\n flushSync(() => {\n setPageRotationDeltas(nextDeltas)\n store.dispatchToCore(refreshPages(documentId, targetPageIndexes))\n })\n\n if (viewport && scrollDelta !== 0) {\n viewport.scrollTop += scrollDelta\n }\n ;(\n thumbnailPlugin as {\n calculateWindowState?: (documentId: string) => void\n } | null\n )?.calculateWindowState?.(documentId)\n },\n [\n activePage,\n basePageRotations,\n currentZoomLevel,\n documentId,\n pdfDocument,\n registry,\n thumbnailPlugin,\n ]\n )\n\n const handleUpload = React.useCallback(\n (file: File) => {\n onUploadFile(file)\n onPdfUpload?.(file)\n },\n [onPdfUpload, onUploadFile]\n )\n\n const renderPage = React.useCallback(\n (page: PageLayout) => {\n const pageNumber = page.pageNumber\n const basePageRotation =\n basePageRotations[page.pageIndex] ??\n pdfDocument?.pages[page.pageIndex]?.rotation ??\n normalizeRotation(0)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(page.pageIndex) ?? 0)\n )\n\n return (\n <Rotate\n documentId={documentId}\n pageIndex={page.pageIndex}\n rotation={pageRotation}\n >\n <PagePointerProvider\n documentId={documentId}\n pageIndex={page.pageIndex}\n rotation={pageRotation}\n key={`${page.pageIndex}-${pageRotation}`}\n data-pdf-viewer-page={pageNumber}\n className={cn(\n "relative border border-transparent bg-transparent shadow-xs select-none selection:bg-transparent selection:text-inherit",\n pageClassName?.(pageNumber)\n )}\n style={{ backgroundColor: "transparent" }}\n onPointerDown={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerDown?.(event, pageNumber)\n }\n onPointerMove={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerMove?.(event, pageNumber)\n }\n onPointerUp={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerUp?.(event, pageNumber)\n }\n onPointerCancel={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerCancel?.(event, pageNumber)\n }\n >\n <div\n aria-hidden="true"\n className="pointer-events-none absolute inset-0 bg-white"\n />\n <RenderLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n scale={Math.min(currentZoomLevel, PAGE_BASE_RENDER_MAX_SCALE)}\n dpr={PAGE_BASE_RENDER_DPR}\n className="pointer-events-none absolute inset-0 h-full w-full object-fill opacity-100 blur-[0.35px] transition-none"\n />\n <TilingLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n key={`tiles-${page.pageIndex}-${pageRotation}`}\n className="pointer-events-none opacity-100 transition-none [&_img]:opacity-100 [&_img]:transition-none"\n />\n <SearchLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n className="pointer-events-none"\n highlightColor="rgba(253, 224, 71, 0.45)"\n activeHighlightColor="rgba(249, 115, 22, 0.55)"\n />\n <PDFViewerTextSelectionLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n scale={currentZoomLevel}\n />\n {renderPageOverlay?.({\n pageNumber,\n pageWidth: page.width,\n pageHeight: page.height,\n scale: currentZoomLevel,\n rotation: rotationToDegrees(pageRotation),\n })}\n </PagePointerProvider>\n </Rotate>\n )\n },\n [\n basePageRotations,\n currentZoomLevel,\n onPagePointerCancel,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n pageClassName,\n pageRotationDeltas,\n renderPageOverlay,\n documentId,\n pdfDocument,\n ]\n )\n\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n {showToolbar ? (\n <PDFViewerToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n currentZoomLevel={currentZoomLevel}\n downloadDisabled={downloadDisabled}\n isPreparingDownload={isPreparingDownload}\n numPages={numPages}\n searchControl={\n <PDFViewerSearchControl\n key={documentId}\n documentId={documentId}\n controlsDisabled={controlsDisabled}\n />\n }\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n onDownload={handleDownload}\n onPageChange={scrollToPage}\n onRotate={rotateSelectedPages}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadFile={handleUpload}\n onZoomChange={(zoomLevel) => zoom?.requestZoom(zoomLevel)}\n />\n ) : null}\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {isLoading ? (\n <PDFViewerLoadingSkeleton\n sidebarInline={sidebarInline}\n sidebarOpen={sidebarOpen}\n />\n ) : null}\n <div className="flex h-full max-h-full min-h-0 w-full flex-1 overflow-hidden">\n <DocumentViewerThumbnailSidebar\n closedInlineClassName={THUMBNAIL_SIDEBAR_CLOSED_CLASS}\n inline={sidebarInline}\n open={thumbnailSidebarVisible}\n widthClassName={THUMBNAIL_SIDEBAR_WIDTH_CLASS}\n >\n {thumbnailSidebarVisible ? (\n <PDFViewerThumbnails\n basePageRotations={basePageRotations}\n documentId={documentId}\n activePage={activePage}\n pageCount={numPages}\n pageRotationDeltas={pageRotationDeltas}\n pdfDocument={pdfDocument}\n selectedPageIndexes={selectedPageIndexes}\n onSelectPage={selectThumbnailPage}\n />\n ) : null}\n </DocumentViewerThumbnailSidebar>\n <PDFViewerScrollAreaViewport\n documentId={documentId}\n className="relative h-full max-h-full min-h-0 min-w-0 flex-1"\n >\n <PDFViewerViewportBridge viewportElementRef={viewportElementRef} />\n <PDFViewerSelectionCopyShortcut documentId={documentId} />\n <PDFViewerSelectionReleaseGuard documentId={documentId} />\n <GlobalPointerProvider documentId={documentId}>\n <PDFViewerScroller\n basePageRotations={basePageRotations}\n documentId={documentId}\n pageRotationDeltas={pageRotationDeltas}\n renderPage={renderPage}\n />\n </GlobalPointerProvider>\n <CopyToClipboard />\n </PDFViewerScrollAreaViewport>\n </div>\n </div>\n </div>\n )\n}\n\nfunction PDFViewerDocumentLoader({\n pdfFile,\n onDocumentLoadSuccess,\n ...innerProps\n}: {\n pdfFile: string\n onDocumentLoadSuccess?: (numPages: number) => void\n} & Omit<PDFViewerInnerProps, "pdfFile" | "documentId" | "document">) {\n const { provides: documentManager } = useDocumentManagerCapability()\n const { activeDocumentId, activeDocument } = useActiveDocument()\n const [loadError, setLoadError] = React.useState(false)\n const openedFileRef = React.useRef<string | null>(null)\n const onDocumentLoadSuccessRef = React.useRef(onDocumentLoadSuccess)\n\n React.useEffect(() => {\n onDocumentLoadSuccessRef.current = onDocumentLoadSuccess\n })\n\n React.useEffect(() => {\n if (!documentManager || !pdfFile) return\n if (openedFileRef.current === pdfFile) return\n\n openedFileRef.current = pdfFile\n setLoadError(false)\n\n const previousDocumentIds = documentManager\n .getOpenDocuments()\n .map((openDocument) => openDocument.id)\n const handleOpenError = () => {\n if (openedFileRef.current === pdfFile) setLoadError(true)\n }\n\n documentManager\n .openDocumentUrl({\n url: pdfFile,\n mode: pdfFile.startsWith("blob:") ? "full-fetch" : "auto",\n })\n .wait((response) => {\n response.task.wait((openedDocument) => {\n onDocumentLoadSuccessRef.current?.(openedDocument.pageCount)\n previousDocumentIds.forEach((documentIdToClose) => {\n documentManager.closeDocument(documentIdToClose).wait(\n () => undefined,\n () => undefined\n )\n })\n }, handleOpenError)\n }, handleOpenError)\n }, [documentManager, pdfFile])\n\n const document =\n activeDocument?.status === "loaded" ? activeDocument.document : null\n const documentFailed = loadError || activeDocument?.status === "error"\n\n if (!activeDocumentId || documentFailed || !pdfFile) {\n return (\n <PDFViewerFallbackShell\n className={innerProps.className}\n defaultZoom={innerProps.defaultZoom}\n showDownload={innerProps.showDownload}\n showRotateControls={innerProps.showRotateControls}\n showToolbar={innerProps.showToolbar}\n showUpload={innerProps.showUpload}\n sidebarOpen={false}\n state={!pdfFile ? "empty" : documentFailed ? "error" : "loading"}\n toolbarActions={innerProps.toolbarActions}\n onUploadFile={(file) => {\n innerProps.onUploadFile(file)\n innerProps.onPdfUpload?.(file)\n }}\n />\n )\n }\n\n return (\n <PDFViewerInner\n key={activeDocumentId}\n {...innerProps}\n pdfFile={pdfFile}\n documentId={activeDocumentId}\n document={document}\n />\n )\n}\n\nexport const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(\n function PDFViewer(\n {\n className,\n defaultZoom = DEFAULT_ZOOM,\n fileName,\n resolveScrollAreaViewport,\n showDownload = true,\n showRotateControls = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n pageClassName,\n renderPageOverlay,\n onActivePageChange,\n onDocumentLoadSuccess,\n onPdfUpload,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n },\n ref\n ) {\n const { engine, error: engineError } = useSharedPdfEngine()\n const [uploadedPdfFile, setUploadedPdfFile] = React.useState<{\n src: string | undefined\n url: string | null\n }>(() => ({ src, url: null }))\n const uploadedPdfUrl =\n uploadedPdfFile.src === src ? uploadedPdfFile.url : null\n const pdfFile = uploadedPdfUrl ?? src ?? ""\n\n React.useEffect(\n () => () => {\n if (uploadedPdfUrl) URL.revokeObjectURL(uploadedPdfUrl)\n },\n [uploadedPdfUrl]\n )\n\n const handleUploadFile = React.useCallback(\n (nextFile: File) => {\n const nextUrl = URL.createObjectURL(nextFile)\n\n setUploadedPdfFile({ src, url: nextUrl })\n },\n [src]\n )\n\n // Plugin registrations are created once per viewer instance.\n const [plugins] = React.useState(() => [\n createPluginRegistration(DocumentManagerPluginPackage),\n createPluginRegistration(ViewportPluginPackage, {\n viewportGap: PAGE_GAP,\n }),\n createPluginRegistration(ScrollPluginPackage, {\n defaultPageGap: PAGE_GAP,\n defaultBufferSize: 2,\n }),\n createPluginRegistration(RenderPluginPackage),\n createPluginRegistration(TilingPluginPackage, {\n tileSize: 768,\n overlapPx: 2.5,\n extraRings: 0,\n }),\n createPluginRegistration(InteractionManagerPluginPackage),\n createPluginRegistration(SelectionPluginPackage, {\n marquee: { enabled: false },\n }),\n createPluginRegistration(SearchPluginPackage, {\n showAllResults: true,\n }),\n createPluginRegistration(ThumbnailPluginPackage, {\n width: THUMBNAIL_WIDTH,\n gap: THUMBNAIL_GAP,\n imagePadding: THUMBNAIL_IMAGE_PADDING,\n labelHeight: THUMBNAIL_LABEL_HEIGHT,\n paddingY: THUMBNAIL_PANE_PADDING_Y,\n buffer: 3,\n autoScroll: true,\n scrollBehavior: "auto",\n }),\n createPluginRegistration(ZoomPluginPackage, {\n defaultZoomLevel: defaultZoom,\n minZoom: ZOOM_OPTIONS[0],\n maxZoom: ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1],\n }),\n createPluginRegistration(RotatePluginPackage),\n ])\n\n if (engineError) {\n return (\n <PDFViewerFallbackShell\n className={className}\n defaultZoom={defaultZoom}\n errorMessage="Unable to load the PDF engine."\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showToolbar={showToolbar}\n showUpload={showUpload}\n sidebarOpen={false}\n state="error"\n toolbarActions={toolbarActions}\n onUploadFile={(file) => {\n handleUploadFile(file)\n onPdfUpload?.(file)\n }}\n />\n )\n }\n\n if (!engine) {\n return (\n <PDFViewerFallbackShell\n className={className}\n defaultZoom={defaultZoom}\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showToolbar={showToolbar}\n showUpload={showUpload}\n sidebarOpen={false}\n state="loading"\n toolbarActions={toolbarActions}\n onUploadFile={(file) => {\n handleUploadFile(file)\n onPdfUpload?.(file)\n }}\n />\n )\n }\n\n return (\n <PDFViewerScrollAreaResolverContext.Provider\n value={resolveScrollAreaViewport ?? resolveDefaultScrollAreaViewport}\n >\n <EmbedPDF engine={engine} plugins={plugins}>\n <PDFViewerDocumentLoader\n viewerRef={ref}\n pdfFile={pdfFile}\n defaultZoom={defaultZoom}\n className={className}\n fileName={fileName}\n showDownload={showDownload}\n showToolbar={showToolbar}\n showRotateControls={showRotateControls}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n pageClassName={pageClassName}\n renderPageOverlay={renderPageOverlay}\n onActivePageChange={onActivePageChange}\n onDocumentLoadSuccess={onDocumentLoadSuccess}\n onPdfUpload={onPdfUpload}\n onPagePointerDown={onPagePointerDown}\n onPagePointerMove={onPagePointerMove}\n onPagePointerUp={onPagePointerUp}\n onPagePointerCancel={onPagePointerCancel}\n onUploadFile={handleUploadFile}\n />\n </EmbedPDF>\n </PDFViewerScrollAreaResolverContext.Provider>\n )\n }\n)\n'+ '"use client"\n\nimport * as React from "react"\nimport { createPluginRegistration, refreshPages } from "@embedpdf/core"\nimport { EmbedPDF, useRegistry } from "@embedpdf/core/react"\nimport type {\n PdfDocumentObject,\n PdfEngine,\n Rect,\n Rotation,\n} from "@embedpdf/models"\nimport {\n DocumentManagerPluginPackage,\n useActiveDocument,\n useDocumentManagerCapability,\n} from "@embedpdf/plugin-document-manager/react"\nimport {\n GlobalPointerProvider,\n InteractionManagerPluginPackage,\n PagePointerProvider,\n} from "@embedpdf/plugin-interaction-manager/react"\nimport { RenderLayer, RenderPluginPackage } from "@embedpdf/plugin-render/react"\nimport { Rotate, RotatePluginPackage } from "@embedpdf/plugin-rotate/react"\nimport {\n ScrollPluginPackage,\n ScrollStrategy,\n useScroll,\n useScrollPlugin,\n type PageLayout,\n type ScrollerLayout,\n type VirtualItem,\n} from "@embedpdf/plugin-scroll/react"\nimport {\n SearchLayer,\n SearchPluginPackage,\n useSearch,\n} from "@embedpdf/plugin-search/react"\nimport {\n CopyToClipboard,\n SelectionPluginPackage,\n useSelectionCapability,\n useSelectionPlugin,\n} from "@embedpdf/plugin-selection/react"\nimport {\n ThumbImg,\n ThumbnailPluginPackage,\n useThumbnailCapability,\n useThumbnailPlugin,\n type ThumbMeta,\n} from "@embedpdf/plugin-thumbnail/react"\nimport { TilingLayer, TilingPluginPackage } from "@embedpdf/plugin-tiling/react"\nimport {\n useIsViewportGated,\n useViewportCapability,\n useViewportElement,\n useViewportRef,\n ViewportElementContext,\n ViewportPluginPackage,\n} from "@embedpdf/plugin-viewport/react"\nimport { useZoom, ZoomPluginPackage } from "@embedpdf/plugin-zoom/react"\nimport { flushSync } from "react-dom"\n\nimport { loadSharedPdfEngine } from "@/lib/pdf-thumbnail-utils"\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { Input } from "@/components/ui/input"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from "@/components/ui/popover"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport {\n DocumentViewerSidebarSkeleton,\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/extend/document-viewer-sidebar"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nexport type PDFViewerPageOverlayProps = {\n pageNumber: number\n pageWidth: number\n pageHeight: number\n scale: number\n rotation: number\n}\n\nexport type PDFViewerHandle = {\n scrollToPage: (pageNumber: number, options?: ScrollIntoViewOptions) => void\n scrollToPageArea: (\n pageNumber: number,\n area: { top: number; left?: number; width?: number; height?: number },\n options?: ScrollToOptions\n ) => void\n getViewportElement: () => HTMLDivElement | null\n}\n\nexport type PDFViewerScrollAreaViewportResolver = (\n container: HTMLDivElement\n) => HTMLDivElement | null\n\nexport type PDFViewerProps = {\n className?: string\n defaultZoom?: number\n fileName?: string\n resolveScrollAreaViewport?: PDFViewerScrollAreaViewportResolver\n showDownload?: boolean\n showToolbar?: boolean\n showRotateControls?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onActivePageChange?: (pageNumber: number) => void\n onDocumentLoadSuccess?: (numPages: number) => void\n onPdfUpload?: (file: File) => void\n onPagePointerDown?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerMove?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerUp?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n onPagePointerCancel?: (\n event: React.PointerEvent<HTMLDivElement>,\n pageNumber: number\n ) => void\n}\n\nconst DEFAULT_ZOOM = 1\nconst ZOOM_OPTIONS = [0.1, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2]\nconst PAGE_GAP = 24\nconst THUMBNAIL_PAGE_WIDTH = 92\nconst THUMBNAIL_IMAGE_PADDING = 8\nconst THUMBNAIL_WIDTH = THUMBNAIL_PAGE_WIDTH + THUMBNAIL_IMAGE_PADDING * 2\nconst THUMBNAIL_LABEL_HEIGHT = 24\nconst THUMBNAIL_GAP = 12\nconst THUMBNAIL_PANE_PADDING_Y = 16\nconst THUMBNAIL_SIDEBAR_WIDTH_CLASS = "w-40"\nconst THUMBNAIL_SIDEBAR_CLOSED_CLASS = "-ml-40"\nconst PAGE_BASE_RENDER_MAX_SCALE = 1\nconst PAGE_BASE_RENDER_DPR = 1\nconst PDF_SEARCH_DEBOUNCE_MS = 300\nconst TEXT_SELECTION_BACKGROUND = "rgba(59, 130, 246, 0.14)"\nconst THUMBNAIL_FOCUS_RING_CLASS =\n "group-focus-visible/pdf-thumbnail-sidebar:ring-2 group-focus-visible/pdf-thumbnail-sidebar:ring-ring group-focus-visible/pdf-thumbnail-sidebar:ring-offset-1 group-focus-visible/pdf-thumbnail-sidebar:ring-offset-background"\nconst DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR =\n \'[data-slot="scroll-area-viewport"]\'\n\nfunction resolveDefaultScrollAreaViewport(container: HTMLDivElement) {\n return container.querySelector<HTMLDivElement>(\n DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR\n )\n}\n\nconst PDFViewerScrollAreaResolverContext =\n React.createContext<PDFViewerScrollAreaViewportResolver>(\n resolveDefaultScrollAreaViewport\n )\n\ntype PageRotationDeltas = Map<number, Rotation>\ntype ThumbnailSelectionMode = "replace" | "toggle" | "range"\n\nfunction getPageIndexRange(from: number, to: number): Set<number> {\n const start = Math.min(from, to)\n const end = Math.max(from, to)\n const range = new Set<number>()\n\n for (let pageIndex = start; pageIndex <= end; pageIndex += 1) {\n range.add(pageIndex)\n }\n\n return range\n}\n\nfunction arePageIndexSetsEqual(left: Set<number>, right: Set<number>) {\n if (left.size !== right.size) return false\n\n for (const value of left) {\n if (!right.has(value)) return false\n }\n\n return true\n}\n\nfunction normalizeRotation(rotation: number): Rotation {\n return (((rotation % 4) + 4) % 4) as Rotation\n}\n\nfunction useSharedPdfEngine() {\n const [engine, setEngine] = React.useState<PdfEngine | null>(null)\n const [error, setError] = React.useState<Error | null>(null)\n\n React.useEffect(() => {\n let cancelled = false\n\n loadSharedPdfEngine().then(\n (loadedEngine) => {\n if (!cancelled) setEngine(loadedEngine)\n },\n (loadError: Error) => {\n if (!cancelled) setError(loadError)\n }\n )\n\n return () => {\n cancelled = true\n }\n }, [])\n\n return { engine, error }\n}\n\nfunction rotationToDegrees(rotation: Rotation) {\n return (rotation as number) * 90\n}\n\nfunction normalizeDegrees(rotation: number) {\n return ((rotation % 360) + 360) % 360\n}\n\nfunction ensurePdfExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(".pdf") ? fileName : `${fileName}.pdf`\n}\n\nfunction getPdfDownloadFileName(fileName: string | undefined, src: string) {\n if (fileName?.trim()) return ensurePdfExtension(fileName.trim())\n\n const pathname = src.split(/[?#]/)[0] ?? ""\n const rawName = pathname.split("/").pop() || "document.pdf"\n\n try {\n return ensurePdfExtension(decodeURIComponent(rawName))\n } catch {\n return ensurePdfExtension(rawName)\n }\n}\n\nfunction getRotatedPdfDownloadFileName(fileName: string) {\n return fileName.replace(/\\.pdf$/i, "-rotated.pdf")\n}\n\nfunction downloadBlob(blob: Blob, fileName: string) {\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = fileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nasync function downloadPdfWithPageRotations({\n fileName,\n pageRotationDeltas,\n src,\n}: {\n fileName: string\n pageRotationDeltas: PageRotationDeltas\n src: string\n}) {\n const response = await fetch(src)\n\n if (!response.ok) {\n throw new Error(`Failed to download PDF (${response.status})`)\n }\n\n if (pageRotationDeltas.size === 0) {\n downloadBlob(await response.blob(), fileName)\n return\n }\n\n const [{ PDFDocument, degrees }, pdfBytes] = await Promise.all([\n import("pdf-lib"),\n response.arrayBuffer(),\n ])\n const pdfDocument = await PDFDocument.load(pdfBytes)\n\n pdfDocument.getPages().forEach((page, pageIndex) => {\n const rotationDelta = pageRotationDeltas.get(pageIndex)\n\n if (!rotationDelta) return\n\n page.setRotation(\n degrees(\n normalizeDegrees(\n page.getRotation().angle + rotationToDegrees(rotationDelta)\n )\n )\n )\n })\n\n const nextPdfBytes = await pdfDocument.save()\n const nextPdfBuffer = new ArrayBuffer(nextPdfBytes.byteLength)\n new Uint8Array(nextPdfBuffer).set(nextPdfBytes)\n\n downloadBlob(\n new Blob([nextPdfBuffer], { type: "application/pdf" }),\n getRotatedPdfDownloadFileName(fileName)\n )\n}\n\nfunction getThumbnailMetaForPage({\n page,\n pageIndex,\n rotation,\n width,\n imagePadding,\n labelHeight,\n top,\n}: {\n page: PdfDocumentObject["pages"][number]\n pageIndex: number\n rotation: Rotation\n width: number\n imagePadding: number\n labelHeight: number\n top: number\n}): ThumbMeta {\n const innerWidth = Math.max(1, width - imagePadding * 2)\n const pageWidth = rotation % 2 === 1 ? page.size.height : page.size.width\n const pageHeight = rotation % 2 === 1 ? page.size.width : page.size.height\n const imageHeight = Math.round(innerWidth * (pageHeight / pageWidth))\n const wrapperHeight = imagePadding + imageHeight + imagePadding + labelHeight\n\n return {\n pageIndex,\n width: innerWidth,\n height: imageHeight,\n wrapperHeight,\n top,\n labelHeight,\n padding: imagePadding,\n }\n}\n\nfunction buildThumbnailLayout({\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n width,\n gap,\n imagePadding,\n labelHeight,\n paddingY,\n}: {\n basePageRotations: Rotation[]\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n width: number\n gap: number\n imagePadding: number\n labelHeight: number\n paddingY: number\n}) {\n if (!pdfDocument) return null\n\n let top = paddingY\n const items = pdfDocument.pages.map((page, pageIndex) => {\n const basePageRotation =\n basePageRotations[pageIndex] ?? normalizeRotation(page.rotation)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(pageIndex) ?? 0)\n )\n const meta = getThumbnailMetaForPage({\n page,\n pageIndex,\n rotation: pageRotation,\n width,\n imagePadding,\n labelHeight,\n top,\n })\n\n top += meta.wrapperHeight + gap\n return meta\n })\n\n return {\n items,\n totalHeight: items.length ? top - gap + paddingY : paddingY * 2,\n }\n}\n\nfunction getVisibleThumbnailItems({\n buffer,\n clientHeight,\n items,\n scrollTop,\n}: {\n buffer: number\n clientHeight: number\n items: ThumbMeta[]\n scrollTop: number\n}) {\n if (items.length === 0) return []\n if (clientHeight <= 0)\n return items.slice(0, Math.min(items.length, buffer * 2))\n\n const viewportBottom = scrollTop + clientHeight\n let start = items.findIndex(\n (item) => item.top + item.wrapperHeight >= scrollTop\n )\n\n if (start === -1) start = items.length - 1\n\n let end = start\n while (end < items.length && items[end].top <= viewportBottom) {\n end += 1\n }\n\n return items.slice(\n Math.max(0, start - buffer),\n Math.min(items.length, end + buffer)\n )\n}\n\nfunction PDFViewerLoadingSkeleton({\n sidebarOpen,\n sidebarInline,\n}: {\n sidebarOpen: boolean\n sidebarInline: boolean\n}) {\n return (\n <div className="absolute inset-0 z-20 flex bg-muted/30">\n {sidebarOpen ? (\n <DocumentViewerSidebarSkeleton\n className={THUMBNAIL_SIDEBAR_WIDTH_CLASS}\n inline={sidebarInline}\n />\n ) : null}\n <div className="grid min-w-0 flex-1 place-items-center">\n <Spinner className="size-4" />\n </div>\n </div>\n )\n}\n\n// Rendered while the engine or document is not ready: same frame and controls\n// as the full viewer, with document-dependent controls disabled.\nfunction PDFViewerFallbackShell({\n className,\n defaultZoom,\n errorMessage = "Unable to load the PDF preview.",\n showDownload,\n showRotateControls,\n showToolbar,\n showUpload,\n sidebarOpen,\n state,\n toolbarActions,\n onUploadFile,\n}: {\n className?: string\n defaultZoom: number\n errorMessage?: string\n showDownload: boolean\n showRotateControls: boolean\n showToolbar: boolean\n showUpload: boolean\n sidebarOpen: boolean\n state: "loading" | "error" | "empty"\n toolbarActions?: React.ReactNode\n onUploadFile?: (file: File) => void\n}) {\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n {showToolbar ? (\n <PDFViewerToolbar\n activePage={1}\n controlsDisabled\n currentZoomLevel={defaultZoom}\n numPages={0}\n searchControl={\n <ToolbarTooltip label="Search text">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search text"\n disabled\n >\n <IconPlaceholder\n lucide="Search"\n tabler="IconSearch"\n hugeicons="Search01Icon"\n phosphor="MagnifyingGlassIcon"\n remixicon="RiSearchLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n }\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n onPageChange={() => undefined}\n onRotate={() => undefined}\n onToggleSidebar={() => undefined}\n onUploadFile={onUploadFile}\n onZoomChange={() => undefined}\n />\n ) : null}\n <div className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30">\n {state === "loading" ? (\n <PDFViewerLoadingSkeleton sidebarInline sidebarOpen={sidebarOpen} />\n ) : null}\n {state === "error" ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-sm text-muted-foreground">\n {errorMessage}\n </div>\n ) : null}\n {state === "empty" ? (\n <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-center text-sm text-muted-foreground">\n <div className="max-w-sm space-y-3">\n <div className="font-medium text-foreground">\n Upload a PDF to preview\n </div>\n <div>\n Pass a PDF URL with the <code>src</code> prop or use the upload\n control.\n </div>\n </div>\n </div>\n ) : null}\n </div>\n </div>\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 PDFViewerFileActionsMenu({\n downloadDisabled,\n isPreparingDownload = false,\n onDownload,\n onUploadFile,\n showDownload = false,\n showUpload = false,\n}: {\n downloadDisabled?: boolean\n isPreparingDownload?: boolean\n onDownload?: () => void\n onUploadFile?: (file: File) => void\n showDownload?: boolean\n showUpload?: boolean\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n\n if (!showDownload && !showUpload) return null\n\n return (\n <>\n {showUpload && onUploadFile ? (\n <input\n ref={inputRef}\n type="file"\n accept="application/pdf,.pdf"\n className="sr-only"\n tabIndex={-1}\n onChange={(event) => {\n const nextFile = event.target.files?.[0]\n\n if (nextFile) {\n onUploadFile(nextFile)\n event.currentTarget.value = ""\n }\n }}\n />\n ) : null}\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open PDF actions"\n >\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className="size-4"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-40">\n {showDownload ? (\n <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>\n {isPreparingDownload ? (\n <Spinner className="size-4" />\n ) : (\n <IconPlaceholder\n lucide="Download"\n tabler="IconDownload"\n hugeicons="Download01Icon"\n phosphor="DownloadSimpleIcon"\n remixicon="RiDownload2Line"\n className="size-4"\n />\n )}\n Download\n </DropdownMenuItem>\n ) : null}\n {showUpload && onUploadFile ? (\n <DropdownMenuItem onClick={() => inputRef.current?.click()}>\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n </>\n )\n}\n\nfunction PDFViewerPageNumberControl({\n activePage,\n controlsDisabled,\n numPages,\n onPageChange,\n}: {\n activePage: number\n controlsDisabled: boolean\n numPages: number\n onPageChange: (pageNumber: number) => void\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n const displayPage = numPages ? activePage : 1\n const [isEditing, setIsEditing] = React.useState(false)\n const [draftPage, setDraftPage] = React.useState(() => String(displayPage))\n\n React.useEffect(() => {\n if (!isEditing) return\n\n inputRef.current?.focus()\n inputRef.current?.select()\n }, [isEditing])\n\n const applyPageDraft = React.useCallback(\n (value: string) => {\n const trimmedValue = value.trim()\n\n if (!trimmedValue) return\n\n const parsedPage = Number(trimmedValue)\n\n if (!Number.isInteger(parsedPage)) return\n\n onPageChange(Math.min(Math.max(parsedPage, 1), Math.max(numPages, 1)))\n },\n [numPages, onPageChange]\n )\n\n return (\n <div className="flex items-center text-sm whitespace-nowrap text-primary">\n <span>Page</span>\n {isEditing ? (\n <Input\n ref={inputRef}\n aria-label="Page number"\n inputMode="numeric"\n pattern="[0-9]*"\n size="sm"\n value={draftPage}\n className="mx-1 w-14 min-w-14 rounded-md [&_[data-slot=input]]:text-center"\n onBlur={() => setIsEditing(false)}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) => {\n const nextValue = event.target.value\n\n setDraftPage(nextValue)\n applyPageDraft(nextValue)\n }}\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === "Enter" || event.key === "Escape") {\n event.currentTarget.blur()\n }\n }}\n />\n ) : (\n <Button\n type="button"\n variant="ghost"\n size="sm"\n className="font-normal"\n aria-label={`Current page ${displayPage}. Edit page number`}\n disabled={controlsDisabled || !numPages}\n onClick={() => {\n setDraftPage(String(displayPage))\n setIsEditing(true)\n }}\n >\n {displayPage}\n </Button>\n )}\n <span>of {numPages || "\u2013"}</span>\n </div>\n )\n}\n\nfunction PDFViewerSearchControl({\n documentId,\n controlsDisabled,\n}: {\n documentId: string\n controlsDisabled: boolean\n}) {\n const { state, provides } = useSearch(documentId)\n const { provides: scroll } = useScroll(documentId)\n const [searchDraft, setSearchDraft] = React.useState("")\n const [searchQuery, setSearchQuery] = React.useState("")\n const [isSearching, setIsSearching] = React.useState(false)\n const providesRef = React.useRef(provides)\n const scrollRef = React.useRef(scroll)\n const searchRequestIdRef = React.useRef(0)\n const hasActiveQuery = Boolean(searchQuery.trim())\n const resultLabel = isSearching\n ? "Searching"\n : !hasActiveQuery\n ? "No search"\n : state.total\n ? `${state.activeResultIndex + 1} / ${state.total}`\n : "No results"\n\n const scrollToResult = React.useCallback(\n (index: number) => {\n const result = state.results[index]\n\n if (!result || !scroll) return\n\n const firstRect = result.rects[0]\n\n scroll.scrollToPage({\n pageNumber: result.pageIndex + 1,\n ...(firstRect\n ? {\n pageCoordinates: {\n x: firstRect.origin.x,\n y: firstRect.origin.y,\n },\n alignY: 30,\n }\n : {}),\n behavior: "auto",\n })\n },\n [scroll, state.results]\n )\n\n React.useEffect(() => {\n providesRef.current = provides\n scrollRef.current = scroll\n }, [provides, scroll])\n\n const runSearch = React.useCallback((rawQuery: string) => {\n const query = rawQuery.trim()\n const requestId = searchRequestIdRef.current + 1\n searchRequestIdRef.current = requestId\n setSearchQuery(query)\n\n const searchProvider = providesRef.current\n const scrollProvider = scrollRef.current\n\n if (!searchProvider) {\n setIsSearching(false)\n return\n }\n\n if (!query) {\n searchProvider.stopSearch()\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n searchProvider.startSearch()\n searchProvider.searchAllPages(query).wait(\n (result) => {\n if (searchRequestIdRef.current !== requestId) return\n\n const firstResult = result.results[0]\n\n if (firstResult && scrollProvider) {\n searchProvider.goToResult(0)\n const firstRect = firstResult.rects[0]\n\n scrollProvider.scrollToPage({\n pageNumber: firstResult.pageIndex + 1,\n ...(firstRect\n ? {\n pageCoordinates: {\n x: firstRect.origin.x,\n y: firstRect.origin.y,\n },\n alignY: 30,\n }\n : {}),\n behavior: "auto",\n })\n }\n setIsSearching(false)\n },\n () => {\n if (searchRequestIdRef.current !== requestId) return\n setIsSearching(false)\n }\n )\n }, [])\n\n React.useEffect(() => {\n if (!searchDraft.trim()) return\n\n const timeoutId = window.setTimeout(() => {\n runSearch(searchDraft)\n }, PDF_SEARCH_DEBOUNCE_MS)\n\n return () => window.clearTimeout(timeoutId)\n }, [runSearch, searchDraft])\n\n const handleSearchDraftChange = React.useCallback(\n (event: React.ChangeEvent<HTMLInputElement>) => {\n const nextDraft = event.target.value\n\n setSearchDraft(nextDraft)\n\n if (nextDraft.trim()) {\n setIsSearching(true)\n return\n }\n\n searchRequestIdRef.current += 1\n setSearchQuery("")\n setIsSearching(false)\n provides?.stopSearch()\n },\n [provides]\n )\n\n const clearSearch = React.useCallback(() => {\n searchRequestIdRef.current += 1\n setSearchDraft("")\n setSearchQuery("")\n setIsSearching(false)\n provides?.stopSearch()\n }, [provides])\n\n const navigate = React.useCallback(\n (direction: 1 | -1) => {\n if (!provides || state.total === 0) return\n\n const index =\n direction === 1 ? provides.nextResult() : provides.previousResult()\n\n scrollToResult(index)\n },\n [provides, scrollToResult, state.total]\n )\n\n return (\n <Popover>\n <ToolbarTooltip label="Search text">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search text"\n disabled={controlsDisabled}\n >\n <IconPlaceholder\n lucide="Search"\n tabler="IconSearch"\n hugeicons="Search01Icon"\n phosphor="MagnifyingGlassIcon"\n remixicon="RiSearchLine"\n className="size-4"\n />\n </Button>\n </PopoverTrigger>\n </ToolbarTooltip>\n <PopoverContent align="end" className="w-72">\n <div className="space-y-3">\n <Input\n placeholder="Search text"\n value={searchDraft}\n onChange={handleSearchDraftChange}\n onKeyDown={(event) => {\n if (event.key !== "Enter") return\n\n event.preventDefault()\n if (event.shiftKey && state.total) {\n navigate(-1)\n } else if (state.total) {\n navigate(1)\n } else if (searchDraft.trim()) {\n runSearch(searchDraft)\n }\n }}\n />\n <div className="flex items-center justify-between gap-2">\n <div className="min-w-0 text-xs text-muted-foreground">\n <div className="truncate">\n {state.total ? (\n <>\n <span className="text-primary">\n {state.activeResultIndex + 1}\n </span>\n {` / ${state.total}`}\n </>\n ) : (\n resultLabel\n )}\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-1">\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Previous result"\n disabled={isSearching || state.total === 0}\n onClick={() => navigate(-1)}\n >\n <IconPlaceholder\n lucide="ChevronLeft"\n tabler="IconChevronLeft"\n hugeicons="ArrowLeft01Icon"\n phosphor="CaretLeftIcon"\n remixicon="RiArrowLeftSLine"\n className="size-4"\n />\n </Button>\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Next result"\n disabled={isSearching || state.total === 0}\n onClick={() => navigate(1)}\n >\n <IconPlaceholder\n lucide="ArrowRight"\n tabler="IconArrowRight"\n hugeicons="ArrowRight01Icon"\n phosphor="ArrowRightIcon"\n remixicon="RiArrowRightLine"\n className="size-4"\n />\n </Button>\n </div>\n </div>\n <div className="flex justify-end">\n <Button\n type="button"\n variant="outline"\n size="sm"\n onClick={clearSearch}\n >\n Clear\n </Button>\n </div>\n </div>\n </PopoverContent>\n </Popover>\n )\n}\n\nfunction PDFViewerToolbar({\n activePage,\n controlsDisabled,\n currentZoomLevel,\n downloadDisabled = controlsDisabled,\n isPreparingDownload = false,\n numPages,\n searchControl,\n showDownload,\n showRotateControls,\n showUpload,\n toolbarActions,\n onDownload,\n onPageChange,\n onRotate,\n onToggleSidebar,\n onUploadFile,\n onZoomChange,\n}: {\n activePage: number\n controlsDisabled: boolean\n currentZoomLevel: number\n downloadDisabled?: boolean\n isPreparingDownload?: boolean\n numPages: number\n searchControl: React.ReactNode\n showDownload: boolean\n showRotateControls: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n onDownload?: () => void\n onPageChange: (pageNumber: number) => void\n onRotate: (direction: 1 | -1) => void\n onToggleSidebar: () => void\n onUploadFile?: (file: File) => void\n onZoomChange: (zoomLevel: number) => void\n}) {\n return (\n <div className="flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2">\n <div className="flex min-w-0 flex-wrap items-center gap-2">\n <TooltipProvider>\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 <IconPlaceholder\n lucide="PanelLeft"\n tabler="IconLayoutSidebar"\n hugeicons="SidebarLeftIcon"\n phosphor="SidebarIcon"\n remixicon="RiLayoutLeftLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </TooltipProvider>\n <PDFViewerPageNumberControl\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n numPages={numPages}\n onPageChange={onPageChange}\n />\n </div>\n <TooltipProvider>\n <div className="flex min-w-0 flex-wrap items-center justify-end gap-1">\n {showRotateControls ? (\n <>\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Rotate counterclockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate counterclockwise"\n disabled={controlsDisabled}\n onClick={() => onRotate(-1)}\n >\n <IconPlaceholder\n lucide="RotateCw"\n tabler="IconRotateClockwise"\n hugeicons="RotateClockwiseIcon"\n phosphor="ArrowClockwiseIcon"\n remixicon="RiClockwiseLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Rotate clockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate clockwise"\n disabled={controlsDisabled}\n onClick={() => onRotate(1)}\n >\n <IconPlaceholder\n lucide="RotateCw"\n tabler="IconRotateClockwise"\n hugeicons="RotateClockwiseIcon"\n phosphor="ArrowClockwiseIcon"\n remixicon="RiClockwiseLine"\n className="size-4 -scale-x-100"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Zoom out"\n disabled={\n controlsDisabled || currentZoomLevel <= ZOOM_OPTIONS[0]\n }\n onClick={() => {\n const nextZoom = [...ZOOM_OPTIONS]\n .reverse()\n .find((option) => option < currentZoomLevel)\n\n onZoomChange(nextZoom ?? ZOOM_OPTIONS[0])\n }}\n >\n <IconPlaceholder\n lucide="CircleMinus"\n tabler="IconCircleMinus"\n hugeicons="MinusSignCircleIcon"\n phosphor="MinusCircleIcon"\n remixicon="RiIndeterminateCircleLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(currentZoomLevel)}\n onValueChange={(value) => onZoomChange(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger size="sm" className="w-[84px] min-w-[84px]">\n <SelectValue placeholder="Zoom">\n {Math.round(currentZoomLevel * 100)}%\n </SelectValue>\n </SelectTrigger>\n <SelectContent alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((option) => (\n <SelectItem key={option} value={String(option)}>\n {Math.round(option * 100)}%\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 aria-label="Zoom in"\n disabled={\n controlsDisabled ||\n currentZoomLevel >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n }\n onClick={() => {\n const nextZoom = ZOOM_OPTIONS.find(\n (option) => option > currentZoomLevel\n )\n\n onZoomChange(\n nextZoom ?? ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n )\n }}\n >\n <IconPlaceholder\n lucide="CirclePlusIcon"\n tabler="IconCirclePlusFilled"\n hugeicons="PlusSignCircleIcon"\n phosphor="PlusCircleIcon"\n remixicon="RiAddCircleFill"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n {searchControl}\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n {showDownload || showUpload ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <PDFViewerFileActionsMenu\n downloadDisabled={downloadDisabled}\n isPreparingDownload={isPreparingDownload}\n onDownload={onDownload}\n onUploadFile={onUploadFile}\n showDownload={showDownload}\n showUpload={showUpload}\n />\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction setPdfViewerRef<T>(ref: React.Ref<T> | undefined, value: T | null) {\n if (!ref) return\n\n if (typeof ref === "function") {\n ref(value)\n } else {\n ref.current = value\n }\n}\n\nfunction PDFViewerScrollArea({\n children,\n className,\n viewportClassName,\n viewportProps,\n viewportRef,\n}: {\n children: React.ReactNode\n className?: string\n viewportClassName?: string\n viewportProps?: React.HTMLAttributes<HTMLDivElement>\n viewportRef?: React.Ref<HTMLDivElement>\n}) {\n const resolveScrollAreaViewport = React.useContext(\n PDFViewerScrollAreaResolverContext\n )\n const containerRef = React.useRef<HTMLDivElement | null>(null)\n const { className: viewportPropsClassName, ...resolvedViewportProps } =\n viewportProps ?? {}\n\n const setViewportRef = React.useCallback(\n (viewport: HTMLDivElement | null) => {\n setPdfViewerRef(viewportRef, viewport)\n },\n [viewportRef]\n )\n\n React.useLayoutEffect(() => {\n const container = containerRef.current\n if (!container) return\n\n const viewport = resolveScrollAreaViewport(container)\n\n if (!viewport) {\n console.error(\n `PDFViewer could not resolve the scroll viewport. Add ${DEFAULT_SCROLL_AREA_VIEWPORT_SELECTOR} to your ScrollArea viewport or pass resolveScrollAreaViewport.`\n )\n return\n }\n\n setViewportRef(viewport)\n\n return () => setViewportRef(null)\n }, [resolveScrollAreaViewport, setViewportRef])\n\n return (\n <div\n ref={containerRef}\n data-slot="pdf-viewer-scroll-area"\n className={cn("size-full min-h-0", className)}\n >\n <ScrollArea className="size-full min-h-0">\n <div\n {...resolvedViewportProps}\n data-slot="pdf-viewer-scroll-content"\n className={cn(\n "min-h-full",\n viewportPropsClassName,\n viewportClassName\n )}\n >\n {children}\n </div>\n </ScrollArea>\n </div>\n )\n}\n\nfunction PDFViewerThumbnails({\n basePageRotations,\n documentId,\n activePage,\n pageCount,\n pageRotationDeltas,\n pdfDocument,\n selectedPageIndexes,\n onSelectPage,\n}: {\n basePageRotations: Rotation[]\n documentId: string\n activePage: number\n pageCount: number\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n selectedPageIndexes: Set<number>\n onSelectPage: (pageNumber: number, mode: ThumbnailSelectionMode) => void\n}) {\n const thumbnailListboxId = React.useId()\n const activeDescendantId =\n activePage > 0 ? `${thumbnailListboxId}-page-${activePage}` : undefined\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (pageCount < 1) return\n\n const currentPage = activePage > 0 ? activePage : 1\n let nextPage: number | null = null\n\n if (event.key === "ArrowDown") {\n nextPage = Math.min(pageCount, currentPage + 1)\n } else if (event.key === "ArrowUp") {\n nextPage = Math.max(1, currentPage - 1)\n } else if (event.key === "Home") {\n nextPage = 1\n } else if (event.key === "End") {\n nextPage = pageCount\n } else if (event.key === " ") {\n event.preventDefault()\n onSelectPage(currentPage, "toggle")\n return\n }\n\n if (nextPage === null) return\n\n event.preventDefault()\n onSelectPage(nextPage, event.shiftKey ? "range" : "replace")\n },\n [activePage, onSelectPage, pageCount]\n )\n\n return (\n <PDFViewerThumbnailScrollArea\n activeDescendantId={activeDescendantId}\n basePageRotations={basePageRotations}\n documentId={documentId}\n onKeyDown={handleKeyDown}\n pageRotationDeltas={pageRotationDeltas}\n pdfDocument={pdfDocument}\n >\n {(meta: ThumbMeta) => {\n const pageNumber = meta.pageIndex + 1\n const isActive = pageNumber === activePage\n const isSelected = selectedPageIndexes.has(meta.pageIndex)\n const imagePadding = meta.padding ?? 0\n const pageRotationDelta = pageRotationDeltas.get(meta.pageIndex) ?? 0\n const thumbnailImageStyle: React.CSSProperties =\n pageRotationDelta % 2 === 1\n ? {\n height: meta.width,\n transform: `rotate(${rotationToDegrees(pageRotationDelta)}deg)`,\n width: meta.height,\n }\n : {\n height: meta.height,\n transform:\n pageRotationDelta === 0\n ? undefined\n : `rotate(${rotationToDegrees(pageRotationDelta)}deg)`,\n width: meta.width,\n }\n\n return (\n <div\n key={meta.pageIndex}\n data-pdf-viewer-thumbnail={pageNumber}\n className={cn(\n "absolute right-0 left-0 flex justify-center",\n isActive && "z-10"\n )}\n style={{ top: meta.top, height: meta.wrapperHeight }}\n >\n <div\n id={`${thumbnailListboxId}-page-${pageNumber}`}\n role="option"\n data-pdf-viewer-thumbnail-option={pageNumber}\n aria-current={isActive ? "page" : undefined}\n aria-label={`Page ${pageNumber}`}\n aria-posinset={pageNumber}\n aria-selected={isSelected}\n aria-setsize={pageCount}\n data-selected={isSelected ? "" : undefined}\n className={cn(\n "flex h-full w-full cursor-default flex-col items-center justify-between rounded-md px-2 py-0 text-xs transition-shadow outline-none select-none hover:bg-sidebar-accent",\n isActive || isSelected\n ? "bg-sidebar-accent text-foreground"\n : "text-muted-foreground",\n isActive && THUMBNAIL_FOCUS_RING_CLASS\n )}\n onClick={(event) => {\n const mode = event.shiftKey\n ? "range"\n : event.metaKey || event.ctrlKey\n ? "toggle"\n : "replace"\n\n onSelectPage(pageNumber, mode)\n }}\n >\n <span\n className="mt-0 flex items-center justify-center overflow-hidden rounded-md bg-transparent"\n style={{\n width: meta.width + imagePadding * 2,\n height: meta.height + imagePadding * 2,\n padding: imagePadding,\n }}\n >\n <ThumbImg\n documentId={documentId}\n meta={meta}\n className="block rounded-sm object-contain"\n style={thumbnailImageStyle}\n />\n </span>\n <span\n className="flex items-center justify-center tabular-nums"\n style={{ height: meta.labelHeight }}\n >\n <span className="flex min-w-5 items-center justify-center px-1.5 text-center leading-5">\n {pageNumber}\n </span>\n </span>\n </div>\n </div>\n )\n }}\n </PDFViewerThumbnailScrollArea>\n )\n}\n\nfunction PDFViewerThumbnailScrollArea({\n activeDescendantId,\n basePageRotations,\n children,\n documentId,\n onKeyDown,\n pageRotationDeltas,\n pdfDocument,\n}: {\n activeDescendantId?: string\n basePageRotations: Rotation[]\n children: (meta: ThumbMeta) => React.ReactNode\n documentId: string\n onKeyDown: React.KeyboardEventHandler<HTMLDivElement>\n pageRotationDeltas: PageRotationDeltas\n pdfDocument: PdfDocumentObject | null\n}) {\n const { plugin: thumbnailPlugin } = useThumbnailPlugin()\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewportMetrics, setViewportMetrics] = React.useState({\n clientHeight: 0,\n scrollTop: 0,\n })\n const thumbnailScope = React.useMemo(\n () => thumbnailPlugin?.provides().forDocument(documentId) ?? null,\n [documentId, thumbnailPlugin]\n )\n\n const windowState = React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) => {\n if (!thumbnailScope) return () => undefined\n\n return thumbnailScope.onWindow(() => onStoreChange())\n },\n [thumbnailScope]\n ),\n React.useCallback(\n () => thumbnailScope?.getWindow() ?? null,\n [thumbnailScope]\n ),\n () => null\n )\n const hasWindowState = Boolean(windowState)\n const paddingY = thumbnailPlugin?.cfg.paddingY ?? 0\n const thumbnailLayout = React.useMemo(\n () =>\n buildThumbnailLayout({\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n width: thumbnailPlugin?.cfg.width ?? THUMBNAIL_WIDTH,\n gap: thumbnailPlugin?.cfg.gap ?? THUMBNAIL_GAP,\n imagePadding: thumbnailPlugin?.cfg.imagePadding ?? 0,\n labelHeight: thumbnailPlugin?.cfg.labelHeight ?? THUMBNAIL_LABEL_HEIGHT,\n paddingY,\n }),\n [\n basePageRotations,\n pageRotationDeltas,\n pdfDocument,\n paddingY,\n thumbnailPlugin,\n ]\n )\n const effectiveWindowState = React.useMemo(() => {\n if (!thumbnailLayout) return windowState\n\n const items = getVisibleThumbnailItems({\n buffer: thumbnailPlugin?.cfg.buffer ?? 3,\n clientHeight: viewportMetrics.clientHeight,\n items: thumbnailLayout.items,\n scrollTop: viewportMetrics.scrollTop,\n })\n\n return {\n start: items[0]?.pageIndex ?? -1,\n end: items.at(-1)?.pageIndex ?? -1,\n items,\n totalHeight: thumbnailLayout.totalHeight,\n }\n }, [thumbnailLayout, thumbnailPlugin, viewportMetrics, windowState])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope) return\n\n const updateWindow = () => {\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n }\n\n viewport.addEventListener("scroll", updateWindow)\n const frame = window.requestAnimationFrame(updateWindow)\n\n return () => {\n window.cancelAnimationFrame(frame)\n viewport.removeEventListener("scroll", updateWindow)\n }\n }, [thumbnailScope])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope) return\n\n const resizeObserver = new ResizeObserver(() => {\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n })\n\n resizeObserver.observe(viewport)\n\n return () => resizeObserver.disconnect()\n }, [thumbnailScope])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope) return\n\n thumbnailScope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n }, [thumbnailLayout, thumbnailScope, windowState])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailScope || !hasWindowState) return\n\n return thumbnailScope.onScrollTo(({ top, behavior }) => {\n viewport.scrollTo({ top, behavior })\n })\n }, [hasWindowState, thumbnailScope])\n\n return (\n <PDFViewerScrollArea\n className="h-full w-full"\n viewportClassName="group/pdf-thumbnail-sidebar px-4 focus-visible:ring-0 focus-visible:ring-offset-0"\n viewportProps={{\n "aria-activedescendant": activeDescendantId,\n "aria-label": "PDF pages",\n "aria-multiselectable": true,\n onKeyDown,\n onMouseDown: (event) => {\n event.currentTarget.focus({ preventScroll: true })\n },\n role: "listbox",\n style: {\n paddingBottom: paddingY,\n paddingTop: paddingY,\n },\n tabIndex: 0,\n }}\n viewportRef={viewportRef}\n >\n <div\n className="relative"\n style={{ height: effectiveWindowState?.totalHeight ?? 0 }}\n >\n {effectiveWindowState?.items.map((meta) => children(meta))}\n </div>\n </PDFViewerScrollArea>\n )\n}\n\nfunction PDFViewerScrollAreaViewport({\n children,\n className,\n documentId,\n}: {\n children: React.ReactNode\n className?: string\n documentId: string\n}) {\n const viewportRef = useViewportRef(documentId)\n const { provides: viewport } = useViewportCapability()\n const isGated = useIsViewportGated(documentId)\n const viewportGap = viewport?.getViewportGap() ?? 0\n\n return (\n <ViewportElementContext.Provider value={viewportRef}>\n <PDFViewerScrollArea\n className={className}\n viewportClassName="relative select-none selection:bg-transparent selection:text-inherit"\n viewportProps={{\n style: {\n padding: viewportGap,\n },\n }}\n viewportRef={viewportRef}\n >\n {isGated ? null : children}\n </PDFViewerScrollArea>\n </ViewportElementContext.Provider>\n )\n}\n\n// Captures the scrollable viewport element so the imperative handle can expose\n// it.\nfunction PDFViewerViewportBridge({\n viewportElementRef,\n}: {\n viewportElementRef: React.MutableRefObject<HTMLDivElement | null>\n}) {\n const elementRef = useViewportElement()\n\n React.useEffect(() => {\n viewportElementRef.current = elementRef?.current ?? null\n })\n\n return null\n}\n\nfunction PDFViewerTextSelectionLayer({\n documentId,\n pageIndex,\n scale,\n}: {\n documentId: string\n pageIndex: number\n scale: number\n}) {\n const { plugin: selectionPlugin } = useSelectionPlugin()\n const [rects, setRects] = React.useState<Rect[]>([])\n\n React.useEffect(() => {\n if (!selectionPlugin) return\n\n return selectionPlugin.registerSelectionOnPage({\n documentId,\n pageIndex,\n onRectsChange: ({ rects: nextRects }) => {\n setRects(nextRects)\n },\n })\n }, [documentId, pageIndex, selectionPlugin])\n\n if (!rects.length) return null\n\n return (\n <>\n {rects.map((rect, index) => (\n <div\n key={`${index}-${rect.origin.x}-${rect.origin.y}`}\n className="pointer-events-none absolute"\n style={{\n background: TEXT_SELECTION_BACKGROUND,\n height: rect.size.height * scale,\n left: rect.origin.x * scale,\n top: rect.origin.y * scale,\n width: rect.size.width * scale,\n }}\n />\n ))}\n </>\n )\n}\n\nfunction PDFViewerSelectionReleaseGuard({\n documentId,\n}: {\n documentId: string\n}) {\n const { plugin: selectionPlugin } = useSelectionPlugin()\n const { provides: selection } = useSelectionCapability()\n const lastSelectionModeIdRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n if (!selection) return\n\n return selection.forDocument(documentId).onBeginSelection(({ modeId }) => {\n lastSelectionModeIdRef.current = modeId\n })\n }, [documentId, selection])\n\n React.useEffect(() => {\n if (!selection) return\n\n let cleanupFrame = 0\n const finalizeIfStillSelecting = () => {\n window.cancelAnimationFrame(cleanupFrame)\n cleanupFrame = window.requestAnimationFrame(() => {\n const selectionState = selection.getState(documentId)\n\n if (!selectionState.selecting) return\n\n if (selectionState.selection && selectionPlugin) {\n const pluginWithEndSelection = selectionPlugin as unknown as {\n endSelection?: (documentId: string, modeId: string) => void\n }\n\n pluginWithEndSelection.endSelection?.(\n documentId,\n lastSelectionModeIdRef.current ?? "pointerMode"\n )\n return\n }\n\n if (!selectionState.selection) {\n selection.clear(documentId)\n }\n })\n }\n\n window.addEventListener("pointerup", finalizeIfStillSelecting)\n window.addEventListener("pointercancel", finalizeIfStillSelecting)\n window.addEventListener("blur", finalizeIfStillSelecting)\n\n return () => {\n window.cancelAnimationFrame(cleanupFrame)\n window.removeEventListener("pointerup", finalizeIfStillSelecting)\n window.removeEventListener("pointercancel", finalizeIfStillSelecting)\n window.removeEventListener("blur", finalizeIfStillSelecting)\n }\n }, [documentId, selection, selectionPlugin])\n\n return null\n}\n\nfunction isEditableCopyTarget(target: EventTarget | null) {\n if (!(target instanceof HTMLElement)) return false\n\n if (target.isContentEditable) return true\n\n return Boolean(target.closest("input, textarea, [contenteditable=\'true\']"))\n}\n\nfunction PDFViewerSelectionCopyShortcut({\n documentId,\n}: {\n documentId: string\n}) {\n const { provides: selection } = useSelectionCapability()\n\n React.useEffect(() => {\n if (!selection) return\n\n const copySelectedPdfText = (event: Event) => {\n if (isEditableCopyTarget(event.target)) return\n if (!selection.getState(documentId).selection) return\n\n event.preventDefault()\n selection.copyToClipboard(documentId)\n }\n\n const handleKeyDown = (event: KeyboardEvent) => {\n if (event.key.toLowerCase() !== "c") return\n if (!event.metaKey && !event.ctrlKey) return\n\n copySelectedPdfText(event)\n }\n\n document.addEventListener("copy", copySelectedPdfText)\n document.addEventListener("keydown", handleKeyDown)\n\n return () => {\n document.removeEventListener("copy", copySelectedPdfText)\n document.removeEventListener("keydown", handleKeyDown)\n }\n }, [documentId, selection])\n\n return null\n}\n\nfunction isQuarterTurn(rotation: Rotation) {\n return rotation % 2 === 1\n}\n\nfunction getRotatedDimensions({\n height,\n rotation,\n width,\n}: {\n height: number\n rotation: Rotation\n width: number\n}) {\n return isQuarterTurn(rotation)\n ? { height: width, width: height }\n : { height, width }\n}\n\nfunction getRotatedPageDimensions(page: PageLayout, rotation: Rotation) {\n return getRotatedDimensions({\n height: page.height,\n rotation,\n width: page.width,\n })\n}\n\nfunction applyPageRotationDeltasToScrollerLayout({\n basePageRotations,\n layout,\n pageRotationDeltas,\n}: {\n basePageRotations: Rotation[]\n layout: ScrollerLayout\n pageRotationDeltas: PageRotationDeltas\n}): ScrollerLayout {\n if (pageRotationDeltas.size === 0) return layout\n\n let maxWidth = 0\n let maxHeight = 0\n let offset = 0\n const pageGap = layout.pageGap\n let startSpacingAdjustment = 0\n const items: VirtualItem[] = layout.items.map((item, itemIndex) => {\n let pageOffset = 0\n let itemWidth = 0\n let itemHeight = 0\n const pageLayouts = item.pageLayouts.map((page) => {\n const basePageRotation =\n basePageRotations[page.pageIndex] ?? normalizeRotation(0)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(page.pageIndex) ?? 0)\n )\n const rotatedSize = getRotatedPageDimensions(page, pageRotation)\n const oldScrollAxisSize =\n layout.strategy === ScrollStrategy.Horizontal\n ? page.rotatedWidth\n : page.rotatedHeight\n const newScrollAxisSize =\n layout.strategy === ScrollStrategy.Horizontal\n ? rotatedSize.width\n : rotatedSize.height\n\n if (\n layout.startSpacing === 0 &&\n itemIndex === 0 &&\n pageOffset === 0 &&\n newScrollAxisSize < oldScrollAxisSize\n ) {\n startSpacingAdjustment = Math.max(\n startSpacingAdjustment,\n (oldScrollAxisSize - newScrollAxisSize) / 2\n )\n }\n\n const nextPageLayout = {\n ...page,\n rotatedHeight: rotatedSize.height,\n rotatedWidth: rotatedSize.width,\n x: layout.strategy === ScrollStrategy.Horizontal ? 0 : pageOffset,\n y: layout.strategy === ScrollStrategy.Horizontal ? pageOffset : 0,\n }\n\n pageOffset +=\n (layout.strategy === ScrollStrategy.Horizontal\n ? rotatedSize.height\n : rotatedSize.width) + pageGap\n itemWidth =\n layout.strategy === ScrollStrategy.Horizontal\n ? Math.max(itemWidth, rotatedSize.width)\n : itemWidth + rotatedSize.width\n itemHeight =\n layout.strategy === ScrollStrategy.Horizontal\n ? itemHeight + rotatedSize.height\n : Math.max(itemHeight, rotatedSize.height)\n\n return nextPageLayout\n })\n\n if (pageLayouts.length > 1) {\n if (layout.strategy === ScrollStrategy.Horizontal) {\n itemHeight -= pageGap\n } else {\n itemWidth -= pageGap\n }\n }\n\n const nextItem = {\n ...item,\n height: itemHeight,\n offset,\n pageLayouts,\n width: itemWidth,\n x: layout.strategy === ScrollStrategy.Horizontal ? offset : item.x,\n y: layout.strategy === ScrollStrategy.Horizontal ? item.y : offset,\n }\n\n if (layout.strategy === ScrollStrategy.Horizontal) {\n offset += itemWidth + pageGap\n maxHeight = Math.max(maxHeight, itemHeight)\n } else {\n offset += itemHeight + pageGap\n maxWidth = Math.max(maxWidth, itemWidth)\n }\n\n return nextItem\n })\n\n if (items.length > 0) {\n offset -= pageGap\n }\n\n return {\n ...layout,\n endSpacing: layout.endSpacing,\n items,\n startSpacing: layout.startSpacing + startSpacingAdjustment,\n totalHeight:\n layout.strategy === ScrollStrategy.Horizontal\n ? maxHeight\n : layout.startSpacing +\n startSpacingAdjustment +\n offset +\n layout.endSpacing,\n totalWidth:\n layout.strategy === ScrollStrategy.Horizontal\n ? layout.startSpacing +\n startSpacingAdjustment +\n offset +\n layout.endSpacing\n : maxWidth,\n }\n}\n\nfunction PDFViewerScroller({\n documentId,\n pageRotationDeltas,\n basePageRotations,\n renderPage,\n}: {\n documentId: string\n pageRotationDeltas: PageRotationDeltas\n basePageRotations: Rotation[]\n renderPage: (props: PageLayout) => React.ReactNode\n}) {\n const { plugin: scrollPlugin } = useScrollPlugin()\n const [layoutData, setLayoutData] = React.useState<{\n docId: string | null\n layout: ScrollerLayout | null\n }>({ docId: null, layout: null })\n\n React.useEffect(() => {\n if (!scrollPlugin || !documentId) return\n let frame = 0\n\n const setCurrentLayout = () => {\n try {\n setLayoutData({\n docId: documentId,\n layout: scrollPlugin.getScrollerLayout(documentId),\n })\n } catch {\n setLayoutData({ docId: documentId, layout: null })\n }\n }\n\n const unsubscribe = scrollPlugin.onScrollerData(documentId, (layout) => {\n setLayoutData({ docId: documentId, layout })\n })\n\n frame = window.requestAnimationFrame(setCurrentLayout)\n\n return () => {\n window.cancelAnimationFrame(frame)\n unsubscribe()\n setLayoutData({ docId: null, layout: null })\n scrollPlugin.clearLayoutReady(documentId)\n }\n }, [documentId, scrollPlugin])\n\n const scrollerLayout = React.useMemo(() => {\n if (layoutData.docId !== documentId || !layoutData.layout) return null\n\n return applyPageRotationDeltasToScrollerLayout({\n basePageRotations,\n layout: layoutData.layout,\n pageRotationDeltas,\n })\n }, [basePageRotations, documentId, layoutData, pageRotationDeltas])\n\n React.useLayoutEffect(() => {\n if (!scrollPlugin || !documentId || !scrollerLayout) return\n scrollPlugin.setLayoutReady(documentId)\n }, [documentId, scrollPlugin, scrollerLayout])\n\n if (!scrollerLayout) return null\n\n return (\n <div\n style={{\n width: `${scrollerLayout.totalWidth}px`,\n height: `${scrollerLayout.totalHeight}px`,\n position: "relative",\n boxSizing: "border-box",\n margin: "0 auto",\n ...(scrollerLayout.strategy === ScrollStrategy.Horizontal && {\n display: "flex",\n flexDirection: "row",\n }),\n }}\n >\n <div\n style={\n scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n width: scrollerLayout.startSpacing,\n height: "100%",\n flexShrink: 0,\n }\n : {\n height: scrollerLayout.startSpacing,\n width: "100%",\n }\n }\n />\n <div\n style={{\n gap: scrollerLayout.pageGap,\n display: "flex",\n alignItems: "center",\n position: "relative",\n boxSizing: "border-box",\n ...(scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n flexDirection: "row",\n minHeight: "100%",\n }\n : {\n flexDirection: "column",\n minWidth: "fit-content",\n }),\n }}\n >\n {scrollerLayout.items.map((item) => (\n <div\n key={item.pageNumbers[0]}\n style={{\n display: "flex",\n justifyContent: "center",\n gap: scrollerLayout.pageGap,\n }}\n >\n {item.pageLayouts.map((layout) => (\n <div\n key={layout.pageNumber}\n style={{\n width: `${layout.rotatedWidth}px`,\n height: `${layout.rotatedHeight}px`,\n position: "relative",\n zIndex: layout.elevated ? 1 : undefined,\n }}\n >\n {renderPage(layout)}\n </div>\n ))}\n </div>\n ))}\n </div>\n <div\n style={\n scrollerLayout.strategy === ScrollStrategy.Horizontal\n ? {\n width: scrollerLayout.endSpacing,\n height: "100%",\n flexShrink: 0,\n }\n : {\n height: scrollerLayout.endSpacing,\n width: "100%",\n }\n }\n />\n </div>\n )\n}\n\ntype PDFViewerInnerProps = {\n viewerRef: React.ForwardedRef<PDFViewerHandle>\n pdfFile: string\n documentId: string\n document: PdfDocumentObject | null\n defaultZoom: number\n className?: string\n fileName?: string\n showDownload: boolean\n showToolbar: boolean\n showRotateControls: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onActivePageChange?: (pageNumber: number) => void\n onPdfUpload?: (file: File) => void\n onPagePointerDown?: PDFViewerProps["onPagePointerDown"]\n onPagePointerMove?: PDFViewerProps["onPagePointerMove"]\n onPagePointerUp?: PDFViewerProps["onPagePointerUp"]\n onPagePointerCancel?: PDFViewerProps["onPagePointerCancel"]\n onUploadFile: (file: File) => void\n}\n\nfunction PDFViewerInner({\n viewerRef,\n pdfFile,\n documentId,\n document: pdfDocument,\n defaultZoom,\n className,\n fileName,\n showDownload,\n showToolbar,\n showRotateControls,\n showUpload,\n toolbarActions,\n pageClassName,\n renderPageOverlay,\n onActivePageChange,\n onPdfUpload,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n onUploadFile,\n}: PDFViewerInnerProps) {\n const { registry } = useRegistry()\n const { state: scrollState, provides: scroll } = useScroll(documentId)\n const { state: zoomState, provides: zoom } = useZoom(documentId)\n const { provides: thumbnails } = useThumbnailCapability()\n const { plugin: thumbnailPlugin } = useThumbnailPlugin()\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)\n const [pageRotationDeltas, setPageRotationDeltas] =\n React.useState<PageRotationDeltas>(() => new Map())\n const [selectedPageIndexes, setSelectedPageIndexes] = React.useState<\n Set<number>\n >(() => new Set())\n const basePageRotations = React.useMemo(\n () =>\n pdfDocument?.pages.map((page) => normalizeRotation(page.rotation)) ?? [],\n [pdfDocument]\n )\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewportElementRef = React.useRef<HTMLDivElement | null>(null)\n const pageRotationDeltasRef = React.useRef(pageRotationDeltas)\n const selectedPageIndexesRef = React.useRef(selectedPageIndexes)\n const selectionAnchorPageIndexRef = React.useRef<number | null>(null)\n const suppressActivePageSelectionSyncRef = React.useRef<number | null>(null)\n const initializedSelectionDocumentRef = React.useRef<string | null>(null)\n\n const activePage = scrollState.currentPage\n const numPages = pdfDocument?.pageCount ?? 0\n const isLoading = !pdfDocument\n const controlsDisabled = !numPages\n const downloadDisabled = controlsDisabled || isPreparingDownload\n const thumbnailSidebarVisible = sidebarOpen && !isLoading\n const currentZoomLevel = zoomState.currentZoomLevel\n const alignedThumbnailSidebarDocumentRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n pageRotationDeltasRef.current = pageRotationDeltas\n }, [pageRotationDeltas])\n\n React.useEffect(() => {\n selectedPageIndexesRef.current = selectedPageIndexes\n }, [selectedPageIndexes])\n\n React.useEffect(() => {\n if (activePage > 0) onActivePageChange?.(activePage)\n }, [activePage, onActivePageChange])\n\n React.useEffect(() => {\n if (activePage < 1 || numPages < 1) return\n\n const activePageIndex = activePage - 1\n const suppressedPageIndex = suppressActivePageSelectionSyncRef.current\n\n suppressActivePageSelectionSyncRef.current = null\n\n if (suppressedPageIndex === activePageIndex) return\n\n const nextSelection = new Set([activePageIndex])\n\n selectionAnchorPageIndexRef.current = activePageIndex\n selectedPageIndexesRef.current = nextSelection\n setSelectedPageIndexes((previousSelection) =>\n arePageIndexSetsEqual(previousSelection, nextSelection)\n ? previousSelection\n : nextSelection\n )\n }, [activePage, numPages])\n\n React.useEffect(() => {\n if (\n numPages < 1 ||\n initializedSelectionDocumentRef.current === documentId\n ) {\n return\n }\n\n const initialPageIndex = Math.max(0, (activePage > 0 ? activePage : 1) - 1)\n const initialSelection = new Set([initialPageIndex])\n\n initializedSelectionDocumentRef.current = documentId\n selectionAnchorPageIndexRef.current = initialPageIndex\n selectedPageIndexesRef.current = initialSelection\n setSelectedPageIndexes(initialSelection)\n }, [activePage, documentId, numPages])\n\n React.useEffect(() => {\n if (!thumbnailSidebarVisible) {\n alignedThumbnailSidebarDocumentRef.current = null\n return\n }\n\n if (\n activePage < 1 ||\n !thumbnails ||\n alignedThumbnailSidebarDocumentRef.current === documentId\n ) {\n return\n }\n\n alignedThumbnailSidebarDocumentRef.current = documentId\n const frame = window.requestAnimationFrame(() => {\n thumbnails.forDocument(documentId).scrollToThumb(activePage - 1)\n })\n\n return () => window.cancelAnimationFrame(frame)\n }, [activePage, documentId, thumbnailSidebarVisible, thumbnails])\n\n // The zoom plugin only releases its viewport gate for mode-based zoom\n // levels (automatic/fit); with a numeric default the gate would never\n // lift, so apply the initial zoom explicitly once the document loads.\n const initialZoomDocumentRef = React.useRef<string | null>(null)\n React.useEffect(() => {\n if (!pdfDocument || !zoom) return\n if (initialZoomDocumentRef.current === documentId) return\n\n initialZoomDocumentRef.current = documentId\n zoom.requestZoom(defaultZoom)\n }, [defaultZoom, documentId, pdfDocument, zoom])\n\n const scrollToPage = React.useCallback(\n (pageNumber: number, options?: ScrollIntoViewOptions) => {\n scroll?.scrollToPage({\n pageNumber,\n behavior: options?.behavior === "smooth" ? "smooth" : "auto",\n })\n },\n [scroll]\n )\n\n const selectThumbnailPage = React.useCallback(\n (pageNumber: number, mode: ThumbnailSelectionMode) => {\n const pageIndex = pageNumber - 1\n\n if (pageIndex < 0 || pageIndex >= numPages) return\n\n suppressActivePageSelectionSyncRef.current = pageIndex\n\n setSelectedPageIndexes((previousSelection) => {\n let nextSelection: Set<number>\n\n if (mode === "range") {\n const anchorPageIndex =\n selectionAnchorPageIndexRef.current ??\n (activePage > 0 ? activePage - 1 : pageIndex)\n\n nextSelection = getPageIndexRange(anchorPageIndex, pageIndex)\n } else if (mode === "toggle") {\n nextSelection = new Set(previousSelection)\n\n if (nextSelection.has(pageIndex)) {\n nextSelection.delete(pageIndex)\n } else {\n nextSelection.add(pageIndex)\n }\n\n selectionAnchorPageIndexRef.current = pageIndex\n } else {\n nextSelection = new Set([pageIndex])\n selectionAnchorPageIndexRef.current = pageIndex\n }\n\n selectedPageIndexesRef.current = nextSelection\n return nextSelection\n })\n\n scrollToPage(pageNumber)\n },\n [activePage, numPages, scrollToPage]\n )\n\n React.useImperativeHandle(\n viewerRef,\n () => ({\n scrollToPage,\n scrollToPageArea: (pageNumber, area, options) => {\n const pageSize = pdfDocument?.pages[pageNumber - 1]?.size\n\n scroll?.scrollToPage({\n pageNumber,\n ...(pageSize\n ? {\n pageCoordinates: {\n x: ((area.left ?? 0) / 100) * pageSize.width,\n y: (area.top / 100) * pageSize.height,\n },\n alignY: 25,\n }\n : {}),\n behavior: options?.behavior === "smooth" ? "smooth" : "auto",\n })\n },\n getViewportElement: () => viewportElementRef.current,\n }),\n [pdfDocument, scroll, scrollToPage]\n )\n\n const handleDownload = React.useCallback(async () => {\n if (!pdfFile || isPreparingDownload) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadPdfWithPageRotations({\n fileName: getPdfDownloadFileName(fileName, pdfFile),\n pageRotationDeltas,\n src: pdfFile,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [fileName, isPreparingDownload, pageRotationDeltas, pdfFile])\n\n const rotateSelectedPages = React.useCallback(\n (direction: -1 | 1) => {\n if (!pdfDocument || !registry || activePage < 1) return\n\n const documentState = registry.getStore().getState().core.documents[\n documentId\n ]\n const currentDocument = documentState?.document ?? pdfDocument\n const selectedTargetPageIndexes = Array.from(\n selectedPageIndexesRef.current\n ).filter((pageIndex) => currentDocument.pages[pageIndex])\n const fallbackPageIndex = activePage - 1\n const targetPageIndexes = (\n selectedTargetPageIndexes.length\n ? selectedTargetPageIndexes\n : [fallbackPageIndex]\n )\n .filter((pageIndex) => currentDocument.pages[pageIndex])\n .sort((a, b) => a - b)\n\n if (targetPageIndexes.length === 0) return\n\n const previousDeltas = pageRotationDeltasRef.current\n const nextDeltas = new Map(previousDeltas)\n const referencePageIndex =\n activePage > 0 && currentDocument.pages[activePage - 1]\n ? activePage - 1\n : targetPageIndexes[0]\n let scrollDelta = 0\n\n for (const pageIndex of targetPageIndexes) {\n const currentPage = currentDocument.pages[pageIndex]\n if (!currentPage) continue\n\n const previousDelta = previousDeltas.get(pageIndex) ?? 0\n const nextDelta = normalizeRotation(previousDelta + direction)\n const basePageRotation =\n basePageRotations[pageIndex] ??\n normalizeRotation(currentPage.rotation)\n const previousPageRotation = normalizeRotation(\n basePageRotation + previousDelta\n )\n const nextPageRotation = normalizeRotation(basePageRotation + nextDelta)\n const previousRotatedSize = getRotatedDimensions({\n height: currentPage.size.height * currentZoomLevel,\n rotation: previousPageRotation,\n width: currentPage.size.width * currentZoomLevel,\n })\n const nextRotatedSize = getRotatedDimensions({\n height: currentPage.size.height * currentZoomLevel,\n rotation: nextPageRotation,\n width: currentPage.size.width * currentZoomLevel,\n })\n const heightDelta = nextRotatedSize.height - previousRotatedSize.height\n\n if (pageIndex < referencePageIndex) {\n scrollDelta += heightDelta\n } else if (pageIndex === referencePageIndex) {\n scrollDelta += heightDelta / 2\n }\n\n if (nextDelta) {\n nextDeltas.set(pageIndex, nextDelta)\n } else {\n nextDeltas.delete(pageIndex)\n }\n }\n\n const store = registry.getStore()\n const viewport = viewportElementRef.current\n\n pageRotationDeltasRef.current = nextDeltas\n flushSync(() => {\n setPageRotationDeltas(nextDeltas)\n store.dispatchToCore(refreshPages(documentId, targetPageIndexes))\n })\n\n if (viewport && scrollDelta !== 0) {\n viewport.scrollTop += scrollDelta\n }\n ;(\n thumbnailPlugin as {\n calculateWindowState?: (documentId: string) => void\n } | null\n )?.calculateWindowState?.(documentId)\n },\n [\n activePage,\n basePageRotations,\n currentZoomLevel,\n documentId,\n pdfDocument,\n registry,\n thumbnailPlugin,\n ]\n )\n\n const handleUpload = React.useCallback(\n (file: File) => {\n onUploadFile(file)\n onPdfUpload?.(file)\n },\n [onPdfUpload, onUploadFile]\n )\n\n const renderPage = React.useCallback(\n (page: PageLayout) => {\n const pageNumber = page.pageNumber\n const basePageRotation =\n basePageRotations[page.pageIndex] ??\n pdfDocument?.pages[page.pageIndex]?.rotation ??\n normalizeRotation(0)\n const pageRotation = normalizeRotation(\n basePageRotation + (pageRotationDeltas.get(page.pageIndex) ?? 0)\n )\n\n return (\n <Rotate\n documentId={documentId}\n pageIndex={page.pageIndex}\n rotation={pageRotation}\n >\n <PagePointerProvider\n documentId={documentId}\n pageIndex={page.pageIndex}\n rotation={pageRotation}\n key={`${page.pageIndex}-${pageRotation}`}\n data-pdf-viewer-page={pageNumber}\n className={cn(\n "relative border border-transparent bg-transparent shadow-xs select-none selection:bg-transparent selection:text-inherit",\n pageClassName?.(pageNumber)\n )}\n style={{ backgroundColor: "transparent" }}\n onPointerDown={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerDown?.(event, pageNumber)\n }\n onPointerMove={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerMove?.(event, pageNumber)\n }\n onPointerUp={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerUp?.(event, pageNumber)\n }\n onPointerCancel={(event: React.PointerEvent<HTMLDivElement>) =>\n onPagePointerCancel?.(event, pageNumber)\n }\n >\n <div\n aria-hidden="true"\n className="pointer-events-none absolute inset-0 bg-white"\n />\n <RenderLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n scale={Math.min(currentZoomLevel, PAGE_BASE_RENDER_MAX_SCALE)}\n dpr={PAGE_BASE_RENDER_DPR}\n className="pointer-events-none absolute inset-0 h-full w-full object-fill opacity-100 blur-[0.35px] transition-none"\n />\n <TilingLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n key={`tiles-${page.pageIndex}-${pageRotation}`}\n className="pointer-events-none opacity-100 transition-none [&_img]:opacity-100 [&_img]:transition-none"\n />\n <SearchLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n className="pointer-events-none"\n highlightColor="rgba(253, 224, 71, 0.45)"\n activeHighlightColor="rgba(249, 115, 22, 0.55)"\n />\n <PDFViewerTextSelectionLayer\n documentId={documentId}\n pageIndex={page.pageIndex}\n scale={currentZoomLevel}\n />\n {renderPageOverlay?.({\n pageNumber,\n pageWidth: page.width,\n pageHeight: page.height,\n scale: currentZoomLevel,\n rotation: rotationToDegrees(pageRotation),\n })}\n </PagePointerProvider>\n </Rotate>\n )\n },\n [\n basePageRotations,\n currentZoomLevel,\n onPagePointerCancel,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n pageClassName,\n pageRotationDeltas,\n renderPageOverlay,\n documentId,\n pdfDocument,\n ]\n )\n\n return (\n <div\n data-slot="pdf-viewer"\n className={cn(\n "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",\n className\n )}\n >\n {showToolbar ? (\n <PDFViewerToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n currentZoomLevel={currentZoomLevel}\n downloadDisabled={downloadDisabled}\n isPreparingDownload={isPreparingDownload}\n numPages={numPages}\n searchControl={\n <PDFViewerSearchControl\n key={documentId}\n documentId={documentId}\n controlsDisabled={controlsDisabled}\n />\n }\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n onDownload={handleDownload}\n onPageChange={scrollToPage}\n onRotate={rotateSelectedPages}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadFile={handleUpload}\n onZoomChange={(zoomLevel) => zoom?.requestZoom(zoomLevel)}\n />\n ) : null}\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {isLoading ? (\n <PDFViewerLoadingSkeleton\n sidebarInline={sidebarInline}\n sidebarOpen={sidebarOpen}\n />\n ) : null}\n <div className="flex h-full max-h-full min-h-0 w-full flex-1 overflow-hidden">\n <DocumentViewerThumbnailSidebar\n closedInlineClassName={THUMBNAIL_SIDEBAR_CLOSED_CLASS}\n inline={sidebarInline}\n open={thumbnailSidebarVisible}\n widthClassName={THUMBNAIL_SIDEBAR_WIDTH_CLASS}\n >\n {thumbnailSidebarVisible ? (\n <PDFViewerThumbnails\n basePageRotations={basePageRotations}\n documentId={documentId}\n activePage={activePage}\n pageCount={numPages}\n pageRotationDeltas={pageRotationDeltas}\n pdfDocument={pdfDocument}\n selectedPageIndexes={selectedPageIndexes}\n onSelectPage={selectThumbnailPage}\n />\n ) : null}\n </DocumentViewerThumbnailSidebar>\n <PDFViewerScrollAreaViewport\n documentId={documentId}\n className="relative h-full max-h-full min-h-0 min-w-0 flex-1"\n >\n <PDFViewerViewportBridge viewportElementRef={viewportElementRef} />\n <PDFViewerSelectionCopyShortcut documentId={documentId} />\n <PDFViewerSelectionReleaseGuard documentId={documentId} />\n <GlobalPointerProvider documentId={documentId}>\n <PDFViewerScroller\n basePageRotations={basePageRotations}\n documentId={documentId}\n pageRotationDeltas={pageRotationDeltas}\n renderPage={renderPage}\n />\n </GlobalPointerProvider>\n <CopyToClipboard />\n </PDFViewerScrollAreaViewport>\n </div>\n </div>\n </div>\n )\n}\n\nfunction PDFViewerDocumentLoader({\n pdfFile,\n onDocumentLoadSuccess,\n ...innerProps\n}: {\n pdfFile: string\n onDocumentLoadSuccess?: (numPages: number) => void\n} & Omit<PDFViewerInnerProps, "pdfFile" | "documentId" | "document">) {\n const { provides: documentManager } = useDocumentManagerCapability()\n const { activeDocumentId, activeDocument } = useActiveDocument()\n const [loadError, setLoadError] = React.useState(false)\n const openedFileRef = React.useRef<string | null>(null)\n const onDocumentLoadSuccessRef = React.useRef(onDocumentLoadSuccess)\n\n React.useEffect(() => {\n onDocumentLoadSuccessRef.current = onDocumentLoadSuccess\n })\n\n React.useEffect(() => {\n if (!documentManager || !pdfFile) return\n if (openedFileRef.current === pdfFile) return\n\n openedFileRef.current = pdfFile\n setLoadError(false)\n\n const previousDocumentIds = documentManager\n .getOpenDocuments()\n .map((openDocument) => openDocument.id)\n const handleOpenError = () => {\n if (openedFileRef.current === pdfFile) setLoadError(true)\n }\n\n documentManager\n .openDocumentUrl({\n url: pdfFile,\n mode: pdfFile.startsWith("blob:") ? "full-fetch" : "auto",\n })\n .wait((response) => {\n response.task.wait((openedDocument) => {\n onDocumentLoadSuccessRef.current?.(openedDocument.pageCount)\n previousDocumentIds.forEach((documentIdToClose) => {\n documentManager.closeDocument(documentIdToClose).wait(\n () => undefined,\n () => undefined\n )\n })\n }, handleOpenError)\n }, handleOpenError)\n }, [documentManager, pdfFile])\n\n const document =\n activeDocument?.status === "loaded" ? activeDocument.document : null\n const documentFailed = loadError || activeDocument?.status === "error"\n\n if (!activeDocumentId || documentFailed || !pdfFile) {\n return (\n <PDFViewerFallbackShell\n className={innerProps.className}\n defaultZoom={innerProps.defaultZoom}\n showDownload={innerProps.showDownload}\n showRotateControls={innerProps.showRotateControls}\n showToolbar={innerProps.showToolbar}\n showUpload={innerProps.showUpload}\n sidebarOpen={false}\n state={!pdfFile ? "empty" : documentFailed ? "error" : "loading"}\n toolbarActions={innerProps.toolbarActions}\n onUploadFile={(file) => {\n innerProps.onUploadFile(file)\n innerProps.onPdfUpload?.(file)\n }}\n />\n )\n }\n\n return (\n <PDFViewerInner\n key={activeDocumentId}\n {...innerProps}\n pdfFile={pdfFile}\n documentId={activeDocumentId}\n document={document}\n />\n )\n}\n\nexport const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(\n function PDFViewer(\n {\n className,\n defaultZoom = DEFAULT_ZOOM,\n fileName,\n resolveScrollAreaViewport,\n showDownload = true,\n showRotateControls = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n pageClassName,\n renderPageOverlay,\n onActivePageChange,\n onDocumentLoadSuccess,\n onPdfUpload,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n },\n ref\n ) {\n const { engine, error: engineError } = useSharedPdfEngine()\n const [uploadedPdfFile, setUploadedPdfFile] = React.useState<{\n src: string | undefined\n url: string | null\n }>(() => ({ src, url: null }))\n const uploadedPdfUrl =\n uploadedPdfFile.src === src ? uploadedPdfFile.url : null\n const pdfFile = uploadedPdfUrl ?? src ?? ""\n\n React.useEffect(\n () => () => {\n if (uploadedPdfUrl) URL.revokeObjectURL(uploadedPdfUrl)\n },\n [uploadedPdfUrl]\n )\n\n const handleUploadFile = React.useCallback(\n (nextFile: File) => {\n const nextUrl = URL.createObjectURL(nextFile)\n\n setUploadedPdfFile({ src, url: nextUrl })\n },\n [src]\n )\n\n // Plugin registrations are created once per viewer instance.\n const [plugins] = React.useState(() => [\n createPluginRegistration(DocumentManagerPluginPackage),\n createPluginRegistration(ViewportPluginPackage, {\n viewportGap: PAGE_GAP,\n }),\n createPluginRegistration(ScrollPluginPackage, {\n defaultPageGap: PAGE_GAP,\n defaultBufferSize: 2,\n }),\n createPluginRegistration(RenderPluginPackage),\n createPluginRegistration(TilingPluginPackage, {\n tileSize: 768,\n overlapPx: 2.5,\n extraRings: 0,\n }),\n createPluginRegistration(InteractionManagerPluginPackage),\n createPluginRegistration(SelectionPluginPackage, {\n marquee: { enabled: false },\n }),\n createPluginRegistration(SearchPluginPackage, {\n showAllResults: true,\n }),\n createPluginRegistration(ThumbnailPluginPackage, {\n width: THUMBNAIL_WIDTH,\n gap: THUMBNAIL_GAP,\n imagePadding: THUMBNAIL_IMAGE_PADDING,\n labelHeight: THUMBNAIL_LABEL_HEIGHT,\n paddingY: THUMBNAIL_PANE_PADDING_Y,\n buffer: 3,\n autoScroll: true,\n scrollBehavior: "auto",\n }),\n createPluginRegistration(ZoomPluginPackage, {\n defaultZoomLevel: defaultZoom,\n minZoom: ZOOM_OPTIONS[0],\n maxZoom: ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1],\n }),\n createPluginRegistration(RotatePluginPackage),\n ])\n\n if (engineError) {\n return (\n <PDFViewerFallbackShell\n className={className}\n defaultZoom={defaultZoom}\n errorMessage="Unable to load the PDF engine."\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showToolbar={showToolbar}\n showUpload={showUpload}\n sidebarOpen={false}\n state="error"\n toolbarActions={toolbarActions}\n onUploadFile={(file) => {\n handleUploadFile(file)\n onPdfUpload?.(file)\n }}\n />\n )\n }\n\n if (!engine) {\n return (\n <PDFViewerFallbackShell\n className={className}\n defaultZoom={defaultZoom}\n showDownload={showDownload}\n showRotateControls={showRotateControls}\n showToolbar={showToolbar}\n showUpload={showUpload}\n sidebarOpen={false}\n state="loading"\n toolbarActions={toolbarActions}\n onUploadFile={(file) => {\n handleUploadFile(file)\n onPdfUpload?.(file)\n }}\n />\n )\n }\n\n return (\n <PDFViewerScrollAreaResolverContext.Provider\n value={resolveScrollAreaViewport ?? resolveDefaultScrollAreaViewport}\n >\n <EmbedPDF engine={engine} plugins={plugins}>\n <PDFViewerDocumentLoader\n viewerRef={ref}\n pdfFile={pdfFile}\n defaultZoom={defaultZoom}\n className={className}\n fileName={fileName}\n showDownload={showDownload}\n showToolbar={showToolbar}\n showRotateControls={showRotateControls}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n pageClassName={pageClassName}\n renderPageOverlay={renderPageOverlay}\n onActivePageChange={onActivePageChange}\n onDocumentLoadSuccess={onDocumentLoadSuccess}\n onPdfUpload={onPdfUpload}\n onPagePointerDown={onPagePointerDown}\n onPagePointerMove={onPagePointerMove}\n onPagePointerUp={onPagePointerUp}\n onPagePointerCancel={onPagePointerCancel}\n onUploadFile={handleUploadFile}\n />\n </EmbedPDF>\n </PDFViewerScrollAreaResolverContext.Provider>\n )\n }\n)\n'export function PdfViewerSourceCode() {return (diff --git a/apps/v4/components/ui/color-picker.tsx b/apps/v4/components/ui/color-picker.tsxindex 911ef5b..ed00237 100644--- a/apps/v4/components/ui/color-picker.tsx+++ b/apps/v4/components/ui/color-picker.tsx@@ -1,8 +1,6 @@"use client"import * as React from "react"-import { CheckIcon } from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"@@ -24,6 +22,7 @@ import {TooltipContent,TooltipTrigger,} from "@/components/ui/tooltip"+import { IconPlaceholder } from "@/components/icon-placeholder"const COLOR_PICKER_PRESETS = ["#111827",@@ -255,7 +254,7 @@ function ColorPickerTooltip({export function ColorPicker({color,disabled,- icon,+ icon: IconComponent,label,onTriggerMouseDown,onTriggerPointerDown,@@ -263,7 +262,7 @@ export function ColorPicker({}: {color: stringdisabled?: boolean- icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]+ icon: React.ComponentType<React.ComponentProps<"svg">>label: stringonTriggerMouseDown?: React.MouseEventHandler<HTMLButtonElement>onTriggerPointerDown?: React.PointerEventHandler<HTMLButtonElement>@@ -285,7 +284,7 @@ export function ColorPicker({onMouseDown={onTriggerMouseDown}onPointerDown={onTriggerPointerDown}>- <HugeiconsIcon icon={icon} className="size-4" />+ <IconComponent className="size-4" /><spanclassName="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"style={{ backgroundColor: color }}@@ -476,8 +475,12 @@ export function ColorPickerPanel({}}>{selected ? (- <HugeiconsIcon- icon={CheckIcon}+ <IconPlaceholder+ lucide="Check"+ tabler="IconCheck"+ hugeicons="CheckIcon"+ phosphor="CheckIcon"+ remixicon="RiCheckLine"className={cn("size-3.5",preset === "#ffffff" ? "text-foreground" : "text-white"diff --git a/apps/v4/components/ui/resizable.tsx b/apps/v4/components/ui/resizable.tsxindex 9ac7382..f8d014c 100644--- a/apps/v4/components/ui/resizable.tsx+++ b/apps/v4/components/ui/resizable.tsx@@ -2,11 +2,10 @@import * as React from "react"import type { ReactNode } from "react"-import { DragDropVerticalIcon } from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import * as ResizablePrimitive from "react-resizable-panels"import { cn } from "@/lib/utils"+import { IconPlaceholder } from "@/components/icon-placeholder"function ResizablePanelGroup({className,@@ -61,7 +60,14 @@ function ResizableHandle({{withHandle &&(typeof withHandle === "boolean" ? (<div className="relative z-30 flex h-4 w-3 items-center justify-center rounded-xs border bg-background text-foreground opacity-100 shadow-sm">- <HugeiconsIcon icon={DragDropVerticalIcon} className="size-2.5" />+ <IconPlaceholder+ lucide="GripVertical"+ tabler="IconGripVertical"+ hugeicons="DragDropVerticalIcon"+ phosphor="DotsSixVerticalIcon"+ remixicon="RiDraggable"+ className="size-2.5"+ /></div>) : (withHandlediff --git a/apps/v4/components/xlsx-editor-docs.tsx b/apps/v4/components/xlsx-editor-docs.tsxindex a90230f..da4b69e 100644--- a/apps/v4/components/xlsx-editor-docs.tsx+++ b/apps/v4/components/xlsx-editor-docs.tsx@@ -67,7 +67,7 @@ export function XlsxEditorExample() {}`const xlsxEditorSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n useXlsxViewer,\n useXlsxViewerController,\n useXlsxViewerEditing,\n useXlsxViewerSelection,\n useXlsxViewerZoom,\n XlsxViewer,\n XlsxViewerProvider,\n type XlsxCellAlignmentInput,\n type XlsxCellBorderEdgeInput,\n type XlsxCellRange,\n type XlsxCellStyleInput,\n type XlsxSheetData,\n type XlsxTableHeaderMenuRenderProps,\n} from "@extend-ai/react-xlsx"\nimport {\n Add01Icon,\n AlignBoxBottomCenterIcon,\n AlignBoxMiddleCenterIcon,\n AlignBoxTopCenterIcon,\n BorderAll01Icon,\n BorderBottom01Icon,\n BorderLeft01Icon,\n BorderNone01Icon,\n BorderRight01Icon,\n BorderTop01Icon,\n Calendar03Icon,\n CellsIcon,\n ChevronDownIcon,\n Delete02Icon,\n DollarCircleIcon,\n Download01Icon,\n DropletOffIcon,\n Grid2X2XIcon,\n MinusSignCircleIcon,\n Moon02Icon,\n MoreHorizontalIcon,\n PaintBucketIcon,\n PathfinderMergeIcon,\n PercentIcon,\n PlusSignCircleIcon,\n Redo02Icon,\n Sun03Icon,\n TableRowsSplitIcon,\n TextAlignCenterIcon,\n TextAlignLeft01Icon,\n TextAlignRight01Icon,\n TextBoldIcon,\n TextColorIcon,\n TextItalicIcon,\n TextNumberSignIcon,\n TextStrikethroughIcon,\n TextUnderlineIcon,\n TextWrapIcon,\n Undo02Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport { ColorPicker, ColorPickerPanel } from "@/components/ui/color-picker"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuGroup,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuSub,\n DropdownMenuSubContent,\n DropdownMenuSubTrigger,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { Group, GroupSeparator, GroupText } from "@/components/ui/group"\nimport { Input } from "@/components/ui/input"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport {\n renderXlsxScroller,\n WorkbookSheetTabs,\n WorkbookTableHeaderMenu,\n} from "@/components/extend/xlsx-viewer"\n\nconst XLSX_LOADING_INDICATOR_DELAY_MS = 300\nconst XLSX_EDITOR_READ_ONLY_THRESHOLD_BYTES = 5 * 1024 * 1024\nconst XLSX_DROPDOWN_Z_INDEX_CLASS = "z-40"\nconst ZOOM_OPTIONS = [50, 75, 100, 125, 150, 200, 400] as const\nconst DEFAULT_FONT_FAMILY = "Arial"\nconst FONT_FAMILIES = [\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 DEFAULT_TEXT_COLOR = "#111827"\nconst DEFAULT_FILL_COLOR = "#fde68a"\nconst DEFAULT_BORDER_COLOR = "#111827"\nconst XLSX_EDITOR_SELECT_CHROME_CLASS =\n "shadow-none before:shadow-none not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-none dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-none"\nconst XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS =\n "has-disabled:opacity-100 dark:has-disabled:before:shadow-[0_-1px_--theme(--color-white/6%)]"\n\ntype UploadedWorkbook = {\n buffer: ArrayBuffer\n fileName: string\n identity: string\n}\n\ntype NumberFormatOption = {\n formatString?: string\n formatType: NonNullable<XlsxCellStyleInput["numberFormat"]>["formatType"]\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n id?: number\n label: string\n value: string\n}\n\ntype BorderOption = {\n action: XlsxBorderAction\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n label: string\n}\n\ntype XlsxResolvedCellStyle = XlsxSheetData["styleById"][number]\ntype XlsxResolvedStyleGroup = Record<string, unknown>\n\ntype HorizontalAlignment = NonNullable<XlsxCellAlignmentInput["horizontal"]>\n\ntype VerticalAlignment = NonNullable<XlsxCellAlignmentInput["vertical"]>\n\ntype HorizontalAlignmentToggleValue = Extract<\n HorizontalAlignment,\n "left" | "center" | "right"\n>\n\ntype VerticalAlignmentToggleValue = Extract<\n VerticalAlignment,\n "top" | "center" | "bottom"\n>\n\ntype XlsxFontToggleValue = "bold" | "italic" | "underline" | "strikethrough"\n\ntype XlsxMergeRegion = XlsxCellRange\n\ntype XlsxBorderEdgeKey = "bottom" | "left" | "top" | "right"\n\ntype XlsxBorderAction = "all" | "outside" | "none" | XlsxBorderEdgeKey\n\ntype XlsxWorksheetWithMergeRegions = {\n mergedRegions?: unknown[]\n unmergeCells?: (range: string) => boolean\n}\n\nconst NUMBER_FORMAT_OPTIONS: NumberFormatOption[] = [\n {\n formatType: "general",\n icon: TextNumberSignIcon,\n label: "General",\n value: "General",\n },\n {\n formatString: "0.00",\n formatType: "custom",\n icon: TextNumberSignIcon,\n label: "Number",\n value: "Number",\n },\n {\n formatString: "$#,##0.00",\n formatType: "custom",\n icon: DollarCircleIcon,\n label: "Currency",\n value: "Currency",\n },\n {\n formatString: "0.00%",\n formatType: "custom",\n icon: PercentIcon,\n label: "Percent",\n value: "Percent",\n },\n {\n formatString: "m/d/yyyy",\n formatType: "custom",\n icon: Calendar03Icon,\n label: "Date",\n value: "Date",\n },\n]\n\nconst GENERAL_NUMBER_FORMAT_VALUE = "General"\nconst BUILTIN_NUMBER_FORMAT_VALUE_PREFIX = "builtin:"\n\nfunction formatWorkbookName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "workbook.xlsx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\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 normalizeHexColor(value: string, fallback = DEFAULT_TEXT_COLOR) {\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 toXlsxRgbColor(value: string) {\n return {\n colorType: "rgb" as const,\n hex: normalizeHexColor(value).slice(1).toUpperCase(),\n }\n}\n\nfunction asResolvedStyleGroup(\n value: unknown\n): XlsxResolvedStyleGroup | undefined {\n return value && typeof value === "object" && !Array.isArray(value)\n ? (value as XlsxResolvedStyleGroup)\n : undefined\n}\n\nfunction mergeResolvedCellStyle(\n base: XlsxResolvedCellStyle | null | undefined,\n overlay: XlsxResolvedCellStyle | null | undefined\n): XlsxResolvedCellStyle | null {\n if (!base && !overlay) return null\n\n const nextStyle = { ...(base ?? {}), ...(overlay ?? {}) }\n const baseFont = asResolvedStyleGroup(base?.font)\n const overlayFont = asResolvedStyleGroup(overlay?.font)\n\n if (baseFont || overlayFont) {\n nextStyle.font = overlayFont ?? baseFont\n }\n\n return nextStyle\n}\n\nfunction resolveInheritedCellStyle(\n sheet: XlsxSheetData | null,\n row: number,\n col: number\n): XlsxResolvedCellStyle | null {\n if (!sheet) return null\n\n const colStyleId = sheet.colStyleIds[col]\n const rowStyleId = sheet.rowStyleIds[row]\n const colStyle =\n colStyleId !== undefined ? sheet.styleById[colStyleId] : undefined\n const rowStyle =\n rowStyleId !== undefined ? sheet.styleById[rowStyleId] : undefined\n\n return mergeResolvedCellStyle(colStyle, rowStyle)\n}\n\nfunction getFontToggleValuesFromStyle(\n style: XlsxResolvedCellStyle | null\n): XlsxFontToggleValue[] {\n const font = asResolvedStyleGroup(style?.font)\n const values: XlsxFontToggleValue[] = []\n\n if (font?.bold === true) values.push("bold")\n if (font?.italic === true) values.push("italic")\n if (font?.underline && font.underline !== "none") values.push("underline")\n if (font?.strikethrough === true) values.push("strikethrough")\n\n return values\n}\n\nfunction getFontFamilyValue(style: XlsxResolvedCellStyle | null) {\n const font = asResolvedStyleGroup(style?.font)\n const fontName = font?.name\n\n return typeof fontName === "string" && fontName.trim()\n ? fontName.trim()\n : undefined\n}\n\nfunction getHorizontalAlignmentValue(\n style: XlsxResolvedCellStyle | null\n): HorizontalAlignmentToggleValue[] {\n const alignment = asResolvedStyleGroup(style?.alignment)\n const horizontal = alignment?.horizontal\n\n return horizontal === "left" ||\n horizontal === "center" ||\n horizontal === "right"\n ? [horizontal]\n : []\n}\n\nfunction getVerticalAlignmentValue(\n style: XlsxResolvedCellStyle | null\n): VerticalAlignmentToggleValue[] {\n const alignment = asResolvedStyleGroup(style?.alignment)\n const vertical = alignment?.vertical\n\n if (vertical === undefined || vertical === null) return ["bottom"]\n\n return vertical === "top" || vertical === "center" || vertical === "bottom"\n ? [vertical]\n : []\n}\n\nfunction getNumberFormatValue(style: XlsxResolvedCellStyle | null) {\n const numberFormat = asResolvedStyleGroup(style?.numberFormat)\n\n if (!numberFormat) return GENERAL_NUMBER_FORMAT_VALUE\n\n const formatType = numberFormat.formatType\n const formatString =\n typeof numberFormat.formatString === "string"\n ? numberFormat.formatString.trim()\n : ""\n const id = getNumericValue(numberFormat.id)\n\n if (formatString) {\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.formatString === formatString\n )\n\n return matchingOption?.value ?? formatString\n }\n if (formatType === "builtin" && id !== undefined) {\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.id === id\n )\n\n if (matchingOption) return matchingOption.value\n\n return `${BUILTIN_NUMBER_FORMAT_VALUE_PREFIX}${id}`\n }\n if (formatType === "general") return GENERAL_NUMBER_FORMAT_VALUE\n\n return GENERAL_NUMBER_FORMAT_VALUE\n}\n\nfunction getNumberFormatLabel(value: string) {\n if (value === GENERAL_NUMBER_FORMAT_VALUE) return "General"\n\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.value === value\n )\n if (matchingOption) return matchingOption.label\n\n if (value.startsWith(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX)) {\n return `Builtin ${value.slice(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX.length)}`\n }\n\n return value\n}\n\nfunction getNumberFormatIcon(value: string) {\n return (\n NUMBER_FORMAT_OPTIONS.find((option) => option.value === value)?.icon ??\n TextNumberSignIcon\n )\n}\n\nfunction createNumberFormatStyle(value: string): XlsxCellStyleInput {\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.value === value\n )\n\n if (matchingOption) {\n return {\n numberFormat: {\n formatString: matchingOption.formatString,\n formatType: matchingOption.formatType,\n id: matchingOption.id,\n },\n }\n }\n\n if (value.startsWith(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX)) {\n const id = Number(value.slice(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX.length))\n\n if (Number.isFinite(id)) {\n return {\n numberFormat: {\n formatType: "builtin",\n id: Math.max(0, Math.trunc(id)),\n },\n }\n }\n }\n\n return {\n numberFormat: {\n formatString: value,\n formatType: "custom",\n },\n }\n}\n\nfunction normalizeCellRange(range: XlsxCellRange): XlsxCellRange {\n return {\n start: {\n row: Math.min(range.start.row, range.end.row),\n col: Math.min(range.start.col, range.end.col),\n },\n end: {\n row: Math.max(range.start.row, range.end.row),\n col: Math.max(range.start.col, range.end.col),\n },\n }\n}\n\nfunction getNumericValue(value: unknown) {\n return typeof value === "number" && Number.isFinite(value)\n ? Math.max(0, Math.trunc(value))\n : undefined\n}\n\nfunction getWorksheetMergeRegions(\n worksheet: XlsxWorksheetWithMergeRegions | null\n): XlsxMergeRegion[] {\n if (!Array.isArray(worksheet?.mergedRegions)) return []\n\n return worksheet.mergedRegions.flatMap((entry) => {\n if (!entry || typeof entry !== "object") return []\n\n const region = entry as Record<string, unknown>\n const start = asResolvedStyleGroup(region.start)\n const end = asResolvedStyleGroup(region.end)\n const startRow = getNumericValue(region.startRow ?? start?.row)\n const startCol = getNumericValue(region.startCol ?? start?.col)\n const endRow = getNumericValue(region.endRow ?? end?.row)\n const endCol = getNumericValue(region.endCol ?? end?.col)\n\n if (\n startRow === undefined ||\n startCol === undefined ||\n endRow === undefined ||\n endCol === undefined\n ) {\n return []\n }\n\n return [\n normalizeCellRange({\n start: { row: startRow, col: startCol },\n end: { row: endRow, col: endCol },\n }),\n ]\n })\n}\n\nfunction rangesIntersect(\n firstRange: XlsxCellRange,\n secondRange: XlsxCellRange\n) {\n const first = normalizeCellRange(firstRange)\n const second = normalizeCellRange(secondRange)\n\n return (\n first.start.row <= second.end.row &&\n first.end.row >= second.start.row &&\n first.start.col <= second.end.col &&\n first.end.col >= second.start.col\n )\n}\n\nfunction isSingleCellRange(range: XlsxCellRange) {\n const normalizedRange = normalizeCellRange(range)\n\n return (\n normalizedRange.start.row === normalizedRange.end.row &&\n normalizedRange.start.col === normalizedRange.end.col\n )\n}\n\nfunction getCellColumnLabel(col: number) {\n let label = ""\n let value = col\n\n do {\n label = String.fromCharCode(65 + (value % 26)) + label\n value = Math.floor(value / 26) - 1\n } while (value >= 0)\n\n return label\n}\n\nfunction cellAddressToA1(cell: XlsxCellRange["start"]) {\n return `${getCellColumnLabel(cell.col)}${cell.row + 1}`\n}\n\nfunction rangeToA1(range: XlsxCellRange) {\n const normalizedRange = normalizeCellRange(range)\n\n return `${cellAddressToA1(normalizedRange.start)}:${cellAddressToA1(\n normalizedRange.end\n )}`\n}\n\nfunction getRangeKey(range: XlsxCellRange) {\n const normalizedRange = normalizeCellRange(range)\n\n return `${normalizedRange.start.row}:${normalizedRange.start.col}:${normalizedRange.end.row}:${normalizedRange.end.col}`\n}\n\nfunction createBorderEdge(\n color = DEFAULT_BORDER_COLOR\n): XlsxCellBorderEdgeInput {\n return {\n color: toXlsxRgbColor(color),\n style: "thin",\n }\n}\n\nfunction createBorderPatch(\n entries: Partial<Record<XlsxBorderEdgeKey, XlsxCellBorderEdgeInput>>\n): XlsxCellStyleInput {\n return {\n border: entries,\n }\n}\n\nfunction createNoBorderPatch(): XlsxCellStyleInput {\n return {\n border: {\n bottom: { style: "none" },\n left: { style: "none" },\n right: { style: "none" },\n top: { style: "none" },\n },\n }\n}\n\nfunction createBorderOptions(): BorderOption[] {\n return [\n {\n action: "bottom",\n icon: BorderBottom01Icon,\n label: "Bottom border",\n },\n {\n action: "left",\n icon: BorderLeft01Icon,\n label: "Left border",\n },\n {\n action: "top",\n icon: BorderTop01Icon,\n label: "Top border",\n },\n {\n action: "right",\n icon: BorderRight01Icon,\n label: "Right border",\n },\n {\n action: "all",\n icon: BorderAll01Icon,\n label: "All borders",\n },\n {\n action: "outside",\n icon: BorderAll01Icon,\n label: "Outside border",\n },\n {\n action: "none",\n icon: BorderNone01Icon,\n label: "No border",\n },\n ]\n}\n\nfunction getBorderEdgeRange(\n range: XlsxCellRange,\n edgeKey: XlsxBorderEdgeKey\n): XlsxCellRange {\n const normalizedRange = normalizeCellRange(range)\n\n if (edgeKey === "top") {\n return {\n start: normalizedRange.start,\n end: { row: normalizedRange.start.row, col: normalizedRange.end.col },\n }\n }\n\n if (edgeKey === "bottom") {\n return {\n start: { row: normalizedRange.end.row, col: normalizedRange.start.col },\n end: normalizedRange.end,\n }\n }\n\n if (edgeKey === "left") {\n return {\n start: normalizedRange.start,\n end: { row: normalizedRange.end.row, col: normalizedRange.start.col },\n }\n }\n\n return {\n start: { row: normalizedRange.start.row, col: normalizedRange.end.col },\n end: normalizedRange.end,\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 w-full min-w-full 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 ToolbarSeparator() {\n return <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n}\n\nfunction StyleDropdownItem({\n children,\n icon,\n onClick,\n}: {\n children: React.ReactNode\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n onClick: () => void\n}) {\n return (\n <DropdownMenuItem onClick={onClick}>\n <HugeiconsIcon icon={icon} className="size-4" />\n {children}\n </DropdownMenuItem>\n )\n}\n\nfunction MergeCellsMenu({\n canMerge,\n canMergeAcross,\n canUnmerge,\n disabled,\n isMerged,\n onMergeAcross,\n onMergeAndCenter,\n onMergeCells,\n onUnmergeCells,\n}: {\n canMerge: boolean\n canMergeAcross: boolean\n canUnmerge: boolean\n disabled: boolean\n isMerged: boolean\n onMergeAcross: () => void\n onMergeAndCenter: () => void\n onMergeCells: () => void\n onUnmergeCells: () => void\n}) {\n return (\n <DropdownMenu>\n <div\n className={cn(\n "inline-flex shrink-0 overflow-hidden rounded-lg border border-transparent"\n )}\n >\n <ToolbarTooltip\n label={isMerged ? "Unmerge cells from the menu" : "Merge & Center"}\n >\n <Button\n type="button"\n variant={isMerged ? "secondary" : "ghost"}\n size="sm"\n aria-label="Merge & Center"\n className="h-7 rounded-r-none border-0 px-2.5 before:rounded-r-none"\n data-pressed={isMerged ? "" : undefined}\n disabled={disabled || !canMerge}\n onClick={onMergeAndCenter}\n >\n <HugeiconsIcon icon={PathfinderMergeIcon} className="size-4" />\n <span className="hidden text-xs font-medium lg:inline">\n Merge & Center\n </span>\n </Button>\n </ToolbarTooltip>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant={isMerged ? "secondary" : "ghost"}\n size="icon-sm"\n aria-label="Merge cells options"\n className="h-7 w-6 rounded-l-none border-0 px-0 before:rounded-l-none"\n data-pressed={isMerged ? "" : undefined}\n disabled={disabled}\n >\n <HugeiconsIcon\n icon={ChevronDownIcon}\n className="size-3.5 opacity-100"\n />\n </Button>\n </DropdownMenuTrigger>\n </div>\n <DropdownMenuContent\n align="start"\n className={cn("w-56", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <DropdownMenuItem disabled={!canMerge} onClick={onMergeAndCenter}>\n <HugeiconsIcon icon={PathfinderMergeIcon} className="size-4" />\n Merge & Center\n </DropdownMenuItem>\n <DropdownMenuItem disabled={!canMergeAcross} onClick={onMergeAcross}>\n <HugeiconsIcon icon={TableRowsSplitIcon} className="size-4" />\n Merge Across\n </DropdownMenuItem>\n <DropdownMenuItem disabled={!canMerge} onClick={onMergeCells}>\n <HugeiconsIcon icon={CellsIcon} className="size-4" />\n Merge Cells\n </DropdownMenuItem>\n <DropdownMenuSeparator />\n <DropdownMenuItem disabled={!canUnmerge} onClick={onUnmergeCells}>\n <HugeiconsIcon icon={Grid2X2XIcon} className="size-4" />\n Unmerge Cells\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction NumberFormatSelect({\n disabled,\n onApplyStyle,\n value,\n}: {\n disabled: boolean\n onApplyStyle: (style: XlsxCellStyleInput) => void\n value: string\n}) {\n const hasMatchingOption = NUMBER_FORMAT_OPTIONS.some(\n (option) => option.value === value\n )\n const currentLabel = getNumberFormatLabel(value)\n const CurrentIcon = getNumberFormatIcon(value)\n\n return (\n <Select\n value={value}\n onValueChange={(nextValue) => {\n if (!nextValue) return\n onApplyStyle(createNumberFormatStyle(nextValue))\n }}\n disabled={disabled}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[132px] min-w-[132px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Number format"\n >\n <HugeiconsIcon icon={CurrentIcon} className="size-4" />\n <SelectValue placeholder="General" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {NUMBER_FORMAT_OPTIONS.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n <span className="flex min-w-0 items-center gap-2">\n <HugeiconsIcon icon={option.icon} className="size-4" />\n <span className="truncate">{option.label}</span>\n </span>\n </SelectItem>\n ))}\n {!hasMatchingOption && value !== GENERAL_NUMBER_FORMAT_VALUE ? (\n <SelectItem value={value}>\n <span className="flex min-w-0 items-center gap-2">\n <HugeiconsIcon icon={CurrentIcon} className="size-4" />\n <span className="truncate">{currentLabel}</span>\n </span>\n </SelectItem>\n ) : null}\n </SelectContent>\n </Select>\n )\n}\n\nfunction BorderMenu({\n borderColor,\n disabled,\n onApplyBorder,\n onBorderColorChange,\n}: {\n borderColor: string\n disabled: boolean\n onApplyBorder: (action: XlsxBorderAction) => void\n onBorderColorChange: (color: string) => void\n}) {\n const borderOptions = React.useMemo(() => createBorderOptions(), [])\n const edgeBorderOptions = borderOptions.filter(\n (option) =>\n option.action === "bottom" ||\n option.action === "left" ||\n option.action === "top" ||\n option.action === "right"\n )\n const groupedBorderOptions = borderOptions.filter(\n (option) =>\n option.action === "all" ||\n option.action === "outside" ||\n option.action === "none"\n )\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={disabled}\n aria-label="Cell borders"\n className="relative"\n >\n <HugeiconsIcon icon={BorderAll01Icon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: borderColor }}\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align="start"\n className={cn("w-48", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n {edgeBorderOptions.map((option) => (\n <StyleDropdownItem\n key={option.label}\n icon={option.icon}\n onClick={() => onApplyBorder(option.action)}\n >\n {option.label}\n </StyleDropdownItem>\n ))}\n <DropdownMenuSeparator />\n <DropdownMenuGroup>\n {groupedBorderOptions.map((option) => (\n <StyleDropdownItem\n key={option.label}\n icon={option.icon}\n onClick={() => onApplyBorder(option.action)}\n >\n {option.label}\n </StyleDropdownItem>\n ))}\n </DropdownMenuGroup>\n <DropdownMenuSeparator />\n <DropdownMenuSub>\n <DropdownMenuSubTrigger>\n <HugeiconsIcon\n icon={TextColorIcon}\n className="size-4 text-muted-foreground"\n />\n Border color\n <span\n className="h-3 w-5 rounded-full border border-border"\n style={{ backgroundColor: borderColor }}\n />\n </DropdownMenuSubTrigger>\n <DropdownMenuSubContent\n className={cn("w-64 p-2", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <ColorPickerPanel\n label="Border color"\n color={borderColor}\n onChange={(color) =>\n onBorderColorChange(normalizeHexColor(color))\n }\n />\n </DropdownMenuSubContent>\n </DropdownMenuSub>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction AlignmentMoreMenu({\n disabled,\n onApplyStyle,\n}: {\n disabled: boolean\n onApplyStyle: (style: XlsxCellStyleInput) => void\n}) {\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={disabled}\n aria-label="More alignment"\n >\n <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align="start"\n className={cn("w-48", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <StyleDropdownItem\n icon={TextWrapIcon}\n onClick={() => onApplyStyle({ alignment: { wrapText: false } })}\n >\n Do not wrap\n </StyleDropdownItem>\n <StyleDropdownItem\n icon={TextWrapIcon}\n onClick={() => onApplyStyle({ alignment: { shrinkToFit: true } })}\n >\n Shrink to fit\n </StyleDropdownItem>\n <StyleDropdownItem\n icon={TextWrapIcon}\n onClick={() => onApplyStyle({ alignment: { shrinkToFit: false } })}\n >\n Do not shrink\n </StyleDropdownItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction EditorFileActionsMenu({\n canExport,\n exportXlsx,\n onUploadClick,\n}: {\n canExport: boolean\n exportXlsx: () => void\n onUploadClick: () => void\n}) {\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open workbook actions"\n >\n <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align="end"\n className={cn("w-40", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <DropdownMenuItem disabled={!canExport} onClick={exportXlsx}>\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n Download\n </DropdownMenuItem>\n <DropdownMenuItem onClick={onUploadClick}>\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction EditorToolbar({\n isDark,\n onIsDarkChange,\n onUploadClick,\n showNightRenderToggle,\n workbookIdentity,\n}: {\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n showNightRenderToggle: boolean\n workbookIdentity: string\n}) {\n const {\n activeSheet,\n activeSheetIndex,\n canExport,\n exportXlsx,\n getActiveWorksheet,\n revision,\n setActiveSheetIndex,\n sheets,\n } = useXlsxViewer()\n const { activeCell, activeCellAddress, selectRange, selection } =\n useXlsxViewerSelection()\n const {\n addSheet,\n canRedo,\n canUndo,\n mergeSelection,\n pasteStructuredClipboardData,\n readOnly,\n redo,\n removeActiveSheet,\n selectedFormula,\n selectedValue,\n setCellStyle,\n setCellFormula,\n setCellValue,\n setRangeStyle,\n setSelectedCellStyle,\n undo,\n unmergeSelection,\n } = useXlsxViewerEditing()\n const { canZoomIn, canZoomOut, setZoomScale, zoomIn, zoomOut, zoomScale } =\n useXlsxViewerZoom()\n const [formulaDraft, setFormulaDraft] = React.useState("")\n const [formulaFocused, setFormulaFocused] = React.useState(false)\n const [fontFamily, setFontFamily] = React.useState(DEFAULT_FONT_FAMILY)\n const [fontSize, setFontSize] = React.useState(11)\n const [textColor, setTextColor] = React.useState(DEFAULT_TEXT_COLOR)\n const [fillColor, setFillColor] = React.useState(DEFAULT_FILL_COLOR)\n const [borderColor, setBorderColor] = React.useState(DEFAULT_BORDER_COLOR)\n const [appliedMergeRegions, setAppliedMergeRegions] = React.useState<\n XlsxMergeRegion[]\n >([])\n const lastStyleTargetRef = React.useRef<{\n range: XlsxCellRange\n sheetIndex: number\n workbookIdentity: string\n } | null>(null)\n const formulaEditCellRef = React.useRef<typeof activeCell>(null)\n const formulaInitialValueRef = React.useRef("")\n const hasWorkbook = sheets.length > 0\n const hasSelection = Boolean(selection)\n const hasActiveCell = Boolean(activeCell)\n const canStyleSelection = (hasSelection || hasActiveCell) && !readOnly\n const activeRange = React.useMemo<XlsxCellRange | null>(() => {\n if (selection) return normalizeCellRange(selection)\n if (!activeCell) return null\n\n return {\n start: activeCell,\n end: activeCell,\n }\n }, [activeCell, selection])\n\n React.useEffect(() => {\n if (!activeRange) return\n\n lastStyleTargetRef.current = {\n range: activeRange,\n sheetIndex: activeSheetIndex,\n workbookIdentity,\n }\n }, [activeRange, activeSheetIndex, workbookIdentity])\n const worksheetMergeRegions = React.useMemo(() => {\n void revision\n\n return getWorksheetMergeRegions(\n getActiveWorksheet() as XlsxWorksheetWithMergeRegions | null\n )\n }, [getActiveWorksheet, revision])\n const mergeRegions = React.useMemo(\n () => [...worksheetMergeRegions, ...appliedMergeRegions],\n [appliedMergeRegions, worksheetMergeRegions]\n )\n const selectionIntersectsMerge = Boolean(\n activeRange &&\n mergeRegions.some((mergeRegion) =>\n rangesIntersect(activeRange, mergeRegion)\n )\n )\n\n React.useEffect(() => {\n if (\n appliedMergeRegions.length === 0 ||\n worksheetMergeRegions.length === 0\n ) {\n return\n }\n\n setAppliedMergeRegions((currentRegions) =>\n currentRegions.filter(\n (currentRegion) =>\n !worksheetMergeRegions.some((worksheetRegion) =>\n rangesIntersect(currentRegion, worksheetRegion)\n )\n )\n )\n }, [appliedMergeRegions.length, worksheetMergeRegions])\n\n React.useEffect(() => {\n setAppliedMergeRegions([])\n }, [activeSheetIndex])\n const selectionIsSingleCell = activeRange\n ? isSingleCellRange(activeRange)\n : true\n const selectionSpansMultipleColumns = activeRange\n ? activeRange.start.col !== activeRange.end.col\n : false\n const canMergeSelectedCells = Boolean(\n selection &&\n !readOnly &&\n !selectionIntersectsMerge &&\n !selectionIsSingleCell\n )\n const canMergeAcross = Boolean(\n selection &&\n !readOnly &&\n !selectionIntersectsMerge &&\n selectionSpansMultipleColumns\n )\n const canUnmergeSelectedCells = Boolean(\n selection && !readOnly && selectionIntersectsMerge\n )\n const currentZoom = Math.round(zoomScale)\n const selectedCellInputValue = selectedFormula || selectedValue\n\n React.useEffect(() => {\n if (formulaFocused) return\n setFormulaDraft(selectedCellInputValue)\n }, [formulaFocused, selectedCellInputValue, activeCellAddress])\n\n const activeCellStyle = React.useMemo(() => {\n // Worksheet style objects are mutable; revision invalidates this read after edits.\n void revision\n\n if (!activeCell) return null\n\n const worksheet = getActiveWorksheet()\n const inheritedStyle = resolveInheritedCellStyle(\n activeSheet,\n activeCell.row,\n activeCell.col\n )\n const cellStyle = worksheet?.getCellStyleAt(\n activeCell.row,\n activeCell.col\n ) as XlsxResolvedCellStyle | null | undefined\n\n return mergeResolvedCellStyle(inheritedStyle, cellStyle)\n }, [activeCell, activeSheet, getActiveWorksheet, revision])\n const fontToggleValues = React.useMemo(\n () => getFontToggleValuesFromStyle(activeCellStyle),\n [activeCellStyle]\n )\n const fontFamilyValue = getFontFamilyValue(activeCellStyle) ?? fontFamily\n const horizontalAlignmentValue = React.useMemo(\n () => getHorizontalAlignmentValue(activeCellStyle),\n [activeCellStyle]\n )\n const verticalAlignmentValue = React.useMemo(\n () => getVerticalAlignmentValue(activeCellStyle),\n [activeCellStyle]\n )\n const numberFormatValue = React.useMemo(\n () => getNumberFormatValue(activeCellStyle),\n [activeCellStyle]\n )\n\n const commitFormula = React.useCallback(() => {\n const targetCell = formulaEditCellRef.current ?? activeCell\n if (!targetCell) return\n if (formulaDraft === formulaInitialValueRef.current) return\n\n if (formulaDraft.trim().startsWith("=")) {\n setCellFormula(targetCell, formulaDraft)\n } else {\n setCellValue(targetCell, formulaDraft)\n }\n formulaInitialValueRef.current = formulaDraft\n }, [activeCell, formulaDraft, setCellFormula, setCellValue])\n\n const applyStyle = React.useCallback(\n (style: XlsxCellStyleInput) => {\n const applyRangeStyle = (range: XlsxCellRange) => {\n const normalizedRange = normalizeCellRange(range)\n const targetRanges = [\n normalizedRange,\n ...mergeRegions.filter((mergeRegion) =>\n rangesIntersect(normalizedRange, mergeRegion)\n ),\n ]\n const uniqueTargetRanges = new Map<string, XlsxCellRange>()\n\n targetRanges.forEach((targetRange) => {\n const normalizedTargetRange = normalizeCellRange(targetRange)\n uniqueTargetRanges.set(\n getRangeKey(normalizedTargetRange),\n normalizedTargetRange\n )\n })\n\n uniqueTargetRanges.forEach((targetRange) => {\n setRangeStyle(targetRange, style)\n })\n }\n\n if (selection) {\n const normalizedSelection = normalizeCellRange(selection)\n\n if (!isSingleCellRange(normalizedSelection)) {\n applyRangeStyle(normalizedSelection)\n return true\n }\n\n if (activeCell) {\n setSelectedCellStyle(style)\n return true\n }\n\n setCellStyle(normalizedSelection.start, style)\n return true\n }\n\n if (activeCell) {\n setSelectedCellStyle(style)\n return true\n }\n\n const fallbackTarget = lastStyleTargetRef.current\n const targetRange =\n fallbackTarget?.sheetIndex === activeSheetIndex &&\n fallbackTarget.workbookIdentity === workbookIdentity\n ? fallbackTarget.range\n : null\n\n if (!targetRange) return false\n\n if (isSingleCellRange(targetRange)) {\n setCellStyle(normalizeCellRange(targetRange).start, style)\n return true\n }\n\n applyRangeStyle(targetRange)\n return true\n },\n [\n activeCell,\n activeSheetIndex,\n mergeRegions,\n selection,\n setCellStyle,\n setRangeStyle,\n setSelectedCellStyle,\n workbookIdentity,\n ]\n )\n\n const applyBorderAction = React.useCallback(\n (action: XlsxBorderAction) => {\n if (!activeRange) return\n\n const normalizedRange = normalizeCellRange(activeRange)\n const edge = createBorderEdge(borderColor)\n const allBorderPatch = createBorderPatch({\n bottom: edge,\n left: edge,\n right: edge,\n top: edge,\n })\n\n if (action === "all") {\n setRangeStyle(normalizedRange, allBorderPatch)\n return\n }\n\n if (action === "none") {\n setRangeStyle(normalizedRange, createNoBorderPatch())\n return\n }\n\n if (action === "outside") {\n if (isSingleCellRange(normalizedRange)) {\n setCellStyle(normalizedRange.start, allBorderPatch)\n return\n }\n\n const outsideEdgeKeys: XlsxBorderEdgeKey[] = [\n "top",\n "bottom",\n "left",\n "right",\n ]\n\n outsideEdgeKeys.forEach((edgeKey) => {\n setRangeStyle(\n getBorderEdgeRange(normalizedRange, edgeKey),\n createBorderPatch({ [edgeKey]: edge })\n )\n })\n return\n }\n\n setRangeStyle(\n getBorderEdgeRange(normalizedRange, action),\n createBorderPatch({ [action]: edge })\n )\n },\n [activeRange, borderColor, setCellStyle, setRangeStyle]\n )\n\n const applyHorizontalAlignment = React.useCallback(\n (horizontal: HorizontalAlignmentToggleValue | undefined) => {\n if (!horizontal) return\n\n applyStyle({ alignment: { horizontal } })\n },\n [applyStyle]\n )\n\n const applyVerticalAlignment = React.useCallback(\n (vertical: VerticalAlignmentToggleValue | undefined) => {\n if (!vertical) return\n\n applyStyle({ alignment: { vertical } })\n },\n [applyStyle]\n )\n\n const mergeSelectedCells = React.useCallback(() => {\n if (!canMergeSelectedCells || !selection) return\n\n setAppliedMergeRegions([normalizeCellRange(selection)])\n mergeSelection()\n }, [canMergeSelectedCells, mergeSelection, selection])\n\n const mergeAcrossSelectedCells = React.useCallback(() => {\n if (!activeCell || !canMergeAcross || !selection) return\n\n const normalizedRange = normalizeCellRange(selection)\n const worksheet = getActiveWorksheet()\n if (!worksheet) return\n\n const formula = worksheet.getFormulaAt(activeCell.row, activeCell.col)\n const rawValue = worksheet.getCellAt(activeCell.row, activeCell.col).toJs()\n const colSpan = normalizedRange.end.col - normalizedRange.start.col + 1\n const rowSpan = normalizedRange.end.row - normalizedRange.start.row + 1\n const merges = Array.from({ length: rowSpan }, (_, rowOffset) => ({\n colOffset: normalizedRange.start.col - activeCell.col,\n colSpan,\n rowOffset: normalizedRange.start.row + rowOffset - activeCell.row,\n rowSpan: 1,\n }))\n const mergeRegionsByRow = Array.from({ length: rowSpan }, (_, rowOffset) =>\n normalizeCellRange({\n start: {\n col: normalizedRange.start.col,\n row: normalizedRange.start.row + rowOffset,\n },\n end: {\n col: normalizedRange.end.col,\n row: normalizedRange.start.row + rowOffset,\n },\n })\n )\n\n const didPaste = pasteStructuredClipboardData(\n JSON.stringify({\n cells: [\n formula\n ? { colOffset: 0, formula, rowOffset: 0 }\n : { colOffset: 0, rowOffset: 0, value: rawValue ?? "" },\n ],\n cols: colSpan,\n merges,\n rows: rowSpan,\n })\n )\n\n if (!didPaste) return\n\n setAppliedMergeRegions(mergeRegionsByRow)\n selectRange(normalizedRange)\n }, [\n activeCell,\n canMergeAcross,\n getActiveWorksheet,\n pasteStructuredClipboardData,\n selectRange,\n selection,\n ])\n\n const mergeAndCenterSelectedCells = React.useCallback(() => {\n if (!canMergeSelectedCells || !selection) return\n\n setAppliedMergeRegions([normalizeCellRange(selection)])\n setRangeStyle(selection, { alignment: { horizontal: "center" } })\n mergeSelection()\n }, [canMergeSelectedCells, mergeSelection, selection, setRangeStyle])\n\n const unmergeSelectedCells = React.useCallback(() => {\n if (!canUnmergeSelectedCells || !activeRange) return\n\n const worksheet =\n getActiveWorksheet() as XlsxWorksheetWithMergeRegions | null\n if (!worksheet?.unmergeCells) return\n\n const normalizedRange = normalizeCellRange(activeRange)\n const uniqueMergeRegions = new Map<string, XlsxMergeRegion>()\n\n ;[...worksheetMergeRegions, ...appliedMergeRegions].forEach(\n (mergeRegion) => {\n if (!rangesIntersect(normalizedRange, mergeRegion)) return\n\n uniqueMergeRegions.set(getRangeKey(mergeRegion), mergeRegion)\n }\n )\n\n let didUnmerge = false\n\n uniqueMergeRegions.forEach((mergeRegion) => {\n didUnmerge =\n worksheet.unmergeCells?.(rangeToA1(mergeRegion)) || didUnmerge\n })\n\n if (!didUnmerge) {\n unmergeSelection()\n return\n }\n\n setAppliedMergeRegions([])\n setRangeStyle(normalizedRange, {})\n selectRange(normalizedRange)\n }, [\n activeRange,\n appliedMergeRegions,\n canUnmergeSelectedCells,\n getActiveWorksheet,\n selectRange,\n setRangeStyle,\n unmergeSelection,\n worksheetMergeRegions,\n ])\n\n const applyFontToggleValues = React.useCallback(\n (nextValues: XlsxFontToggleValue[]) => {\n const previousValues = fontToggleValues\n const changedValue =\n nextValues.find((value) => !previousValues.includes(value)) ??\n previousValues.find((value) => !nextValues.includes(value))\n\n if (!changedValue) return\n\n const isPressed = nextValues.includes(changedValue)\n\n if (changedValue === "bold") {\n applyStyle({ font: { bold: isPressed } })\n } else if (changedValue === "italic") {\n applyStyle({ font: { italic: isPressed } })\n } else if (changedValue === "underline") {\n applyStyle({ font: { underline: isPressed ? "single" : "none" } })\n } else if (changedValue === "strikethrough") {\n applyStyle({ font: { strikethrough: isPressed } })\n }\n },\n [applyStyle, fontToggleValues]\n )\n\n return (\n <div className="border-b bg-background">\n <div className="flex min-h-11 items-center justify-between gap-3 border-b px-3">\n <div className="min-w-0 flex-1" />\n <TooltipProvider>\n <div className="flex shrink-0 items-center gap-1">\n {showNightRenderToggle ? (\n <>\n <ToolbarTooltip\n label={isDark ? "Use light workbook" : "Use dark workbook"}\n >\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label={\n isDark ? "Use light workbook" : "Use dark workbook"\n }\n onClick={() => onIsDarkChange(!isDark)}\n >\n <HugeiconsIcon\n icon={isDark ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <EditorFileActionsMenu\n canExport={canExport}\n exportXlsx={exportXlsx}\n onUploadClick={onUploadClick}\n />\n </div>\n </TooltipProvider>\n </div>\n <TooltipProvider>\n <div className="flex min-h-12 flex-wrap items-center gap-2 border-b bg-background px-3 py-2">\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarTooltip label="Undo">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Undo"\n disabled={!canUndo || readOnly}\n onClick={undo}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Redo">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Redo"\n disabled={!canRedo || readOnly}\n onClick={redo}\n >\n <HugeiconsIcon icon={Redo02Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <Select\n value={fontFamilyValue}\n onValueChange={(value) => {\n if (!value) return\n\n if (applyStyle({ font: { name: value } })) {\n setFontFamily(value)\n }\n }}\n disabled={!canStyleSelection}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[132px] min-w-[132px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Font family"\n >\n <SelectValue placeholder="Font">{fontFamilyValue}</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {FONT_FAMILIES.map((option) => (\n <SelectItem key={option} value={option}>\n <span style={{ fontFamily: option }}>{option}</span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <Select\n value={String(fontSize)}\n onValueChange={(value) => {\n const nextFontSize = Number(value)\n if (!Number.isFinite(nextFontSize)) return\n\n setFontSize(nextFontSize)\n applyStyle({ font: { size: nextFontSize } })\n }}\n disabled={!canStyleSelection}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[78px] min-w-[78px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Font size"\n >\n <SelectValue placeholder="Size" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\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 </div>\n <ToolbarSeparator />\n <ToggleGroup\n className="shrink-0"\n disabled={!canStyleSelection}\n multiple\n spacing="default"\n value={fontToggleValues}\n onValueChange={(value) =>\n applyFontToggleValues(value as XlsxFontToggleValue[])\n }\n >\n <ToolbarTooltip label="Bold">\n <ToggleGroupItem aria-label="Bold" size="sm" value="bold">\n <HugeiconsIcon icon={TextBoldIcon} className="size-4" />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Italic">\n <ToggleGroupItem aria-label="Italic" size="sm" value="italic">\n <HugeiconsIcon icon={TextItalicIcon} className="size-4" />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Underline">\n <ToggleGroupItem\n aria-label="Underline"\n size="sm"\n value="underline"\n >\n <HugeiconsIcon icon={TextUnderlineIcon} className="size-4" />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Strikethrough">\n <ToggleGroupItem\n aria-label="Strikethrough"\n size="sm"\n value="strikethrough"\n >\n <HugeiconsIcon\n icon={TextStrikethroughIcon}\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n </ToggleGroup>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <ColorPicker\n label="Text color"\n icon={TextColorIcon}\n color={textColor}\n disabled={!canStyleSelection}\n onChange={(color) => {\n const nextColor = normalizeHexColor(color)\n setTextColor(nextColor)\n applyStyle({ font: { color: toXlsxRgbColor(nextColor) } })\n }}\n />\n <ColorPicker\n label="Fill color"\n icon={PaintBucketIcon}\n color={fillColor}\n disabled={!canStyleSelection}\n onChange={(color) => {\n const nextColor = normalizeHexColor(color, DEFAULT_FILL_COLOR)\n setFillColor(nextColor)\n applyStyle({\n fill: {\n color: toXlsxRgbColor(nextColor),\n fillType: "solid",\n },\n })\n }}\n />\n <ToolbarIconButton\n label="No fill"\n disabled={!canStyleSelection}\n onClick={() => applyStyle({ fill: { fillType: "none" } })}\n >\n <HugeiconsIcon icon={DropletOffIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <ToggleGroup\n className="shrink-0"\n disabled={!canStyleSelection}\n spacing="default"\n value={horizontalAlignmentValue}\n >\n <ToolbarTooltip label="Align left">\n <ToggleGroupItem\n aria-label="Align left"\n size="sm"\n value="left"\n onClick={() => applyHorizontalAlignment("left")}\n >\n <HugeiconsIcon\n icon={TextAlignLeft01Icon}\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align center">\n <ToggleGroupItem\n aria-label="Align center"\n size="sm"\n value="center"\n onClick={() => applyHorizontalAlignment("center")}\n >\n <HugeiconsIcon\n icon={TextAlignCenterIcon}\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align right">\n <ToggleGroupItem\n aria-label="Align right"\n size="sm"\n value="right"\n onClick={() => applyHorizontalAlignment("right")}\n >\n <HugeiconsIcon\n icon={TextAlignRight01Icon}\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n </ToggleGroup>\n <ToggleGroup\n className="shrink-0"\n disabled={!canStyleSelection}\n spacing="default"\n value={verticalAlignmentValue}\n >\n <ToolbarTooltip label="Align top">\n <ToggleGroupItem\n aria-label="Align top"\n size="sm"\n value="top"\n onClick={() => applyVerticalAlignment("top")}\n >\n <HugeiconsIcon\n icon={AlignBoxTopCenterIcon}\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align middle">\n <ToggleGroupItem\n aria-label="Align middle"\n size="sm"\n value="center"\n onClick={() => applyVerticalAlignment("center")}\n >\n <HugeiconsIcon\n icon={AlignBoxMiddleCenterIcon}\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align bottom">\n <ToggleGroupItem\n aria-label="Align bottom"\n size="sm"\n value="bottom"\n onClick={() => applyVerticalAlignment("bottom")}\n >\n <HugeiconsIcon\n icon={AlignBoxBottomCenterIcon}\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n </ToggleGroup>\n <ToolbarIconButton\n label="Wrap text"\n disabled={!canStyleSelection}\n onClick={() => applyStyle({ alignment: { wrapText: true } })}\n >\n <HugeiconsIcon icon={TextWrapIcon} className="size-4" />\n </ToolbarIconButton>\n <AlignmentMoreMenu\n disabled={!canStyleSelection}\n onApplyStyle={applyStyle}\n />\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <NumberFormatSelect\n disabled={!canStyleSelection}\n onApplyStyle={applyStyle}\n value={numberFormatValue}\n />\n <BorderMenu\n borderColor={borderColor}\n disabled={!canStyleSelection}\n onApplyBorder={applyBorderAction}\n onBorderColorChange={setBorderColor}\n />\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <MergeCellsMenu\n canMerge={canMergeSelectedCells}\n canMergeAcross={canMergeAcross}\n canUnmerge={canUnmergeSelectedCells}\n disabled={!hasSelection || readOnly}\n isMerged={selectionIntersectsMerge}\n onMergeAcross={mergeAcrossSelectedCells}\n onMergeAndCenter={mergeAndCenterSelectedCells}\n onMergeCells={mergeSelectedCells}\n onUnmergeCells={unmergeSelectedCells}\n />\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarTooltip label="Add sheet">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Add sheet"\n disabled={!hasWorkbook || readOnly}\n onClick={() => addSheet()}\n >\n <HugeiconsIcon icon={Add01Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Remove active sheet">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Remove active sheet"\n disabled={sheets.length <= 1 || readOnly}\n onClick={removeActiveSheet}\n >\n <HugeiconsIcon icon={Delete02Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(activeSheetIndex)}\n onValueChange={(value) => setActiveSheetIndex(Number(value))}\n disabled={!hasWorkbook}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[150px] min-w-[150px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Active sheet"\n >\n <SelectValue>{activeSheet?.name ?? "Sheet"}</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="start"\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {sheets.map((sheet, index) => (\n <SelectItem\n key={`${sheet.name}-${index}`}\n value={String(index)}\n >\n {sheet.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <ToolbarSeparator />\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!hasWorkbook || !canZoomOut}\n aria-label="Zoom out"\n onClick={zoomOut}\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={currentZoom.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={!hasWorkbook}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[84px] min-w-[84px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Zoom level"\n >\n <SelectValue>{currentZoom}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="end"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\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={!hasWorkbook || !canZoomIn}\n aria-label="Zoom in"\n onClick={zoomIn}\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n </div>\n <div className="border-t bg-background px-2 py-1">\n <Group className="w-full">\n <Input\n className={cn(\n "h-8 w-[92px] shrink-0 font-mono text-xs",\n XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS\n )}\n readOnly\n value={activeCellAddress ?? ""}\n />\n <GroupSeparator />\n <GroupText className="h-8 w-9 shrink-0 justify-center px-0 text-[11px] font-semibold italic">\n fx\n </GroupText>\n <GroupSeparator />\n <Input\n className={cn(\n "h-8 flex-1",\n XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS\n )}\n disabled={!hasActiveCell || readOnly}\n value={formulaDraft}\n onBlur={() => {\n commitFormula()\n setFormulaFocused(false)\n }}\n onChange={(event) => setFormulaDraft(event.target.value)}\n onFocus={() => {\n formulaEditCellRef.current = activeCell\n formulaInitialValueRef.current = formulaDraft\n setFormulaFocused(true)\n }}\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n event.preventDefault()\n commitFormula()\n setFormulaFocused(false)\n }\n }}\n placeholder="Select a cell, then enter a value or formula"\n />\n </Group>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function XlsxEditorSurface({\n className,\n isDark,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showNightRenderToggle,\n workbookIdentity,\n}: {\n className?: string\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showNightRenderToggle: boolean\n workbookIdentity: string\n}) {\n const { error } = useXlsxViewer()\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 <EditorToolbar\n isDark={isDark}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n showNightRenderToggle={showNightRenderToggle}\n workbookIdentity={workbookIdentity}\n />\n <div className="flex min-h-0 flex-1 flex-col">\n <div className="min-h-0 flex-1 bg-muted/20">\n <XlsxViewer\n allowResizeInReadOnly\n className="h-full min-h-0 min-w-0"\n height="100%"\n isDark={isDark}\n readOnly={false}\n rounded={false}\n showDefaultToolbar={false}\n showImages\n fileTooLargeState={\n <div className="grid h-full w-full min-w-full place-items-center p-6">\n <div className="max-w-sm rounded-lg border bg-background p-4 text-sm">\n <p className="font-medium">File too large for editing</p>\n <p className="mt-1 text-muted-foreground">\n This workbook exceeds the editor limit. Download it or open\n a smaller file to make changes.\n </p>\n </div>\n </div>\n }\n loadingState={<EditorLoadingSurface />}\n renderScroller={renderXlsxScroller}\n errorState={\n <div className="grid h-full w-full min-w-full place-items-center p-6 text-sm text-destructive">\n {error?.message ?? "Unable to edit workbook."}\n </div>\n }\n renderTableHeaderMenu={renderTableHeaderMenu}\n />\n </div>\n <WorkbookSheetTabs workbookIdentity={workbookIdentity} />\n </div>\n </div>\n )\n}\n\nexport function XlsxEditorPreview({\n className,\n fileName,\n isDark,\n onIsDarkChange,\n src,\n}: {\n className?: string\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n src?: string\n}) {\n return (\n <XlsxEditorContent\n className={className}\n effectiveIsDark={isDark}\n fileName={fileName}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction XlsxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n setNightRenderEnabled,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const [uploadedWorkbook, setUploadedWorkbook] =\n React.useState<UploadedWorkbook | null>(null)\n const [workbookBuffer, setWorkbookBuffer] =\n React.useState<ArrayBuffer | null>(null)\n const [loadError, setLoadError] = React.useState<string>()\n const sourceFileName = React.useMemo(\n () =>\n url ? formatWorkbookName(fileName, url) : (fileName ?? "workbook.xlsx"),\n [fileName, url]\n )\n const displayFileName = uploadedWorkbook?.fileName ?? sourceFileName\n const workbookIdentity =\n uploadedWorkbook?.identity ?? `${url ?? "empty"}::${displayFileName}`\n const shouldShowLoadingSpinner = useDelayedLoadingIndicator(\n !workbookBuffer && !loadError && !uploadedWorkbook,\n XLSX_LOADING_INDICATOR_DELAY_MS\n )\n\n React.useEffect(() => {\n let isCurrent = true\n\n if (url) {\n setUploadedWorkbook(null)\n }\n\n async function loadWorkbook(): Promise<void> {\n if (!url) {\n setWorkbookBuffer(null)\n setLoadError(undefined)\n return\n }\n\n setWorkbookBuffer(null)\n setLoadError(undefined)\n\n try {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch XLSX (${response.status})`)\n }\n\n const nextWorkbookBuffer = await response.arrayBuffer()\n if (!isCurrent) return\n\n setWorkbookBuffer(nextWorkbookBuffer)\n } catch (error) {\n if (!isCurrent) return\n\n setLoadError(\n error instanceof Error ? error.message : "Unknown XLSX load error"\n )\n }\n }\n\n void loadWorkbook()\n\n return () => {\n isCurrent = false\n }\n }, [url])\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 const buffer = await file.arrayBuffer()\n setWorkbookBuffer(null)\n setLoadError(undefined)\n setUploadedWorkbook({\n buffer,\n fileName: file.name,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n const activeBuffer = uploadedWorkbook?.buffer ?? workbookBuffer\n\n if (!url && !uploadedWorkbook) {\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=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <div className="grid min-h-0 flex-1 place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs">\n <p className="font-medium">Upload a workbook to edit</p>\n <p className="mt-1 text-muted-foreground">\n Pass an XLSX URL with the <code>src</code> prop or upload a local\n file.\n </p>\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 XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (loadError && !activeBuffer) {\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=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <div className="grid min-h-0 flex-1 place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm">\n <p className="font-medium">Unable to edit workbook</p>\n <p className="mt-1 text-muted-foreground">{loadError}</p>\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 XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (!activeBuffer) {\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=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <EditorLoadingSurface showSpinner={shouldShowLoadingSpinner} />\n </div>\n )\n }\n\n return (\n <div className={cn("overflow-hidden", className)}>\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <XlsxWorkbookLoadedEditor\n fileName={displayFileName}\n isDark={effectiveIsDark}\n onIsDarkChange={setNightRenderEnabled}\n onUploadClick={() => fileInputRef.current?.click()}\n renderTableHeaderMenu={(props) => (\n <WorkbookTableHeaderMenu {...props} />\n )}\n showNightRenderToggle={shouldRenderNightMode}\n workbookBuffer={activeBuffer}\n workbookIdentity={workbookIdentity}\n />\n </div>\n )\n}\n\nfunction XlsxWorkbookLoadedEditor({\n fileName,\n isDark,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showNightRenderToggle,\n workbookBuffer,\n workbookIdentity,\n}: {\n fileName: string\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showNightRenderToggle: boolean\n workbookBuffer: ArrayBuffer\n workbookIdentity: string\n}) {\n const controller = useXlsxViewerController(\n React.useMemo(\n () => ({\n allowResizeInReadOnly: true,\n file: workbookBuffer,\n fileName,\n readOnly: false,\n readOnlyAboveBytes: XLSX_EDITOR_READ_ONLY_THRESHOLD_BYTES,\n useWorker: true,\n }),\n [fileName, workbookBuffer]\n )\n )\n\n return (\n <XlsxViewerProvider controller={controller} isDark={isDark}>\n <XlsxEditorSurface\n isDark={isDark}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n renderTableHeaderMenu={renderTableHeaderMenu}\n showNightRenderToggle={showNightRenderToggle}\n workbookIdentity={workbookIdentity}\n />\n </XlsxViewerProvider>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n useXlsxViewer,\n useXlsxViewerController,\n useXlsxViewerEditing,\n useXlsxViewerSelection,\n useXlsxViewerZoom,\n XlsxViewer,\n XlsxViewerProvider,\n type XlsxCellAlignmentInput,\n type XlsxCellBorderEdgeInput,\n type XlsxCellRange,\n type XlsxCellStyleInput,\n type XlsxSheetData,\n type XlsxTableHeaderMenuRenderProps,\n} from "@extend-ai/react-xlsx"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport { ColorPicker, ColorPickerPanel } from "@/components/ui/color-picker"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuGroup,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuSub,\n DropdownMenuSubContent,\n DropdownMenuSubTrigger,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { Group, GroupSeparator, GroupText } from "@/components/ui/group"\nimport { Input } from "@/components/ui/input"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport {\n renderXlsxScroller,\n WorkbookSheetTabs,\n WorkbookTableHeaderMenu,\n} from "@/components/extend/xlsx-viewer"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nfunction BorderAll01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Grid2x2"\n tabler="IconBorderAll"\n hugeicons="BorderAll01Icon"\n phosphor="GridFourIcon"\n remixicon="RiGridLine"\n {...props}\n />\n )\n}\n\nfunction BorderBottom01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelBottom"\n tabler="IconBorderBottom"\n hugeicons="BorderBottom01Icon"\n phosphor="SquareHalfBottomIcon"\n remixicon="RiLayoutBottomLine"\n {...props}\n />\n )\n}\n\nfunction BorderLeft01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelLeft"\n tabler="IconBorderLeft"\n hugeicons="BorderLeft01Icon"\n phosphor="SquareHalfIcon"\n remixicon="RiLayoutLeftLine"\n {...props}\n />\n )\n}\n\nfunction BorderNone01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="SquareDashed"\n tabler="IconBorderNone"\n hugeicons="BorderNone01Icon"\n phosphor="SelectionIcon"\n remixicon="RiCheckboxBlankLine"\n {...props}\n />\n )\n}\n\nfunction BorderRight01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelRight"\n tabler="IconBorderRight"\n hugeicons="BorderRight01Icon"\n phosphor="SquareHalfIcon"\n remixicon="RiLayoutRightLine"\n {...props}\n />\n )\n}\n\nfunction BorderTop01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelTop"\n tabler="IconBorderTop"\n hugeicons="BorderTop01Icon"\n phosphor="AlignTopSimpleIcon"\n remixicon="RiLayoutTopLine"\n {...props}\n />\n )\n}\n\nfunction Calendar03Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Calendar"\n tabler="IconCalendar"\n hugeicons="Calendar03Icon"\n phosphor="CalendarIcon"\n remixicon="RiCalendarLine"\n {...props}\n />\n )\n}\n\nfunction DollarCircleGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="CircleDollarSign"\n tabler="IconCurrencyDollar"\n hugeicons="DollarCircleIcon"\n phosphor="CurrencyCircleDollarIcon"\n remixicon="RiMoneyDollarCircleLine"\n {...props}\n />\n )\n}\n\nfunction Moon02Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Moon"\n tabler="IconMoon"\n hugeicons="Moon02Icon"\n phosphor="MoonIcon"\n remixicon="RiMoonLine"\n {...props}\n />\n )\n}\n\nfunction PaintBucketGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PaintBucket"\n tabler="IconPaint"\n hugeicons="PaintBucketIcon"\n phosphor="PaintBucketIcon"\n remixicon="RiPaintFill"\n {...props}\n />\n )\n}\n\nfunction PercentGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Percent"\n tabler="IconPercentage"\n hugeicons="PercentIcon"\n phosphor="PercentIcon"\n remixicon="RiPercentLine"\n {...props}\n />\n )\n}\n\nfunction Sun03Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Sun"\n tabler="IconSun"\n hugeicons="Sun03Icon"\n phosphor="SunIcon"\n remixicon="RiSunLine"\n {...props}\n />\n )\n}\n\nfunction TextColorGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Baseline"\n tabler="IconTextColor"\n hugeicons="TextColorIcon"\n phosphor="TextAaIcon"\n remixicon="RiFontColor"\n {...props}\n />\n )\n}\n\nfunction TextNumberSignGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Hash"\n tabler="IconHash"\n hugeicons="TextNumberSignIcon"\n phosphor="HashIcon"\n remixicon="RiHashtag"\n {...props}\n />\n )\n}\n\nfunction TextWrapGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="WrapText"\n tabler="IconTextWrap"\n hugeicons="TextWrapIcon"\n phosphor="ArrowElbowDownLeftIcon"\n remixicon="RiTextWrap"\n {...props}\n />\n )\n}\n\nconst XLSX_LOADING_INDICATOR_DELAY_MS = 300\nconst XLSX_EDITOR_READ_ONLY_THRESHOLD_BYTES = 5 * 1024 * 1024\nconst XLSX_DROPDOWN_Z_INDEX_CLASS = "z-40"\nconst ZOOM_OPTIONS = [50, 75, 100, 125, 150, 200, 400] as const\nconst DEFAULT_FONT_FAMILY = "Arial"\nconst FONT_FAMILIES = [\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 DEFAULT_TEXT_COLOR = "#111827"\nconst DEFAULT_FILL_COLOR = "#fde68a"\nconst DEFAULT_BORDER_COLOR = "#111827"\nconst XLSX_EDITOR_SELECT_CHROME_CLASS =\n "shadow-none before:shadow-none not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-none dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-none"\nconst XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS =\n "has-disabled:opacity-100 dark:has-disabled:before:shadow-[0_-1px_--theme(--color-white/6%)]"\n\ntype UploadedWorkbook = {\n buffer: ArrayBuffer\n fileName: string\n identity: string\n}\n\ntype NumberFormatOption = {\n formatString?: string\n formatType: NonNullable<XlsxCellStyleInput["numberFormat"]>["formatType"]\n icon: React.ComponentType<React.ComponentProps<"svg">>\n id?: number\n label: string\n value: string\n}\n\ntype BorderOption = {\n action: XlsxBorderAction\n icon: React.ComponentType<React.ComponentProps<"svg">>\n label: string\n}\n\ntype XlsxResolvedCellStyle = XlsxSheetData["styleById"][number]\ntype XlsxResolvedStyleGroup = Record<string, unknown>\n\ntype HorizontalAlignment = NonNullable<XlsxCellAlignmentInput["horizontal"]>\n\ntype VerticalAlignment = NonNullable<XlsxCellAlignmentInput["vertical"]>\n\ntype HorizontalAlignmentToggleValue = Extract<\n HorizontalAlignment,\n "left" | "center" | "right"\n>\n\ntype VerticalAlignmentToggleValue = Extract<\n VerticalAlignment,\n "top" | "center" | "bottom"\n>\n\ntype XlsxFontToggleValue = "bold" | "italic" | "underline" | "strikethrough"\n\ntype XlsxMergeRegion = XlsxCellRange\n\ntype XlsxBorderEdgeKey = "bottom" | "left" | "top" | "right"\n\ntype XlsxBorderAction = "all" | "outside" | "none" | XlsxBorderEdgeKey\n\ntype XlsxWorksheetWithMergeRegions = {\n mergedRegions?: unknown[]\n unmergeCells?: (range: string) => boolean\n}\n\nconst NUMBER_FORMAT_OPTIONS: NumberFormatOption[] = [\n {\n formatType: "general",\n icon: TextNumberSignGlyph,\n label: "General",\n value: "General",\n },\n {\n formatString: "0.00",\n formatType: "custom",\n icon: TextNumberSignGlyph,\n label: "Number",\n value: "Number",\n },\n {\n formatString: "$#,##0.00",\n formatType: "custom",\n icon: DollarCircleGlyph,\n label: "Currency",\n value: "Currency",\n },\n {\n formatString: "0.00%",\n formatType: "custom",\n icon: PercentGlyph,\n label: "Percent",\n value: "Percent",\n },\n {\n formatString: "m/d/yyyy",\n formatType: "custom",\n icon: Calendar03Glyph,\n label: "Date",\n value: "Date",\n },\n]\n\nconst GENERAL_NUMBER_FORMAT_VALUE = "General"\nconst BUILTIN_NUMBER_FORMAT_VALUE_PREFIX = "builtin:"\n\nfunction formatWorkbookName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "workbook.xlsx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\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 normalizeHexColor(value: string, fallback = DEFAULT_TEXT_COLOR) {\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 toXlsxRgbColor(value: string) {\n return {\n colorType: "rgb" as const,\n hex: normalizeHexColor(value).slice(1).toUpperCase(),\n }\n}\n\nfunction asResolvedStyleGroup(\n value: unknown\n): XlsxResolvedStyleGroup | undefined {\n return value && typeof value === "object" && !Array.isArray(value)\n ? (value as XlsxResolvedStyleGroup)\n : undefined\n}\n\nfunction mergeResolvedCellStyle(\n base: XlsxResolvedCellStyle | null | undefined,\n overlay: XlsxResolvedCellStyle | null | undefined\n): XlsxResolvedCellStyle | null {\n if (!base && !overlay) return null\n\n const nextStyle = { ...(base ?? {}), ...(overlay ?? {}) }\n const baseFont = asResolvedStyleGroup(base?.font)\n const overlayFont = asResolvedStyleGroup(overlay?.font)\n\n if (baseFont || overlayFont) {\n nextStyle.font = overlayFont ?? baseFont\n }\n\n return nextStyle\n}\n\nfunction resolveInheritedCellStyle(\n sheet: XlsxSheetData | null,\n row: number,\n col: number\n): XlsxResolvedCellStyle | null {\n if (!sheet) return null\n\n const colStyleId = sheet.colStyleIds[col]\n const rowStyleId = sheet.rowStyleIds[row]\n const colStyle =\n colStyleId !== undefined ? sheet.styleById[colStyleId] : undefined\n const rowStyle =\n rowStyleId !== undefined ? sheet.styleById[rowStyleId] : undefined\n\n return mergeResolvedCellStyle(colStyle, rowStyle)\n}\n\nfunction getFontToggleValuesFromStyle(\n style: XlsxResolvedCellStyle | null\n): XlsxFontToggleValue[] {\n const font = asResolvedStyleGroup(style?.font)\n const values: XlsxFontToggleValue[] = []\n\n if (font?.bold === true) values.push("bold")\n if (font?.italic === true) values.push("italic")\n if (font?.underline && font.underline !== "none") values.push("underline")\n if (font?.strikethrough === true) values.push("strikethrough")\n\n return values\n}\n\nfunction getFontFamilyValue(style: XlsxResolvedCellStyle | null) {\n const font = asResolvedStyleGroup(style?.font)\n const fontName = font?.name\n\n return typeof fontName === "string" && fontName.trim()\n ? fontName.trim()\n : undefined\n}\n\nfunction getHorizontalAlignmentValue(\n style: XlsxResolvedCellStyle | null\n): HorizontalAlignmentToggleValue[] {\n const alignment = asResolvedStyleGroup(style?.alignment)\n const horizontal = alignment?.horizontal\n\n return horizontal === "left" ||\n horizontal === "center" ||\n horizontal === "right"\n ? [horizontal]\n : []\n}\n\nfunction getVerticalAlignmentValue(\n style: XlsxResolvedCellStyle | null\n): VerticalAlignmentToggleValue[] {\n const alignment = asResolvedStyleGroup(style?.alignment)\n const vertical = alignment?.vertical\n\n if (vertical === undefined || vertical === null) return ["bottom"]\n\n return vertical === "top" || vertical === "center" || vertical === "bottom"\n ? [vertical]\n : []\n}\n\nfunction getNumberFormatValue(style: XlsxResolvedCellStyle | null) {\n const numberFormat = asResolvedStyleGroup(style?.numberFormat)\n\n if (!numberFormat) return GENERAL_NUMBER_FORMAT_VALUE\n\n const formatType = numberFormat.formatType\n const formatString =\n typeof numberFormat.formatString === "string"\n ? numberFormat.formatString.trim()\n : ""\n const id = getNumericValue(numberFormat.id)\n\n if (formatString) {\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.formatString === formatString\n )\n\n return matchingOption?.value ?? formatString\n }\n if (formatType === "builtin" && id !== undefined) {\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.id === id\n )\n\n if (matchingOption) return matchingOption.value\n\n return `${BUILTIN_NUMBER_FORMAT_VALUE_PREFIX}${id}`\n }\n if (formatType === "general") return GENERAL_NUMBER_FORMAT_VALUE\n\n return GENERAL_NUMBER_FORMAT_VALUE\n}\n\nfunction getNumberFormatLabel(value: string) {\n if (value === GENERAL_NUMBER_FORMAT_VALUE) return "General"\n\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.value === value\n )\n if (matchingOption) return matchingOption.label\n\n if (value.startsWith(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX)) {\n return `Builtin ${value.slice(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX.length)}`\n }\n\n return value\n}\n\nfunction getNumberFormatIcon(value: string) {\n return (\n NUMBER_FORMAT_OPTIONS.find((option) => option.value === value)?.icon ??\n TextNumberSignGlyph\n )\n}\n\nfunction createNumberFormatStyle(value: string): XlsxCellStyleInput {\n const matchingOption = NUMBER_FORMAT_OPTIONS.find(\n (option) => option.value === value\n )\n\n if (matchingOption) {\n return {\n numberFormat: {\n formatString: matchingOption.formatString,\n formatType: matchingOption.formatType,\n id: matchingOption.id,\n },\n }\n }\n\n if (value.startsWith(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX)) {\n const id = Number(value.slice(BUILTIN_NUMBER_FORMAT_VALUE_PREFIX.length))\n\n if (Number.isFinite(id)) {\n return {\n numberFormat: {\n formatType: "builtin",\n id: Math.max(0, Math.trunc(id)),\n },\n }\n }\n }\n\n return {\n numberFormat: {\n formatString: value,\n formatType: "custom",\n },\n }\n}\n\nfunction normalizeCellRange(range: XlsxCellRange): XlsxCellRange {\n return {\n start: {\n row: Math.min(range.start.row, range.end.row),\n col: Math.min(range.start.col, range.end.col),\n },\n end: {\n row: Math.max(range.start.row, range.end.row),\n col: Math.max(range.start.col, range.end.col),\n },\n }\n}\n\nfunction getNumericValue(value: unknown) {\n return typeof value === "number" && Number.isFinite(value)\n ? Math.max(0, Math.trunc(value))\n : undefined\n}\n\nfunction getWorksheetMergeRegions(\n worksheet: XlsxWorksheetWithMergeRegions | null\n): XlsxMergeRegion[] {\n if (!Array.isArray(worksheet?.mergedRegions)) return []\n\n return worksheet.mergedRegions.flatMap((entry) => {\n if (!entry || typeof entry !== "object") return []\n\n const region = entry as Record<string, unknown>\n const start = asResolvedStyleGroup(region.start)\n const end = asResolvedStyleGroup(region.end)\n const startRow = getNumericValue(region.startRow ?? start?.row)\n const startCol = getNumericValue(region.startCol ?? start?.col)\n const endRow = getNumericValue(region.endRow ?? end?.row)\n const endCol = getNumericValue(region.endCol ?? end?.col)\n\n if (\n startRow === undefined ||\n startCol === undefined ||\n endRow === undefined ||\n endCol === undefined\n ) {\n return []\n }\n\n return [\n normalizeCellRange({\n start: { row: startRow, col: startCol },\n end: { row: endRow, col: endCol },\n }),\n ]\n })\n}\n\nfunction rangesIntersect(\n firstRange: XlsxCellRange,\n secondRange: XlsxCellRange\n) {\n const first = normalizeCellRange(firstRange)\n const second = normalizeCellRange(secondRange)\n\n return (\n first.start.row <= second.end.row &&\n first.end.row >= second.start.row &&\n first.start.col <= second.end.col &&\n first.end.col >= second.start.col\n )\n}\n\nfunction isSingleCellRange(range: XlsxCellRange) {\n const normalizedRange = normalizeCellRange(range)\n\n return (\n normalizedRange.start.row === normalizedRange.end.row &&\n normalizedRange.start.col === normalizedRange.end.col\n )\n}\n\nfunction getCellColumnLabel(col: number) {\n let label = ""\n let value = col\n\n do {\n label = String.fromCharCode(65 + (value % 26)) + label\n value = Math.floor(value / 26) - 1\n } while (value >= 0)\n\n return label\n}\n\nfunction cellAddressToA1(cell: XlsxCellRange["start"]) {\n return `${getCellColumnLabel(cell.col)}${cell.row + 1}`\n}\n\nfunction rangeToA1(range: XlsxCellRange) {\n const normalizedRange = normalizeCellRange(range)\n\n return `${cellAddressToA1(normalizedRange.start)}:${cellAddressToA1(\n normalizedRange.end\n )}`\n}\n\nfunction getRangeKey(range: XlsxCellRange) {\n const normalizedRange = normalizeCellRange(range)\n\n return `${normalizedRange.start.row}:${normalizedRange.start.col}:${normalizedRange.end.row}:${normalizedRange.end.col}`\n}\n\nfunction createBorderEdge(\n color = DEFAULT_BORDER_COLOR\n): XlsxCellBorderEdgeInput {\n return {\n color: toXlsxRgbColor(color),\n style: "thin",\n }\n}\n\nfunction createBorderPatch(\n entries: Partial<Record<XlsxBorderEdgeKey, XlsxCellBorderEdgeInput>>\n): XlsxCellStyleInput {\n return {\n border: entries,\n }\n}\n\nfunction createNoBorderPatch(): XlsxCellStyleInput {\n return {\n border: {\n bottom: { style: "none" },\n left: { style: "none" },\n right: { style: "none" },\n top: { style: "none" },\n },\n }\n}\n\nfunction createBorderOptions(): BorderOption[] {\n return [\n {\n action: "bottom",\n icon: BorderBottom01Glyph,\n label: "Bottom border",\n },\n {\n action: "left",\n icon: BorderLeft01Glyph,\n label: "Left border",\n },\n {\n action: "top",\n icon: BorderTop01Glyph,\n label: "Top border",\n },\n {\n action: "right",\n icon: BorderRight01Glyph,\n label: "Right border",\n },\n {\n action: "all",\n icon: BorderAll01Glyph,\n label: "All borders",\n },\n {\n action: "outside",\n icon: BorderAll01Glyph,\n label: "Outside border",\n },\n {\n action: "none",\n icon: BorderNone01Glyph,\n label: "No border",\n },\n ]\n}\n\nfunction getBorderEdgeRange(\n range: XlsxCellRange,\n edgeKey: XlsxBorderEdgeKey\n): XlsxCellRange {\n const normalizedRange = normalizeCellRange(range)\n\n if (edgeKey === "top") {\n return {\n start: normalizedRange.start,\n end: { row: normalizedRange.start.row, col: normalizedRange.end.col },\n }\n }\n\n if (edgeKey === "bottom") {\n return {\n start: { row: normalizedRange.end.row, col: normalizedRange.start.col },\n end: normalizedRange.end,\n }\n }\n\n if (edgeKey === "left") {\n return {\n start: normalizedRange.start,\n end: { row: normalizedRange.end.row, col: normalizedRange.start.col },\n }\n }\n\n return {\n start: { row: normalizedRange.start.row, col: normalizedRange.end.col },\n end: normalizedRange.end,\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 w-full min-w-full 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 ToolbarSeparator() {\n return <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n}\n\nfunction StyleDropdownItem({\n children,\n icon,\n onClick,\n}: {\n children: React.ReactNode\n icon: React.ComponentType<React.ComponentProps<"svg">>\n onClick: () => void\n}) {\n const IconComponent = icon\n return (\n <DropdownMenuItem onClick={onClick}>\n <IconComponent className="size-4" />\n {children}\n </DropdownMenuItem>\n )\n}\n\nfunction MergeCellsMenu({\n canMerge,\n canMergeAcross,\n canUnmerge,\n disabled,\n isMerged,\n onMergeAcross,\n onMergeAndCenter,\n onMergeCells,\n onUnmergeCells,\n}: {\n canMerge: boolean\n canMergeAcross: boolean\n canUnmerge: boolean\n disabled: boolean\n isMerged: boolean\n onMergeAcross: () => void\n onMergeAndCenter: () => void\n onMergeCells: () => void\n onUnmergeCells: () => void\n}) {\n return (\n <DropdownMenu>\n <div\n className={cn(\n "inline-flex shrink-0 overflow-hidden rounded-lg border border-transparent"\n )}\n >\n <ToolbarTooltip\n label={isMerged ? "Unmerge cells from the menu" : "Merge & Center"}\n >\n <Button\n type="button"\n variant={isMerged ? "secondary" : "ghost"}\n size="sm"\n aria-label="Merge & Center"\n className="h-7 rounded-r-none border-0 px-2.5 before:rounded-r-none"\n data-pressed={isMerged ? "" : undefined}\n disabled={disabled || !canMerge}\n onClick={onMergeAndCenter}\n >\n <IconPlaceholder\n lucide="TableCellsMerge"\n tabler="IconArrowMerge"\n hugeicons="PathfinderMergeIcon"\n phosphor="ArrowsMergeIcon"\n remixicon="RiMergeCellsVertical"\n className="size-4"\n />\n <span className="hidden text-xs font-medium lg:inline">\n Merge & Center\n </span>\n </Button>\n </ToolbarTooltip>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant={isMerged ? "secondary" : "ghost"}\n size="icon-sm"\n aria-label="Merge cells options"\n className="h-7 w-6 rounded-l-none border-0 px-0 before:rounded-l-none"\n data-pressed={isMerged ? "" : undefined}\n disabled={disabled}\n >\n <IconPlaceholder\n lucide="ChevronDown"\n tabler="IconChevronDown"\n hugeicons="ChevronDownIcon"\n phosphor="CaretDownIcon"\n remixicon="RiArrowDownSLine"\n className="size-3.5 opacity-100"\n />\n </Button>\n </DropdownMenuTrigger>\n </div>\n <DropdownMenuContent\n align="start"\n className={cn("w-56", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <DropdownMenuItem disabled={!canMerge} onClick={onMergeAndCenter}>\n <IconPlaceholder\n lucide="TableCellsMerge"\n tabler="IconArrowMerge"\n hugeicons="PathfinderMergeIcon"\n phosphor="ArrowsMergeIcon"\n remixicon="RiMergeCellsVertical"\n className="size-4"\n />\n Merge & Center\n </DropdownMenuItem>\n <DropdownMenuItem disabled={!canMergeAcross} onClick={onMergeAcross}>\n <IconPlaceholder\n lucide="TableRowsSplit"\n tabler="IconArrowsSplit"\n hugeicons="TableRowsSplitIcon"\n phosphor="ArrowsSplitIcon"\n remixicon="RiSplitCellsVertical"\n className="size-4"\n />\n Merge Across\n </DropdownMenuItem>\n <DropdownMenuItem disabled={!canMerge} onClick={onMergeCells}>\n <IconPlaceholder\n lucide="Grid3x3"\n tabler="IconGrid4x4"\n hugeicons="CellsIcon"\n phosphor="GridNineIcon"\n remixicon="RiMergeCellsHorizontal"\n className="size-4"\n />\n Merge Cells\n </DropdownMenuItem>\n <DropdownMenuSeparator />\n <DropdownMenuItem disabled={!canUnmerge} onClick={onUnmergeCells}>\n <IconPlaceholder\n lucide="Grid2x2X"\n tabler="IconTableMinus"\n hugeicons="Grid2X2XIcon"\n phosphor="SelectionSlashIcon"\n remixicon="RiSplitCellsHorizontal"\n className="size-4"\n />\n Unmerge Cells\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction NumberFormatSelect({\n disabled,\n onApplyStyle,\n value,\n}: {\n disabled: boolean\n onApplyStyle: (style: XlsxCellStyleInput) => void\n value: string\n}) {\n const hasMatchingOption = NUMBER_FORMAT_OPTIONS.some(\n (option) => option.value === value\n )\n const currentLabel = getNumberFormatLabel(value)\n const currentIcon = React.createElement(getNumberFormatIcon(value), {\n className: "size-4",\n })\n\n return (\n <Select\n value={value}\n onValueChange={(nextValue) => {\n if (!nextValue) return\n onApplyStyle(createNumberFormatStyle(nextValue))\n }}\n disabled={disabled}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[132px] min-w-[132px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Number format"\n >\n {currentIcon}\n <SelectValue placeholder="General" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {NUMBER_FORMAT_OPTIONS.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n <span className="flex min-w-0 items-center gap-2">\n <option.icon className="size-4" />\n <span className="truncate">{option.label}</span>\n </span>\n </SelectItem>\n ))}\n {!hasMatchingOption && value !== GENERAL_NUMBER_FORMAT_VALUE ? (\n <SelectItem value={value}>\n <span className="flex min-w-0 items-center gap-2">\n {currentIcon}\n <span className="truncate">{currentLabel}</span>\n </span>\n </SelectItem>\n ) : null}\n </SelectContent>\n </Select>\n )\n}\n\nfunction BorderMenu({\n borderColor,\n disabled,\n onApplyBorder,\n onBorderColorChange,\n}: {\n borderColor: string\n disabled: boolean\n onApplyBorder: (action: XlsxBorderAction) => void\n onBorderColorChange: (color: string) => void\n}) {\n const borderOptions = React.useMemo(() => createBorderOptions(), [])\n const edgeBorderOptions = borderOptions.filter(\n (option) =>\n option.action === "bottom" ||\n option.action === "left" ||\n option.action === "top" ||\n option.action === "right"\n )\n const groupedBorderOptions = borderOptions.filter(\n (option) =>\n option.action === "all" ||\n option.action === "outside" ||\n option.action === "none"\n )\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={disabled}\n aria-label="Cell borders"\n className="relative"\n >\n <IconPlaceholder\n lucide="Grid2x2"\n tabler="IconBorderAll"\n hugeicons="BorderAll01Icon"\n phosphor="GridFourIcon"\n remixicon="RiGridLine"\n className="size-4"\n />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: borderColor }}\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align="start"\n className={cn("w-48", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n {edgeBorderOptions.map((option) => (\n <StyleDropdownItem\n key={option.label}\n icon={option.icon}\n onClick={() => onApplyBorder(option.action)}\n >\n {option.label}\n </StyleDropdownItem>\n ))}\n <DropdownMenuSeparator />\n <DropdownMenuGroup>\n {groupedBorderOptions.map((option) => (\n <StyleDropdownItem\n key={option.label}\n icon={option.icon}\n onClick={() => onApplyBorder(option.action)}\n >\n {option.label}\n </StyleDropdownItem>\n ))}\n </DropdownMenuGroup>\n <DropdownMenuSeparator />\n <DropdownMenuSub>\n <DropdownMenuSubTrigger>\n <IconPlaceholder\n lucide="Baseline"\n tabler="IconTextColor"\n hugeicons="TextColorIcon"\n phosphor="TextAaIcon"\n remixicon="RiFontColor"\n className="size-4 text-muted-foreground"\n />\n Border color\n <span\n className="h-3 w-5 rounded-full border border-border"\n style={{ backgroundColor: borderColor }}\n />\n </DropdownMenuSubTrigger>\n <DropdownMenuSubContent\n className={cn("w-64 p-2", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <ColorPickerPanel\n label="Border color"\n color={borderColor}\n onChange={(color) =>\n onBorderColorChange(normalizeHexColor(color))\n }\n />\n </DropdownMenuSubContent>\n </DropdownMenuSub>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction AlignmentMoreMenu({\n disabled,\n onApplyStyle,\n}: {\n disabled: boolean\n onApplyStyle: (style: XlsxCellStyleInput) => void\n}) {\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={disabled}\n aria-label="More alignment"\n >\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className="size-4"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align="start"\n className={cn("w-48", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <StyleDropdownItem\n icon={TextWrapGlyph}\n onClick={() => onApplyStyle({ alignment: { wrapText: false } })}\n >\n Do not wrap\n </StyleDropdownItem>\n <StyleDropdownItem\n icon={TextWrapGlyph}\n onClick={() => onApplyStyle({ alignment: { shrinkToFit: true } })}\n >\n Shrink to fit\n </StyleDropdownItem>\n <StyleDropdownItem\n icon={TextWrapGlyph}\n onClick={() => onApplyStyle({ alignment: { shrinkToFit: false } })}\n >\n Do not shrink\n </StyleDropdownItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction EditorFileActionsMenu({\n canExport,\n exportXlsx,\n onUploadClick,\n}: {\n canExport: boolean\n exportXlsx: () => void\n onUploadClick: () => void\n}) {\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open workbook actions"\n >\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className="size-4"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align="end"\n className={cn("w-40", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <DropdownMenuItem disabled={!canExport} onClick={exportXlsx}>\n <IconPlaceholder\n lucide="Download"\n tabler="IconDownload"\n hugeicons="Download01Icon"\n phosphor="DownloadSimpleIcon"\n remixicon="RiDownload2Line"\n className="size-4"\n />\n Download\n </DropdownMenuItem>\n <DropdownMenuItem onClick={onUploadClick}>\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction EditorToolbar({\n isDark,\n onIsDarkChange,\n onUploadClick,\n showNightRenderToggle,\n workbookIdentity,\n}: {\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n showNightRenderToggle: boolean\n workbookIdentity: string\n}) {\n const {\n activeSheet,\n activeSheetIndex,\n canExport,\n exportXlsx,\n getActiveWorksheet,\n revision,\n setActiveSheetIndex,\n sheets,\n } = useXlsxViewer()\n const { activeCell, activeCellAddress, selectRange, selection } =\n useXlsxViewerSelection()\n const {\n addSheet,\n canRedo,\n canUndo,\n mergeSelection,\n pasteStructuredClipboardData,\n readOnly,\n redo,\n removeActiveSheet,\n selectedFormula,\n selectedValue,\n setCellStyle,\n setCellFormula,\n setCellValue,\n setRangeStyle,\n setSelectedCellStyle,\n undo,\n unmergeSelection,\n } = useXlsxViewerEditing()\n const { canZoomIn, canZoomOut, setZoomScale, zoomIn, zoomOut, zoomScale } =\n useXlsxViewerZoom()\n const [formulaDraft, setFormulaDraft] = React.useState("")\n const [formulaFocused, setFormulaFocused] = React.useState(false)\n const [fontFamily, setFontFamily] = React.useState(DEFAULT_FONT_FAMILY)\n const [fontSize, setFontSize] = React.useState(11)\n const [textColor, setTextColor] = React.useState(DEFAULT_TEXT_COLOR)\n const [fillColor, setFillColor] = React.useState(DEFAULT_FILL_COLOR)\n const [borderColor, setBorderColor] = React.useState(DEFAULT_BORDER_COLOR)\n const [appliedMergeRegions, setAppliedMergeRegions] = React.useState<\n XlsxMergeRegion[]\n >([])\n const lastStyleTargetRef = React.useRef<{\n range: XlsxCellRange\n sheetIndex: number\n workbookIdentity: string\n } | null>(null)\n const formulaEditCellRef = React.useRef<typeof activeCell>(null)\n const formulaInitialValueRef = React.useRef("")\n const hasWorkbook = sheets.length > 0\n const hasSelection = Boolean(selection)\n const hasActiveCell = Boolean(activeCell)\n const canStyleSelection = (hasSelection || hasActiveCell) && !readOnly\n const activeRange = React.useMemo<XlsxCellRange | null>(() => {\n if (selection) return normalizeCellRange(selection)\n if (!activeCell) return null\n\n return {\n start: activeCell,\n end: activeCell,\n }\n }, [activeCell, selection])\n\n React.useEffect(() => {\n if (!activeRange) return\n\n lastStyleTargetRef.current = {\n range: activeRange,\n sheetIndex: activeSheetIndex,\n workbookIdentity,\n }\n }, [activeRange, activeSheetIndex, workbookIdentity])\n const worksheetMergeRegions = React.useMemo(() => {\n void revision\n\n return getWorksheetMergeRegions(\n getActiveWorksheet() as XlsxWorksheetWithMergeRegions | null\n )\n }, [getActiveWorksheet, revision])\n const mergeRegions = React.useMemo(\n () => [...worksheetMergeRegions, ...appliedMergeRegions],\n [appliedMergeRegions, worksheetMergeRegions]\n )\n const selectionIntersectsMerge = Boolean(\n activeRange &&\n mergeRegions.some((mergeRegion) =>\n rangesIntersect(activeRange, mergeRegion)\n )\n )\n\n React.useEffect(() => {\n if (\n appliedMergeRegions.length === 0 ||\n worksheetMergeRegions.length === 0\n ) {\n return\n }\n\n setAppliedMergeRegions((currentRegions) =>\n currentRegions.filter(\n (currentRegion) =>\n !worksheetMergeRegions.some((worksheetRegion) =>\n rangesIntersect(currentRegion, worksheetRegion)\n )\n )\n )\n }, [appliedMergeRegions.length, worksheetMergeRegions])\n\n React.useEffect(() => {\n setAppliedMergeRegions([])\n }, [activeSheetIndex])\n const selectionIsSingleCell = activeRange\n ? isSingleCellRange(activeRange)\n : true\n const selectionSpansMultipleColumns = activeRange\n ? activeRange.start.col !== activeRange.end.col\n : false\n const canMergeSelectedCells = Boolean(\n selection &&\n !readOnly &&\n !selectionIntersectsMerge &&\n !selectionIsSingleCell\n )\n const canMergeAcross = Boolean(\n selection &&\n !readOnly &&\n !selectionIntersectsMerge &&\n selectionSpansMultipleColumns\n )\n const canUnmergeSelectedCells = Boolean(\n selection && !readOnly && selectionIntersectsMerge\n )\n const currentZoom = Math.round(zoomScale)\n const selectedCellInputValue = selectedFormula || selectedValue\n\n React.useEffect(() => {\n if (formulaFocused) return\n setFormulaDraft(selectedCellInputValue)\n }, [formulaFocused, selectedCellInputValue, activeCellAddress])\n\n const activeCellStyle = React.useMemo(() => {\n // Worksheet style objects are mutable; revision invalidates this read after edits.\n void revision\n\n if (!activeCell) return null\n\n const worksheet = getActiveWorksheet()\n const inheritedStyle = resolveInheritedCellStyle(\n activeSheet,\n activeCell.row,\n activeCell.col\n )\n const cellStyle = worksheet?.getCellStyleAt(\n activeCell.row,\n activeCell.col\n ) as XlsxResolvedCellStyle | null | undefined\n\n return mergeResolvedCellStyle(inheritedStyle, cellStyle)\n }, [activeCell, activeSheet, getActiveWorksheet, revision])\n const fontToggleValues = React.useMemo(\n () => getFontToggleValuesFromStyle(activeCellStyle),\n [activeCellStyle]\n )\n const fontFamilyValue = getFontFamilyValue(activeCellStyle) ?? fontFamily\n const horizontalAlignmentValue = React.useMemo(\n () => getHorizontalAlignmentValue(activeCellStyle),\n [activeCellStyle]\n )\n const verticalAlignmentValue = React.useMemo(\n () => getVerticalAlignmentValue(activeCellStyle),\n [activeCellStyle]\n )\n const numberFormatValue = React.useMemo(\n () => getNumberFormatValue(activeCellStyle),\n [activeCellStyle]\n )\n\n const commitFormula = React.useCallback(() => {\n const targetCell = formulaEditCellRef.current ?? activeCell\n if (!targetCell) return\n if (formulaDraft === formulaInitialValueRef.current) return\n\n if (formulaDraft.trim().startsWith("=")) {\n setCellFormula(targetCell, formulaDraft)\n } else {\n setCellValue(targetCell, formulaDraft)\n }\n formulaInitialValueRef.current = formulaDraft\n }, [activeCell, formulaDraft, setCellFormula, setCellValue])\n\n const applyStyle = React.useCallback(\n (style: XlsxCellStyleInput) => {\n const applyRangeStyle = (range: XlsxCellRange) => {\n const normalizedRange = normalizeCellRange(range)\n const targetRanges = [\n normalizedRange,\n ...mergeRegions.filter((mergeRegion) =>\n rangesIntersect(normalizedRange, mergeRegion)\n ),\n ]\n const uniqueTargetRanges = new Map<string, XlsxCellRange>()\n\n targetRanges.forEach((targetRange) => {\n const normalizedTargetRange = normalizeCellRange(targetRange)\n uniqueTargetRanges.set(\n getRangeKey(normalizedTargetRange),\n normalizedTargetRange\n )\n })\n\n uniqueTargetRanges.forEach((targetRange) => {\n setRangeStyle(targetRange, style)\n })\n }\n\n if (selection) {\n const normalizedSelection = normalizeCellRange(selection)\n\n if (!isSingleCellRange(normalizedSelection)) {\n applyRangeStyle(normalizedSelection)\n return true\n }\n\n if (activeCell) {\n setSelectedCellStyle(style)\n return true\n }\n\n setCellStyle(normalizedSelection.start, style)\n return true\n }\n\n if (activeCell) {\n setSelectedCellStyle(style)\n return true\n }\n\n const fallbackTarget = lastStyleTargetRef.current\n const targetRange =\n fallbackTarget?.sheetIndex === activeSheetIndex &&\n fallbackTarget.workbookIdentity === workbookIdentity\n ? fallbackTarget.range\n : null\n\n if (!targetRange) return false\n\n if (isSingleCellRange(targetRange)) {\n setCellStyle(normalizeCellRange(targetRange).start, style)\n return true\n }\n\n applyRangeStyle(targetRange)\n return true\n },\n [\n activeCell,\n activeSheetIndex,\n mergeRegions,\n selection,\n setCellStyle,\n setRangeStyle,\n setSelectedCellStyle,\n workbookIdentity,\n ]\n )\n\n const applyBorderAction = React.useCallback(\n (action: XlsxBorderAction) => {\n if (!activeRange) return\n\n const normalizedRange = normalizeCellRange(activeRange)\n const edge = createBorderEdge(borderColor)\n const allBorderPatch = createBorderPatch({\n bottom: edge,\n left: edge,\n right: edge,\n top: edge,\n })\n\n if (action === "all") {\n setRangeStyle(normalizedRange, allBorderPatch)\n return\n }\n\n if (action === "none") {\n setRangeStyle(normalizedRange, createNoBorderPatch())\n return\n }\n\n if (action === "outside") {\n if (isSingleCellRange(normalizedRange)) {\n setCellStyle(normalizedRange.start, allBorderPatch)\n return\n }\n\n const outsideEdgeKeys: XlsxBorderEdgeKey[] = [\n "top",\n "bottom",\n "left",\n "right",\n ]\n\n outsideEdgeKeys.forEach((edgeKey) => {\n setRangeStyle(\n getBorderEdgeRange(normalizedRange, edgeKey),\n createBorderPatch({ [edgeKey]: edge })\n )\n })\n return\n }\n\n setRangeStyle(\n getBorderEdgeRange(normalizedRange, action),\n createBorderPatch({ [action]: edge })\n )\n },\n [activeRange, borderColor, setCellStyle, setRangeStyle]\n )\n\n const applyHorizontalAlignment = React.useCallback(\n (horizontal: HorizontalAlignmentToggleValue | undefined) => {\n if (!horizontal) return\n\n applyStyle({ alignment: { horizontal } })\n },\n [applyStyle]\n )\n\n const applyVerticalAlignment = React.useCallback(\n (vertical: VerticalAlignmentToggleValue | undefined) => {\n if (!vertical) return\n\n applyStyle({ alignment: { vertical } })\n },\n [applyStyle]\n )\n\n const mergeSelectedCells = React.useCallback(() => {\n if (!canMergeSelectedCells || !selection) return\n\n setAppliedMergeRegions([normalizeCellRange(selection)])\n mergeSelection()\n }, [canMergeSelectedCells, mergeSelection, selection])\n\n const mergeAcrossSelectedCells = React.useCallback(() => {\n if (!activeCell || !canMergeAcross || !selection) return\n\n const normalizedRange = normalizeCellRange(selection)\n const worksheet = getActiveWorksheet()\n if (!worksheet) return\n\n const formula = worksheet.getFormulaAt(activeCell.row, activeCell.col)\n const rawValue = worksheet.getCellAt(activeCell.row, activeCell.col).toJs()\n const colSpan = normalizedRange.end.col - normalizedRange.start.col + 1\n const rowSpan = normalizedRange.end.row - normalizedRange.start.row + 1\n const merges = Array.from({ length: rowSpan }, (_, rowOffset) => ({\n colOffset: normalizedRange.start.col - activeCell.col,\n colSpan,\n rowOffset: normalizedRange.start.row + rowOffset - activeCell.row,\n rowSpan: 1,\n }))\n const mergeRegionsByRow = Array.from({ length: rowSpan }, (_, rowOffset) =>\n normalizeCellRange({\n start: {\n col: normalizedRange.start.col,\n row: normalizedRange.start.row + rowOffset,\n },\n end: {\n col: normalizedRange.end.col,\n row: normalizedRange.start.row + rowOffset,\n },\n })\n )\n\n const didPaste = pasteStructuredClipboardData(\n JSON.stringify({\n cells: [\n formula\n ? { colOffset: 0, formula, rowOffset: 0 }\n : { colOffset: 0, rowOffset: 0, value: rawValue ?? "" },\n ],\n cols: colSpan,\n merges,\n rows: rowSpan,\n })\n )\n\n if (!didPaste) return\n\n setAppliedMergeRegions(mergeRegionsByRow)\n selectRange(normalizedRange)\n }, [\n activeCell,\n canMergeAcross,\n getActiveWorksheet,\n pasteStructuredClipboardData,\n selectRange,\n selection,\n ])\n\n const mergeAndCenterSelectedCells = React.useCallback(() => {\n if (!canMergeSelectedCells || !selection) return\n\n setAppliedMergeRegions([normalizeCellRange(selection)])\n setRangeStyle(selection, { alignment: { horizontal: "center" } })\n mergeSelection()\n }, [canMergeSelectedCells, mergeSelection, selection, setRangeStyle])\n\n const unmergeSelectedCells = React.useCallback(() => {\n if (!canUnmergeSelectedCells || !activeRange) return\n\n const worksheet =\n getActiveWorksheet() as XlsxWorksheetWithMergeRegions | null\n if (!worksheet?.unmergeCells) return\n\n const normalizedRange = normalizeCellRange(activeRange)\n const uniqueMergeRegions = new Map<string, XlsxMergeRegion>()\n\n ;[...worksheetMergeRegions, ...appliedMergeRegions].forEach(\n (mergeRegion) => {\n if (!rangesIntersect(normalizedRange, mergeRegion)) return\n\n uniqueMergeRegions.set(getRangeKey(mergeRegion), mergeRegion)\n }\n )\n\n let didUnmerge = false\n\n uniqueMergeRegions.forEach((mergeRegion) => {\n didUnmerge =\n worksheet.unmergeCells?.(rangeToA1(mergeRegion)) || didUnmerge\n })\n\n if (!didUnmerge) {\n unmergeSelection()\n return\n }\n\n setAppliedMergeRegions([])\n setRangeStyle(normalizedRange, {})\n selectRange(normalizedRange)\n }, [\n activeRange,\n appliedMergeRegions,\n canUnmergeSelectedCells,\n getActiveWorksheet,\n selectRange,\n setRangeStyle,\n unmergeSelection,\n worksheetMergeRegions,\n ])\n\n const applyFontToggleValues = React.useCallback(\n (nextValues: XlsxFontToggleValue[]) => {\n const previousValues = fontToggleValues\n const changedValue =\n nextValues.find((value) => !previousValues.includes(value)) ??\n previousValues.find((value) => !nextValues.includes(value))\n\n if (!changedValue) return\n\n const isPressed = nextValues.includes(changedValue)\n\n if (changedValue === "bold") {\n applyStyle({ font: { bold: isPressed } })\n } else if (changedValue === "italic") {\n applyStyle({ font: { italic: isPressed } })\n } else if (changedValue === "underline") {\n applyStyle({ font: { underline: isPressed ? "single" : "none" } })\n } else if (changedValue === "strikethrough") {\n applyStyle({ font: { strikethrough: isPressed } })\n }\n },\n [applyStyle, fontToggleValues]\n )\n\n return (\n <div className="border-b bg-background">\n <div className="flex min-h-11 items-center justify-between gap-3 border-b px-3">\n <div className="min-w-0 flex-1" />\n <TooltipProvider>\n <div className="flex shrink-0 items-center gap-1">\n {showNightRenderToggle ? (\n <>\n <ToolbarTooltip\n label={isDark ? "Use light workbook" : "Use dark workbook"}\n >\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label={\n isDark ? "Use light workbook" : "Use dark workbook"\n }\n onClick={() => onIsDarkChange(!isDark)}\n >\n {isDark ? (\n <Sun03Glyph className="size-4" />\n ) : (\n <Moon02Glyph className="size-4" />\n )}\n </Button>\n </ToolbarTooltip>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <EditorFileActionsMenu\n canExport={canExport}\n exportXlsx={exportXlsx}\n onUploadClick={onUploadClick}\n />\n </div>\n </TooltipProvider>\n </div>\n <TooltipProvider>\n <div className="flex min-h-12 flex-wrap items-center gap-2 border-b bg-background px-3 py-2">\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarTooltip label="Undo">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Undo"\n disabled={!canUndo || readOnly}\n onClick={undo}\n >\n <IconPlaceholder\n lucide="Undo2"\n tabler="IconArrowBackUp"\n hugeicons="Undo02Icon"\n phosphor="ArrowUUpLeftIcon"\n remixicon="RiArrowGoBackLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Redo">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Redo"\n disabled={!canRedo || readOnly}\n onClick={redo}\n >\n <IconPlaceholder\n lucide="Redo2"\n tabler="IconArrowForwardUp"\n hugeicons="Redo02Icon"\n phosphor="ArrowUUpRightIcon"\n remixicon="RiArrowGoForwardLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <Select\n value={fontFamilyValue}\n onValueChange={(value) => {\n if (!value) return\n\n if (applyStyle({ font: { name: value } })) {\n setFontFamily(value)\n }\n }}\n disabled={!canStyleSelection}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[132px] min-w-[132px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Font family"\n >\n <SelectValue placeholder="Font">{fontFamilyValue}</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {FONT_FAMILIES.map((option) => (\n <SelectItem key={option} value={option}>\n <span style={{ fontFamily: option }}>{option}</span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <Select\n value={String(fontSize)}\n onValueChange={(value) => {\n const nextFontSize = Number(value)\n if (!Number.isFinite(nextFontSize)) return\n\n setFontSize(nextFontSize)\n applyStyle({ font: { size: nextFontSize } })\n }}\n disabled={!canStyleSelection}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[78px] min-w-[78px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Font size"\n >\n <SelectValue placeholder="Size" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\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 </div>\n <ToolbarSeparator />\n <ToggleGroup\n className="shrink-0"\n disabled={!canStyleSelection}\n multiple\n spacing="default"\n value={fontToggleValues}\n onValueChange={(value) =>\n applyFontToggleValues(value as XlsxFontToggleValue[])\n }\n >\n <ToolbarTooltip label="Bold">\n <ToggleGroupItem aria-label="Bold" size="sm" value="bold">\n <IconPlaceholder\n lucide="Bold"\n tabler="IconBold"\n hugeicons="TextBoldIcon"\n phosphor="TextBIcon"\n remixicon="RiBold"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Italic">\n <ToggleGroupItem aria-label="Italic" size="sm" value="italic">\n <IconPlaceholder\n lucide="Italic"\n tabler="IconItalic"\n hugeicons="TextItalicIcon"\n phosphor="TextItalicIcon"\n remixicon="RiItalic"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Underline">\n <ToggleGroupItem\n aria-label="Underline"\n size="sm"\n value="underline"\n >\n <IconPlaceholder\n lucide="Underline"\n tabler="IconUnderline"\n hugeicons="TextUnderlineIcon"\n phosphor="TextUnderlineIcon"\n remixicon="RiUnderline"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Strikethrough">\n <ToggleGroupItem\n aria-label="Strikethrough"\n size="sm"\n value="strikethrough"\n >\n <IconPlaceholder\n lucide="Strikethrough"\n tabler="IconStrikethrough"\n hugeicons="TextStrikethroughIcon"\n phosphor="TextStrikethroughIcon"\n remixicon="RiStrikethrough"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n </ToggleGroup>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <ColorPicker\n label="Text color"\n icon={TextColorGlyph}\n color={textColor}\n disabled={!canStyleSelection}\n onChange={(color) => {\n const nextColor = normalizeHexColor(color)\n setTextColor(nextColor)\n applyStyle({ font: { color: toXlsxRgbColor(nextColor) } })\n }}\n />\n <ColorPicker\n label="Fill color"\n icon={PaintBucketGlyph}\n color={fillColor}\n disabled={!canStyleSelection}\n onChange={(color) => {\n const nextColor = normalizeHexColor(color, DEFAULT_FILL_COLOR)\n setFillColor(nextColor)\n applyStyle({\n fill: {\n color: toXlsxRgbColor(nextColor),\n fillType: "solid",\n },\n })\n }}\n />\n <ToolbarIconButton\n label="No fill"\n disabled={!canStyleSelection}\n onClick={() => applyStyle({ fill: { fillType: "none" } })}\n >\n <IconPlaceholder\n lucide="DropletOff"\n tabler="IconDropletOff"\n hugeicons="DropletOffIcon"\n phosphor="DropSlashIcon"\n remixicon="RiDropLine"\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <ToggleGroup\n className="shrink-0"\n disabled={!canStyleSelection}\n spacing="default"\n value={horizontalAlignmentValue}\n >\n <ToolbarTooltip label="Align left">\n <ToggleGroupItem\n aria-label="Align left"\n size="sm"\n value="left"\n onClick={() => applyHorizontalAlignment("left")}\n >\n <IconPlaceholder\n lucide="AlignLeft"\n tabler="IconAlignLeft"\n hugeicons="TextAlignLeft01Icon"\n phosphor="TextAlignLeftIcon"\n remixicon="RiAlignLeft"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align center">\n <ToggleGroupItem\n aria-label="Align center"\n size="sm"\n value="center"\n onClick={() => applyHorizontalAlignment("center")}\n >\n <IconPlaceholder\n lucide="AlignCenter"\n tabler="IconAlignCenter"\n hugeicons="TextAlignCenterIcon"\n phosphor="TextAlignCenterIcon"\n remixicon="RiAlignCenter"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align right">\n <ToggleGroupItem\n aria-label="Align right"\n size="sm"\n value="right"\n onClick={() => applyHorizontalAlignment("right")}\n >\n <IconPlaceholder\n lucide="AlignRight"\n tabler="IconAlignRight"\n hugeicons="TextAlignRight01Icon"\n phosphor="TextAlignRightIcon"\n remixicon="RiAlignRight"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n </ToggleGroup>\n <ToggleGroup\n className="shrink-0"\n disabled={!canStyleSelection}\n spacing="default"\n value={verticalAlignmentValue}\n >\n <ToolbarTooltip label="Align top">\n <ToggleGroupItem\n aria-label="Align top"\n size="sm"\n value="top"\n onClick={() => applyVerticalAlignment("top")}\n >\n <IconPlaceholder\n lucide="AlignVerticalJustifyStart"\n tabler="IconAlignBoxTopCenter"\n hugeicons="AlignBoxTopCenterIcon"\n phosphor="AlignTopIcon"\n remixicon="RiAlignTop"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align middle">\n <ToggleGroupItem\n aria-label="Align middle"\n size="sm"\n value="center"\n onClick={() => applyVerticalAlignment("center")}\n >\n <IconPlaceholder\n lucide="AlignVerticalJustifyCenter"\n tabler="IconAlignBoxCenterMiddle"\n hugeicons="AlignBoxMiddleCenterIcon"\n phosphor="AlignCenterVerticalIcon"\n remixicon="RiAlignVertically"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n <ToolbarTooltip label="Align bottom">\n <ToggleGroupItem\n aria-label="Align bottom"\n size="sm"\n value="bottom"\n onClick={() => applyVerticalAlignment("bottom")}\n >\n <IconPlaceholder\n lucide="AlignVerticalJustifyEnd"\n tabler="IconAlignBoxBottomCenter"\n hugeicons="AlignBoxBottomCenterIcon"\n phosphor="AlignBottomIcon"\n remixicon="RiAlignBottom"\n className="size-4"\n />\n </ToggleGroupItem>\n </ToolbarTooltip>\n </ToggleGroup>\n <ToolbarIconButton\n label="Wrap text"\n disabled={!canStyleSelection}\n onClick={() => applyStyle({ alignment: { wrapText: true } })}\n >\n <IconPlaceholder\n lucide="WrapText"\n tabler="IconTextWrap"\n hugeicons="TextWrapIcon"\n phosphor="ArrowElbowDownLeftIcon"\n remixicon="RiTextWrap"\n className="size-4"\n />\n </ToolbarIconButton>\n <AlignmentMoreMenu\n disabled={!canStyleSelection}\n onApplyStyle={applyStyle}\n />\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <NumberFormatSelect\n disabled={!canStyleSelection}\n onApplyStyle={applyStyle}\n value={numberFormatValue}\n />\n <BorderMenu\n borderColor={borderColor}\n disabled={!canStyleSelection}\n onApplyBorder={applyBorderAction}\n onBorderColorChange={setBorderColor}\n />\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <MergeCellsMenu\n canMerge={canMergeSelectedCells}\n canMergeAcross={canMergeAcross}\n canUnmerge={canUnmergeSelectedCells}\n disabled={!hasSelection || readOnly}\n isMerged={selectionIntersectsMerge}\n onMergeAcross={mergeAcrossSelectedCells}\n onMergeAndCenter={mergeAndCenterSelectedCells}\n onMergeCells={mergeSelectedCells}\n onUnmergeCells={unmergeSelectedCells}\n />\n </div>\n <ToolbarSeparator />\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarTooltip label="Add sheet">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Add sheet"\n disabled={!hasWorkbook || readOnly}\n onClick={() => addSheet()}\n >\n <IconPlaceholder\n lucide="Plus"\n tabler="IconPlus"\n hugeicons="Add01Icon"\n phosphor="PlusIcon"\n remixicon="RiAddLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Remove active sheet">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Remove active sheet"\n disabled={sheets.length <= 1 || readOnly}\n onClick={removeActiveSheet}\n >\n <IconPlaceholder\n lucide="Trash2Icon"\n tabler="IconTrash"\n hugeicons="Delete02Icon"\n phosphor="TrashIcon"\n remixicon="RiDeleteBinLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(activeSheetIndex)}\n onValueChange={(value) => setActiveSheetIndex(Number(value))}\n disabled={!hasWorkbook}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[150px] min-w-[150px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Active sheet"\n >\n <SelectValue>{activeSheet?.name ?? "Sheet"}</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="start"\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\n {sheets.map((sheet, index) => (\n <SelectItem\n key={`${sheet.name}-${index}`}\n value={String(index)}\n >\n {sheet.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <ToolbarSeparator />\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!hasWorkbook || !canZoomOut}\n aria-label="Zoom out"\n onClick={zoomOut}\n >\n <IconPlaceholder\n lucide="CircleMinus"\n tabler="IconCircleMinus"\n hugeicons="MinusSignCircleIcon"\n phosphor="MinusCircleIcon"\n remixicon="RiIndeterminateCircleLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={currentZoom.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={!hasWorkbook}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className={cn(\n "w-[84px] min-w-[84px]",\n XLSX_EDITOR_SELECT_CHROME_CLASS\n )}\n aria-label="Zoom level"\n >\n <SelectValue>{currentZoom}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="end"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\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={!hasWorkbook || !canZoomIn}\n aria-label="Zoom in"\n onClick={zoomIn}\n >\n <IconPlaceholder\n lucide="CirclePlusIcon"\n tabler="IconCirclePlusFilled"\n hugeicons="PlusSignCircleIcon"\n phosphor="PlusCircleIcon"\n remixicon="RiAddCircleFill"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n </div>\n <div className="border-t bg-background px-2 py-1">\n <Group className="w-full">\n <Input\n className={cn(\n "h-8 w-[92px] shrink-0 font-mono text-xs",\n XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS\n )}\n readOnly\n value={activeCellAddress ?? ""}\n />\n <GroupSeparator />\n <GroupText className="h-8 w-9 shrink-0 justify-center px-0 text-[11px] font-semibold italic">\n fx\n </GroupText>\n <GroupSeparator />\n <Input\n className={cn(\n "h-8 flex-1",\n XLSX_EDITOR_FORMULA_INPUT_CHROME_CLASS\n )}\n disabled={!hasActiveCell || readOnly}\n value={formulaDraft}\n onBlur={() => {\n commitFormula()\n setFormulaFocused(false)\n }}\n onChange={(event) => setFormulaDraft(event.target.value)}\n onFocus={() => {\n formulaEditCellRef.current = activeCell\n formulaInitialValueRef.current = formulaDraft\n setFormulaFocused(true)\n }}\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n event.preventDefault()\n commitFormula()\n setFormulaFocused(false)\n }\n }}\n placeholder="Select a cell, then enter a value or formula"\n />\n </Group>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function XlsxEditorSurface({\n className,\n isDark,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showNightRenderToggle,\n workbookIdentity,\n}: {\n className?: string\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showNightRenderToggle: boolean\n workbookIdentity: string\n}) {\n const { error } = useXlsxViewer()\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 <EditorToolbar\n isDark={isDark}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n showNightRenderToggle={showNightRenderToggle}\n workbookIdentity={workbookIdentity}\n />\n <div className="flex min-h-0 flex-1 flex-col">\n <div className="min-h-0 flex-1 bg-muted/20">\n <XlsxViewer\n allowResizeInReadOnly\n className="h-full min-h-0 min-w-0"\n height="100%"\n isDark={isDark}\n readOnly={false}\n rounded={false}\n showDefaultToolbar={false}\n showImages\n fileTooLargeState={\n <div className="grid h-full w-full min-w-full place-items-center p-6">\n <div className="max-w-sm rounded-lg border bg-background p-4 text-sm">\n <p className="font-medium">File too large for editing</p>\n <p className="mt-1 text-muted-foreground">\n This workbook exceeds the editor limit. Download it or open\n a smaller file to make changes.\n </p>\n </div>\n </div>\n }\n loadingState={<EditorLoadingSurface />}\n renderScroller={renderXlsxScroller}\n errorState={\n <div className="grid h-full w-full min-w-full place-items-center p-6 text-sm text-destructive">\n {error?.message ?? "Unable to edit workbook."}\n </div>\n }\n renderTableHeaderMenu={renderTableHeaderMenu}\n />\n </div>\n <WorkbookSheetTabs workbookIdentity={workbookIdentity} />\n </div>\n </div>\n )\n}\n\nexport function XlsxEditorPreview({\n className,\n fileName,\n isDark,\n onIsDarkChange,\n src,\n}: {\n className?: string\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n src?: string\n}) {\n return (\n <XlsxEditorContent\n className={className}\n effectiveIsDark={isDark}\n fileName={fileName}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction XlsxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n setNightRenderEnabled,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const [uploadedWorkbook, setUploadedWorkbook] =\n React.useState<UploadedWorkbook | null>(null)\n const [workbookBuffer, setWorkbookBuffer] =\n React.useState<ArrayBuffer | null>(null)\n const [loadError, setLoadError] = React.useState<string>()\n const sourceFileName = React.useMemo(\n () =>\n url ? formatWorkbookName(fileName, url) : (fileName ?? "workbook.xlsx"),\n [fileName, url]\n )\n const displayFileName = uploadedWorkbook?.fileName ?? sourceFileName\n const workbookIdentity =\n uploadedWorkbook?.identity ?? `${url ?? "empty"}::${displayFileName}`\n const shouldShowLoadingSpinner = useDelayedLoadingIndicator(\n !workbookBuffer && !loadError && !uploadedWorkbook,\n XLSX_LOADING_INDICATOR_DELAY_MS\n )\n\n React.useEffect(() => {\n let isCurrent = true\n\n if (url) {\n setUploadedWorkbook(null)\n }\n\n async function loadWorkbook(): Promise<void> {\n if (!url) {\n setWorkbookBuffer(null)\n setLoadError(undefined)\n return\n }\n\n setWorkbookBuffer(null)\n setLoadError(undefined)\n\n try {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch XLSX (${response.status})`)\n }\n\n const nextWorkbookBuffer = await response.arrayBuffer()\n if (!isCurrent) return\n\n setWorkbookBuffer(nextWorkbookBuffer)\n } catch (error) {\n if (!isCurrent) return\n\n setLoadError(\n error instanceof Error ? error.message : "Unknown XLSX load error"\n )\n }\n }\n\n void loadWorkbook()\n\n return () => {\n isCurrent = false\n }\n }, [url])\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 const buffer = await file.arrayBuffer()\n setWorkbookBuffer(null)\n setLoadError(undefined)\n setUploadedWorkbook({\n buffer,\n fileName: file.name,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n const activeBuffer = uploadedWorkbook?.buffer ?? workbookBuffer\n\n if (!url && !uploadedWorkbook) {\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=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <div className="grid min-h-0 flex-1 place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs">\n <p className="font-medium">Upload a workbook to edit</p>\n <p className="mt-1 text-muted-foreground">\n Pass an XLSX URL with the <code>src</code> prop or upload a local\n file.\n </p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (loadError && !activeBuffer) {\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=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <div className="grid min-h-0 flex-1 place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm">\n <p className="font-medium">Unable to edit workbook</p>\n <p className="mt-1 text-muted-foreground">{loadError}</p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (!activeBuffer) {\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=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <EditorLoadingSurface showSpinner={shouldShowLoadingSpinner} />\n </div>\n )\n }\n\n return (\n <div className={cn("overflow-hidden", className)}>\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <XlsxWorkbookLoadedEditor\n fileName={displayFileName}\n isDark={effectiveIsDark}\n onIsDarkChange={setNightRenderEnabled}\n onUploadClick={() => fileInputRef.current?.click()}\n renderTableHeaderMenu={(props) => (\n <WorkbookTableHeaderMenu {...props} />\n )}\n showNightRenderToggle={shouldRenderNightMode}\n workbookBuffer={activeBuffer}\n workbookIdentity={workbookIdentity}\n />\n </div>\n )\n}\n\nfunction XlsxWorkbookLoadedEditor({\n fileName,\n isDark,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showNightRenderToggle,\n workbookBuffer,\n workbookIdentity,\n}: {\n fileName: string\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showNightRenderToggle: boolean\n workbookBuffer: ArrayBuffer\n workbookIdentity: string\n}) {\n const controller = useXlsxViewerController(\n React.useMemo(\n () => ({\n allowResizeInReadOnly: true,\n file: workbookBuffer,\n fileName,\n readOnly: false,\n readOnlyAboveBytes: XLSX_EDITOR_READ_ONLY_THRESHOLD_BYTES,\n useWorker: true,\n }),\n [fileName, workbookBuffer]\n )\n )\n\n return (\n <XlsxViewerProvider controller={controller} isDark={isDark}>\n <XlsxEditorSurface\n isDark={isDark}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n renderTableHeaderMenu={renderTableHeaderMenu}\n showNightRenderToggle={showNightRenderToggle}\n workbookIdentity={workbookIdentity}\n />\n </XlsxViewerProvider>\n )\n}\n'export function XlsxEditorSource() {return (diff --git a/apps/v4/components/xlsx-viewer-docs.tsx b/apps/v4/components/xlsx-viewer-docs.tsxindex c40d862..b85d3e0 100644--- a/apps/v4/components/xlsx-viewer-docs.tsx+++ b/apps/v4/components/xlsx-viewer-docs.tsx@@ -38,7 +38,7 @@ export function XlsxViewerDemo() {return (<divdata-slot="component-preview"- className="group relative mt-4 mb-12 flex flex-col overflow-hidden border rounded-xl"+ className="group relative mt-4 mb-12 flex flex-col overflow-hidden rounded-xl border"><XlsxViewerPreviewsrc={SAMPLE_XLSX_URL}@@ -67,7 +67,7 @@ export function XlsxViewerExample() {}`const xlsxViewerSourceCode =- "\"use client\"\n\nimport * as React from \"react\"\nimport {\n useXlsxViewer,\n useXlsxViewerController,\n useXlsxViewerThumbnails,\n useXlsxViewerZoom,\n XlsxViewer,\n XlsxViewerProvider,\n type XlsxCellAddress,\n type XlsxScrollerRenderProps,\n type XlsxSheetData,\n type XlsxTableHeaderMenuRenderProps,\n type XlsxViewerController,\n} from \"@extend-ai/react-xlsx\"\nimport {\n ArrowLeft01Icon,\n ArrowRight01Icon,\n Download01Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n MoreHorizontalIcon,\n PlusSignCircleIcon,\n Search01Icon,\n Upload01Icon,\n} from \"@hugeicons/core-free-icons\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { createPortal } from \"react-dom\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuRadioGroup,\n DropdownMenuRadioItem,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\"\nimport { Input } from \"@/components/ui/input\"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from \"@/components/ui/popover\"\nimport { ScrollArea } from \"@/components/ui/scroll-area\"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from \"@/components/ui/select\"\nimport { Separator } from \"@/components/ui/separator\"\nimport { Spinner } from \"@/components/ui/spinner\"\nimport { Tabs, TabsList, TabsTrigger } from \"@/components/ui/tabs\"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from \"@/components/ui/tooltip\"\n\nconst XLSX_LOADING_INDICATOR_DELAY_MS = 300\nconst XLSX_DROPDOWN_Z_INDEX_CLASS = \"z-40\"\nconst XLSX_SEARCH_BATCH_ROW_COUNT = 500\nconst XLSX_SEARCH_DEBOUNCE_MS = 300\nconst XLSX_GRID_HEADER_HEIGHT = 24\nconst XLSX_GRID_ROW_HEADER_WIDTH = 40\nconst XLSX_MAX_FILE_SIZE_BYTES = 50 * 1024 * 1024\nconst ZOOM_OPTIONS = [10, 25, 50, 75, 100, 125, 150, 175, 200, 400] as const\n\n// Stable reference so the thumbnails memo isn't invalidated on every render\n// (e.g. by selection changes), which would recompute every sheet thumbnail.\nconst XLSX_SHEET_TAB_THUMBNAIL_OPTIONS = {\n resolution: {\n maxHeight: 360,\n maxWidth: 560,\n },\n} as const\n\ntype UploadedWorkbook = {\n buffer: ArrayBuffer\n fileName: string\n identity: string\n}\n\ntype XlsxSearchResult = {\n cell: XlsxCellAddress\n displayValue: string\n formula?: string\n sheetIndex: number\n sheetName: string\n workbookSheetIndex: number\n}\n\ntype XlsxBatchCell = {\n col?: unknown\n formula?: unknown\n value?: unknown\n}\n\ntype XlsxBatchRow = {\n cells?: unknown\n index?: unknown\n}\n\nfunction formatWorkbookName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split(\"?\")[0] ?? \"\"\n const rawName = pathname.split(\"/\").pop() ?? \"workbook.xlsx\"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction ensureWorkbookExtension(fileName: string) {\n const lowerFileName = fileName.toLowerCase()\n return lowerFileName.endsWith(\".xlsx\") || lowerFileName.endsWith(\".xls\")\n ? fileName\n : `${fileName}.xlsx`\n}\n\nfunction downloadWorkbookBuffer(buffer: ArrayBuffer, fileName: string) {\n const resolvedFileName = ensureWorkbookExtension(fileName)\n const blob = new Blob([buffer], {\n type: resolvedFileName.toLowerCase().endsWith(\".xls\")\n ? \"application/vnd.ms-excel\"\n : \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n })\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement(\"a\")\n\n anchor.href = url\n anchor.download = resolvedFileName\n anchor.rel = \"noopener\"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nfunction normalizeSearchText(value: unknown) {\n return typeof value === \"string\"\n ? value\n : value === null || value === undefined\n ? \"\"\n : String(value)\n}\n\nfunction cellValueToSearchText(value: unknown) {\n if (!value || typeof value !== \"object\") return normalizeSearchText(value)\n\n const record = value as {\n asBoolean?: () => boolean | null\n asError?: () => string | null\n asNumber?: () => number | null\n asText?: () => string | null\n is_boolean?: boolean\n is_empty?: boolean\n is_error?: boolean\n is_number?: boolean\n is_text?: boolean\n }\n\n if (record.is_empty) return \"\"\n if (record.is_error) return record.asError?.() ?? \"\"\n if (record.is_text) return record.asText?.() ?? \"\"\n if (record.is_number) return normalizeSearchText(record.asNumber?.())\n if (record.is_boolean) return record.asBoolean?.() ? \"TRUE\" : \"FALSE\"\n\n return normalizeSearchText(value)\n}\n\nfunction getCellSearchText(\n controller: XlsxViewerController,\n sheet: XlsxSheetData,\n row: number,\n col: number\n) {\n const worksheet = controller.workbook?.getSheet(sheet.workbookSheetIndex)\n if (!worksheet) return { displayValue: \"\", formula: \"\" }\n\n const formula = worksheet.getFormulaAt(row, col) ?? \"\"\n const cachedFormulaValue = formula\n ? sheet.cachedFormulaValues[cellAddressToA1({ row, col })]\n : undefined\n const formatted = worksheet.getFormattedValueAt(row, col)\n\n if (\n formatted &&\n !(formula && cachedFormulaValue !== undefined && formatted.startsWith(\"#\"))\n ) {\n return { displayValue: formatted, formula }\n }\n\n const calculated = worksheet.getCalculatedValueAt(row, col)\n const displayValue =\n formula && cachedFormulaValue !== undefined && calculated.is_error\n ? cachedFormulaValue\n : cellValueToSearchText(calculated)\n\n return { displayValue, formula }\n}\n\nfunction getBatchRows(rows: unknown): XlsxBatchRow[] {\n return Array.isArray(rows) ? (rows as XlsxBatchRow[]) : []\n}\n\nfunction getBatchCells(row: XlsxBatchRow): XlsxBatchCell[] {\n return Array.isArray(row.cells) ? (row.cells as XlsxBatchCell[]) : []\n}\n\nfunction cellMatchesQuery(\n displayValue: string,\n formula: string,\n query: string\n) {\n return (\n displayValue.toLowerCase().includes(query) ||\n formula.toLowerCase().includes(query)\n )\n}\n\nfunction cellAddressToA1({ col, row }: XlsxCellAddress) {\n let columnNumber = col + 1\n let columnName = \"\"\n\n while (columnNumber > 0) {\n const remainder = (columnNumber - 1) % 26\n columnName = String.fromCharCode(65 + remainder) + columnName\n columnNumber = Math.floor((columnNumber - 1) / 26)\n }\n\n return `${columnName}${row + 1}`\n}\n\nasync function findXlsxSearchResults(\n controller: XlsxViewerController,\n rawQuery: string\n) {\n const query = rawQuery.trim().toLowerCase()\n if (!query) return []\n\n const results: XlsxSearchResult[] = []\n\n for (const [sheetIndex, sheet] of controller.sheets.entries()) {\n const startRow = Math.max(0, sheet.minUsedRow)\n const endRow = Math.max(startRow, sheet.maxUsedRow)\n const visibleCols = sheet.visibleCols.filter(\n (col) => col >= sheet.minUsedCol && col <= sheet.maxUsedCol\n )\n const visibleRowSet = new Set(sheet.visibleRows)\n const visibleColSet = new Set(visibleCols)\n\n if (!visibleCols.length || sheet.maxUsedRow < sheet.minUsedRow) continue\n\n const worksheet = controller.workbook?.getSheet(sheet.workbookSheetIndex)\n const worksheetWithBatch = worksheet as\n | {\n getRowsBatch?: (\n startRow: number,\n rowCount: number,\n options?: Record<string, unknown>\n ) => unknown\n }\n | undefined\n\n for (\n let batchStartRow = startRow;\n batchStartRow <= endRow;\n batchStartRow += XLSX_SEARCH_BATCH_ROW_COUNT\n ) {\n const rowCount = Math.min(\n XLSX_SEARCH_BATCH_ROW_COUNT,\n endRow - batchStartRow + 1\n )\n const rows = controller.getRowsBatchAsync\n ? await controller.getRowsBatchAsync(\n sheet.workbookSheetIndex,\n batchStartRow,\n rowCount\n )\n : worksheetWithBatch?.getRowsBatch?.(batchStartRow, rowCount, {\n includeFormulas: true,\n useFormattedValues: true,\n })\n\n if (rows) {\n for (const rowEntry of getBatchRows(rows)) {\n const row = Number(rowEntry.index)\n if (!Number.isInteger(row) || !visibleRowSet.has(row)) {\n continue\n }\n\n for (const cellEntry of getBatchCells(rowEntry)) {\n const col = Number(cellEntry.col)\n if (!Number.isInteger(col) || !visibleColSet.has(col)) continue\n\n const displayValue = normalizeSearchText(cellEntry.value)\n const formula = normalizeSearchText(cellEntry.formula)\n\n if (!cellMatchesQuery(displayValue, formula, query)) continue\n\n results.push({\n cell: { row, col },\n displayValue,\n formula,\n sheetIndex,\n sheetName: sheet.name,\n workbookSheetIndex: sheet.workbookSheetIndex,\n })\n }\n }\n continue\n }\n\n if (!worksheet) continue\n\n const batchEndRow = batchStartRow + rowCount - 1\n for (const row of sheet.visibleRows) {\n if (row < batchStartRow || row > batchEndRow) continue\n\n for (const col of visibleCols) {\n const { displayValue, formula } = getCellSearchText(\n controller,\n sheet,\n row,\n col\n )\n\n if (!cellMatchesQuery(displayValue, formula, query)) continue\n\n results.push({\n cell: { row, col },\n displayValue,\n formula,\n sheetIndex,\n sheetName: sheet.name,\n workbookSheetIndex: sheet.workbookSheetIndex,\n })\n }\n }\n }\n }\n\n return results\n}\n\nfunction sumAxisBefore(values: number[], endIndex: number, zoomFactor: number) {\n let total = 0\n for (let index = 0; index < endIndex; index += 1) {\n total += (values[index] ?? 0) * zoomFactor\n }\n return total\n}\n\nfunction scrollXlsxCellIntoView({\n controller,\n result,\n viewport,\n}: {\n controller: XlsxViewerController\n result: XlsxSearchResult\n viewport: HTMLDivElement | null\n}) {\n if (!viewport) return\n\n const sheet = controller.sheets[result.sheetIndex]\n if (!sheet) return\n\n const rowIndex = sheet.visibleRows.indexOf(result.cell.row)\n const colIndex = sheet.visibleCols.indexOf(result.cell.col)\n if (rowIndex < 0 || colIndex < 0) return\n\n const zoomFactor = Math.max(0.1, controller.zoomScale / 100)\n const headerHeight = XLSX_GRID_HEADER_HEIGHT * zoomFactor\n const rowHeaderWidth = XLSX_GRID_ROW_HEADER_WIDTH * zoomFactor\n const rowStart =\n headerHeight + sumAxisBefore(sheet.rowHeights, rowIndex, zoomFactor)\n const colStart =\n rowHeaderWidth + sumAxisBefore(sheet.colWidths, colIndex, zoomFactor)\n const rowHeight =\n (sheet.rowHeights[rowIndex] ?? sheet.defaultRowHeightPx) * zoomFactor\n const colWidth =\n (sheet.colWidths[colIndex] ?? sheet.defaultColWidthPx) * zoomFactor\n const rowEnd = rowStart + rowHeight\n const colEnd = colStart + colWidth\n let nextTop = viewport.scrollTop\n let nextLeft = viewport.scrollLeft\n const visibleTop = viewport.scrollTop + headerHeight\n const visibleLeft = viewport.scrollLeft + rowHeaderWidth\n const visibleBottom = viewport.scrollTop + viewport.clientHeight\n const visibleRight = viewport.scrollLeft + viewport.clientWidth\n\n if (rowStart < visibleTop) {\n nextTop = rowStart - headerHeight\n } else if (rowEnd > visibleBottom) {\n nextTop = rowEnd - viewport.clientHeight\n }\n\n if (colStart < visibleLeft) {\n nextLeft = colStart - rowHeaderWidth\n } else if (colEnd > visibleRight) {\n nextLeft = colEnd - viewport.clientWidth\n }\n\n viewport.scrollTo({\n left: Math.max(0, nextLeft),\n top: Math.max(0, nextTop),\n behavior: \"auto\",\n })\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 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 w-full min-w-full place-items-center bg-transparent\">\n {showSpinner ? <Spinner className=\"size-4\" /> : null}\n </div>\n )\n}\n\nfunction WorkbookFileActionsMenu({\n isDark,\n onDownload,\n onIsDarkChange,\n onUploadClick,\n showDownloadButton,\n showNightRenderToggle = false,\n showUploadButton,\n}: {\n isDark?: boolean\n onDownload?: () => void\n onIsDarkChange?: (checked: boolean) => void\n onUploadClick: () => void\n showDownloadButton: boolean\n showNightRenderToggle?: boolean\n showUploadButton: boolean\n}) {\n const showThemeControl = showNightRenderToggle && Boolean(onIsDarkChange)\n const showFileActions = (showDownloadButton && onDownload) || showUploadButton\n if (!showThemeControl && !showFileActions) return null\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Open workbook actions\"\n >\n <HugeiconsIcon icon={MoreHorizontalIcon} className=\"size-4\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align=\"end\"\n className={cn(\"w-52\", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n {showThemeControl ? (\n <>\n <DropdownMenuCheckboxItem\n checked={Boolean(isDark)}\n variant=\"switch\"\n onCheckedChange={(checked) => onIsDarkChange?.(checked === true)}\n >\n <span className=\"flex min-w-0 items-center gap-2\">\n <HugeiconsIcon icon={Moon02Icon} className=\"size-4\" />\n Dark mode\n </span>\n </DropdownMenuCheckboxItem>\n {showFileActions ? <DropdownMenuSeparator /> : null}\n </>\n ) : null}\n {showDownloadButton && onDownload ? (\n <DropdownMenuItem onClick={onDownload}>\n <HugeiconsIcon icon={Download01Icon} className=\"size-4\" />\n Download\n </DropdownMenuItem>\n ) : null}\n {showUploadButton ? (\n <DropdownMenuItem onClick={onUploadClick}>\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n Upload\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nexport function renderXlsxScroller({\n children,\n viewportProps,\n}: XlsxScrollerRenderProps) {\n return (\n <ScrollArea\n className=\"h-full min-h-0 w-full min-w-0 flex-1\"\n viewportProps={viewportProps}\n >\n {children}\n </ScrollArea>\n )\n}\n\nexport function WorkbookTableHeaderMenu({\n direction,\n sortAscending,\n sortDescending,\n triggerIcon,\n triggerProps,\n}: XlsxTableHeaderMenuRenderProps) {\n const [open, setOpen] = React.useState(false)\n\n return (\n <DropdownMenu open={open} onOpenChange={setOpen}>\n <DropdownMenuTrigger asChild>\n <Button\n {...triggerProps}\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n className={cn(\"size-6 rounded-sm\", triggerProps.className)}\n aria-label=\"Column menu\"\n >\n {triggerIcon ? (\n triggerIcon\n ) : (\n <HugeiconsIcon icon={MoreHorizontalIcon} className=\"size-3.5\" />\n )}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align=\"end\"\n className={cn(\"w-40\", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <DropdownMenuRadioGroup\n value={direction ?? \"\"}\n onValueChange={(value) => {\n if (value === \"ascending\") {\n sortAscending()\n } else {\n sortDescending()\n }\n setOpen(false)\n }}\n >\n <DropdownMenuRadioItem value=\"ascending\">\n Sort ascending\n </DropdownMenuRadioItem>\n <DropdownMenuRadioItem value=\"descending\">\n Sort descending\n </DropdownMenuRadioItem>\n </DropdownMenuRadioGroup>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction WorkbookSearchPopover({\n viewportRef,\n workbookIdentity,\n}: {\n viewportRef: React.RefObject<HTMLDivElement | null>\n workbookIdentity: string\n}) {\n const controller = useXlsxViewer()\n const [searchDraft, setSearchDraft] = React.useState(\"\")\n const [searchQuery, setSearchQuery] = React.useState(\"\")\n const [searchResults, setSearchResults] = React.useState<XlsxSearchResult[]>(\n []\n )\n const [activeResultIndex, setActiveResultIndex] = React.useState(0)\n const [isSearching, setIsSearching] = React.useState(false)\n const controllerRef = React.useRef(controller)\n const searchRequestIdRef = React.useRef(0)\n const appliedResultKeyRef = React.useRef(\"\")\n const activeResult = searchResults[activeResultIndex] ?? null\n const activeResultKey = activeResult\n ? `${activeResult.workbookSheetIndex}:${activeResult.cell.row}:${activeResult.cell.col}`\n : \"\"\n const controlsDisabled =\n controller.isLoading ||\n Boolean(controller.error) ||\n !controller.sheets.length\n const hasActiveQuery = Boolean(searchQuery.trim())\n const resultLabel = isSearching\n ? \"Searching\"\n : !hasActiveQuery\n ? \"No search\"\n : searchResults.length\n ? `${activeResultIndex + 1} / ${searchResults.length}`\n : \"No results\"\n\n React.useEffect(() => {\n controllerRef.current = controller\n }, [controller])\n\n const runSearch = React.useCallback((rawQuery: string) => {\n const nextQuery = rawQuery.trim()\n const requestId = searchRequestIdRef.current + 1\n searchRequestIdRef.current = requestId\n appliedResultKeyRef.current = \"\"\n setSearchQuery(nextQuery)\n setActiveResultIndex(0)\n\n if (!nextQuery) {\n setSearchResults([])\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n void findXlsxSearchResults(controllerRef.current, nextQuery)\n .then((nextResults) => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults(nextResults)\n })\n .catch(() => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults([])\n })\n .finally(() => {\n if (searchRequestIdRef.current !== requestId) return\n setIsSearching(false)\n })\n }, [])\n\n React.useEffect(() => {\n const trimmedDraft = searchDraft.trim()\n\n if (!trimmedDraft) {\n runSearch(\"\")\n return\n }\n\n setIsSearching(true)\n const timeoutId = window.setTimeout(() => {\n runSearch(searchDraft)\n }, XLSX_SEARCH_DEBOUNCE_MS)\n\n return () => window.clearTimeout(timeoutId)\n }, [runSearch, searchDraft])\n\n const clearSearch = React.useCallback(() => {\n searchRequestIdRef.current += 1\n setSearchDraft(\"\")\n setSearchQuery(\"\")\n setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = \"\"\n controller.clearSelection()\n }, [controller])\n\n const goToRelativeResult = React.useCallback(\n (direction: 1 | -1) => {\n if (!searchResults.length) return\n\n setActiveResultIndex((currentIndex) => {\n return (\n (currentIndex + direction + searchResults.length) %\n searchResults.length\n )\n })\n },\n [searchResults.length]\n )\n\n React.useEffect(() => {\n searchRequestIdRef.current += 1\n setSearchDraft(\"\")\n setSearchQuery(\"\")\n setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = \"\"\n }, [workbookIdentity])\n\n React.useEffect(() => {\n if (!activeResult) return\n\n if (controller.activeSheetIndex !== activeResult.sheetIndex) {\n appliedResultKeyRef.current = \"\"\n controller.setActiveSheetIndex(activeResult.sheetIndex)\n return\n }\n\n if (appliedResultKeyRef.current === activeResultKey) return\n appliedResultKeyRef.current = activeResultKey\n controller.selectCell(activeResult.cell)\n\n const frame = window.requestAnimationFrame(() => {\n scrollXlsxCellIntoView({\n controller,\n result: activeResult,\n viewport: viewportRef.current,\n })\n })\n\n return () => window.cancelAnimationFrame(frame)\n }, [\n activeResult,\n activeResultKey,\n controller,\n controller.activeSheetIndex,\n viewportRef,\n ])\n\n return (\n <Popover>\n <ToolbarTooltip label=\"Search workbook\">\n <PopoverTrigger asChild>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Search workbook\"\n disabled={controlsDisabled}\n >\n <HugeiconsIcon icon={Search01Icon} className=\"size-4\" />\n </Button>\n </PopoverTrigger>\n </ToolbarTooltip>\n <PopoverContent align=\"end\" className=\"w-72\">\n <div className=\"space-y-3\">\n <Input\n placeholder=\"Search workbook\"\n value={searchDraft}\n onChange={(event) => setSearchDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key !== \"Enter\") return\n\n event.preventDefault()\n if (event.shiftKey && searchResults.length) {\n goToRelativeResult(-1)\n } else if (searchResults.length) {\n goToRelativeResult(1)\n } else if (searchDraft.trim()) {\n runSearch(searchDraft)\n }\n }}\n />\n <div className=\"flex items-center justify-between gap-2\">\n <div className=\"min-w-0 text-xs text-muted-foreground\">\n <div className=\"truncate\">\n {searchResults.length ? (\n <>\n <span className=\"text-primary\">\n {activeResultIndex + 1}\n </span>\n {` / ${searchResults.length}`}\n </>\n ) : (\n resultLabel\n )}\n </div>\n {activeResult ? (\n <div className=\"mt-0.5 truncate\">\n {activeResult.sheetName}!{cellAddressToA1(activeResult.cell)}\n </div>\n ) : null}\n </div>\n <div className=\"flex shrink-0 items-center gap-1\">\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"icon-sm\"\n aria-label=\"Previous result\"\n disabled={isSearching || searchResults.length === 0}\n onClick={() => goToRelativeResult(-1)}\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className=\"size-4\" />\n </Button>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"icon-sm\"\n aria-label=\"Next result\"\n disabled={isSearching || searchResults.length === 0}\n onClick={() => goToRelativeResult(1)}\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className=\"size-4\" />\n </Button>\n </div>\n </div>\n <div className=\"flex justify-end\">\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={clearSearch}\n >\n Clear\n </Button>\n </div>\n </div>\n </PopoverContent>\n </Popover>\n )\n}\n\nfunction WorkbookToolbar({\n isDark,\n onDownload,\n onIsDarkChange,\n onUploadClick,\n showDownloadButton = true,\n showNightRenderToggle,\n showUploadButton = true,\n toolbarActions,\n viewportRef,\n workbookIdentity,\n}: {\n isDark: boolean\n onDownload?: () => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n showDownloadButton?: boolean\n showNightRenderToggle: boolean\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n viewportRef: React.RefObject<HTMLDivElement | null>\n workbookIdentity: string\n}) {\n const { canZoomIn, canZoomOut, setZoomScale, zoomIn, zoomOut, zoomScale } =\n useXlsxViewerZoom()\n const currentZoom = Math.round(zoomScale)\n\n React.useEffect(() => {\n setZoomScale(100)\n }, [setZoomScale, workbookIdentity])\n\n return (\n <div className=\"flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2\">\n <TooltipProvider>\n <div className=\"ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1\">\n <div className=\"flex flex-none items-center gap-1\">\n <ToolbarTooltip label=\"Zoom out\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n disabled={!canZoomOut}\n aria-label=\"Zoom out\"\n onClick={zoomOut}\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={currentZoom.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n modal={false}\n >\n <SelectTrigger\n size=\"sm\"\n className=\"w-[84px] min-w-[84px]\"\n aria-label=\"Zoom level\"\n >\n <SelectValue>{currentZoom}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align=\"end\"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\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={!canZoomIn}\n aria-label=\"Zoom in\"\n onClick={zoomIn}\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator orientation=\"vertical\" className=\"mx-1 h-4 self-center\" />\n <WorkbookSearchPopover\n viewportRef={viewportRef}\n workbookIdentity={workbookIdentity}\n />\n {toolbarActions ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n {toolbarActions}\n </>\n ) : null}\n {(showDownloadButton && onDownload) ||\n showUploadButton ||\n showNightRenderToggle ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n <WorkbookFileActionsMenu\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showUploadButton={showUploadButton}\n />\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction WorkbookStandaloneToolbar({\n onUploadClick,\n showUploadButton = true,\n toolbarActions,\n}: {\n onUploadClick: () => void\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n}) {\n return (\n <div className=\"flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2\">\n <TooltipProvider>\n <div className=\"ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1\">\n {toolbarActions ? <>{toolbarActions}</> : null}\n {showUploadButton ? (\n <>\n {toolbarActions ? (\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n ) : null}\n <WorkbookFileActionsMenu\n onUploadClick={onUploadClick}\n showDownloadButton={false}\n showUploadButton={showUploadButton}\n />\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\ntype WorkbookSheetTab = {\n name: string\n workbookSheetIndex: number\n}\n\ntype WorkbookSheetTabsInnerProps = {\n activeSheetIndex: number\n onActiveSheetIndexChange: (index: number) => void\n sheets: WorkbookSheetTab[]\n workbookIdentity: string\n}\n\nexport function WorkbookSheetTabs({\n workbookIdentity,\n}: {\n workbookIdentity: string\n}) {\n const { activeSheetIndex, setActiveSheetIndex, sheets } = useXlsxViewer()\n\n const handleActiveSheetIndexChange = React.useCallback(\n (index: number) => setActiveSheetIndex(index),\n [setActiveSheetIndex]\n )\n\n return (\n <WorkbookSheetTabsInner\n activeSheetIndex={activeSheetIndex}\n onActiveSheetIndexChange={handleActiveSheetIndexChange}\n sheets={sheets}\n workbookIdentity={workbookIdentity}\n />\n )\n}\n\nconst WorkbookSheetTabsInner = React.memo(function WorkbookSheetTabsInner({\n activeSheetIndex,\n onActiveSheetIndexChange,\n sheets,\n workbookIdentity,\n}: WorkbookSheetTabsInnerProps) {\n const [visiblePreviewIndex, setVisiblePreviewIndex] = React.useState<\n number | null\n >(null)\n const [previewPosition, setPreviewPosition] = React.useState({\n left: 0,\n top: 0,\n })\n const { thumbnails } = useXlsxViewerThumbnails(\n XLSX_SHEET_TAB_THUMBNAIL_OPTIONS\n )\n const [thumbnailUrls, setThumbnailUrls] = React.useState<\n Record<number, string>\n >({})\n const scrollRef = React.useRef<HTMLDivElement | null>(null)\n const itemRefs = React.useRef<Record<number, HTMLButtonElement | null>>({})\n const openTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(\n null\n )\n const closeTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(\n null\n )\n const previewWidth = 220\n const previewHeight = (previewWidth * 7) / 11\n const previewGap = 12\n const previewOpenDelayMs = 500\n\n const clearOpenTimeout = React.useCallback(() => {\n if (openTimeoutRef.current) {\n clearTimeout(openTimeoutRef.current)\n openTimeoutRef.current = null\n }\n }, [])\n\n const clearCloseTimeout = React.useCallback(() => {\n if (closeTimeoutRef.current) {\n clearTimeout(closeTimeoutRef.current)\n closeTimeoutRef.current = null\n }\n }, [])\n\n const getPreviewPosition = React.useCallback(\n (sheetIndex: number) => {\n const item = itemRefs.current[sheetIndex]\n if (!item || typeof window === \"undefined\") {\n return { left: 0, top: 0 }\n }\n\n const itemRect = item.getBoundingClientRect()\n const centeredLeft = itemRect.left + itemRect.width / 2 - previewWidth / 2\n const minLeft = 8\n const maxLeft = Math.max(minLeft, window.innerWidth - previewWidth - 8)\n const left = Math.max(minLeft, Math.min(centeredLeft, maxLeft))\n const top = Math.max(8, itemRect.top - previewHeight - previewGap)\n\n return { left, top }\n },\n [previewHeight]\n )\n\n const updatePreviewPosition = React.useCallback(\n (sheetIndex: number) => {\n setPreviewPosition(getPreviewPosition(sheetIndex))\n },\n [getPreviewPosition]\n )\n\n const handleItemEnter = React.useCallback(\n (sheetIndex: number) => {\n clearCloseTimeout()\n const nextPreviewPosition = getPreviewPosition(sheetIndex)\n\n if (visiblePreviewIndex !== null) {\n clearOpenTimeout()\n setPreviewPosition(nextPreviewPosition)\n setVisiblePreviewIndex(sheetIndex)\n return\n }\n\n clearOpenTimeout()\n openTimeoutRef.current = setTimeout(() => {\n setPreviewPosition(nextPreviewPosition)\n setVisiblePreviewIndex(sheetIndex)\n }, previewOpenDelayMs)\n },\n [\n clearCloseTimeout,\n clearOpenTimeout,\n getPreviewPosition,\n visiblePreviewIndex,\n ]\n )\n\n const handleContainerLeave = React.useCallback(() => {\n clearOpenTimeout()\n clearCloseTimeout()\n closeTimeoutRef.current = setTimeout(() => {\n setVisiblePreviewIndex(null)\n }, 80)\n }, [clearCloseTimeout, clearOpenTimeout])\n\n React.useEffect(() => {\n return () => {\n clearOpenTimeout()\n clearCloseTimeout()\n }\n }, [clearCloseTimeout, clearOpenTimeout])\n\n React.useEffect(() => {\n clearOpenTimeout()\n clearCloseTimeout()\n setVisiblePreviewIndex(null)\n setPreviewPosition({ left: 0, top: 0 })\n setThumbnailUrls({})\n }, [clearCloseTimeout, clearOpenTimeout, workbookIdentity])\n\n React.useEffect(() => {\n thumbnails.forEach((thumbnail) => {\n setThumbnailUrls((current) => {\n if (current[thumbnail.sheetIndex]) return current\n\n const canvas = document.createElement(\"canvas\")\n canvas.width = thumbnail.width\n canvas.height = thumbnail.height\n\n if (!thumbnail.paint(canvas)) return current\n\n return {\n ...current,\n [thumbnail.sheetIndex]: canvas.toDataURL(\"image/png\"),\n }\n })\n })\n }, [thumbnails])\n\n React.useEffect(() => {\n if (visiblePreviewIndex === null) return\n\n const handleReposition = () => updatePreviewPosition(visiblePreviewIndex)\n handleReposition()\n\n const scrollElement = scrollRef.current\n window.addEventListener(\"resize\", handleReposition)\n scrollElement?.addEventListener(\"scroll\", handleReposition, {\n passive: true,\n })\n\n return () => {\n window.removeEventListener(\"resize\", handleReposition)\n scrollElement?.removeEventListener(\"scroll\", handleReposition)\n }\n }, [updatePreviewPosition, visiblePreviewIndex])\n\n // The preview card portals to document.body, so it outlives the tab\n // strip's own visibility: when the viewer is hidden or reparented under\n // the cursor (keep-alive preview pools, a closing dialog) no mouseleave\n // fires and the card would hang on screen. While the preview is open,\n // poll the strip's effective visibility and dismiss as soon as it stops\n // being shown.\n React.useEffect(() => {\n if (visiblePreviewIndex === null) return\n\n const dismissWhenHidden = () => {\n const element = scrollRef.current\n const isVisible = Boolean(\n element?.isConnected &&\n (element.checkVisibility?.({ checkVisibilityCSS: true }) ?? true)\n )\n\n if (isVisible) return\n clearOpenTimeout()\n clearCloseTimeout()\n setVisiblePreviewIndex(null)\n }\n const interval = setInterval(dismissWhenHidden, 200)\n\n return () => clearInterval(interval)\n }, [clearCloseTimeout, clearOpenTimeout, visiblePreviewIndex])\n\n if (sheets.length <= 1) return null\n\n const previewSheet =\n visiblePreviewIndex === null ? null : sheets[visiblePreviewIndex]\n const previewUrl =\n visiblePreviewIndex === null\n ? null\n : (thumbnailUrls[visiblePreviewIndex] ?? null)\n\n return (\n <div\n className=\"border-t bg-muted/40 px-3 py-2\"\n onMouseLeave={handleContainerLeave}\n >\n <Tabs\n value={String(activeSheetIndex)}\n onValueChange={(value) => onActiveSheetIndexChange(Number(value))}\n className=\"gap-0\"\n >\n <ScrollArea\n orientation=\"horizontal\"\n scrollbarGutter\n className=\"h-10 w-full has-[[data-slot=scroll-area-viewport][data-has-overflow-x]]:h-[50px]\"\n viewportClassName=\"overflow-y-hidden\"\n viewportRef={scrollRef}\n >\n <div className=\"flex h-full items-center\">\n <TabsList className=\"shrink-0\">\n {sheets.map((sheet, index) => (\n <TabsTrigger\n key={`${sheet.workbookSheetIndex}-${sheet.name}`}\n ref={(node) => {\n itemRefs.current[index] = node\n }}\n value={String(index)}\n className=\"max-w-48 flex-none\"\n onMouseEnter={() => handleItemEnter(index)}\n >\n <span className=\"truncate\">{sheet.name}</span>\n </TabsTrigger>\n ))}\n </TabsList>\n </div>\n </ScrollArea>\n </Tabs>\n {typeof document !== \"undefined\" &&\n previewSheet &&\n visiblePreviewIndex !== null &&\n previewUrl\n ? createPortal(\n <div\n className=\"pointer-events-none fixed z-40 translate-y-0 overflow-hidden rounded-lg border bg-background/95 opacity-100 shadow-xl backdrop-blur-md transition-[opacity,transform] duration-100\"\n style={{\n left: previewPosition.left,\n top: previewPosition.top,\n width: previewWidth,\n }}\n >\n <div className=\"relative aspect-[11/7] w-full overflow-hidden bg-muted/60\">\n <img\n key={`${workbookIdentity}-${visiblePreviewIndex}-${previewUrl}`}\n src={previewUrl}\n alt={`${previewSheet.name} preview`}\n className=\"absolute inset-0 h-full w-full object-cover object-left-top\"\n />\n </div>\n </div>,\n document.body\n )\n : null}\n </div>\n )\n})\n\nexport function XlsxWorkbookSurface({\n className,\n isDark,\n onDownload,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showDownloadButton = true,\n showNightRenderToggle,\n showToolbar = true,\n showUploadButton = true,\n toolbarActions,\n workbookIdentity,\n}: {\n className?: string\n isDark: boolean\n onDownload?: () => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showDownloadButton?: boolean\n showNightRenderToggle: boolean\n showToolbar?: boolean\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n workbookIdentity: string\n}) {\n const { error } = useXlsxViewer()\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const renderSearchableScroller = React.useCallback(\n ({ children, viewportProps }: XlsxScrollerRenderProps) => (\n <ScrollArea\n className=\"h-full min-h-0 w-full min-w-0 flex-1\"\n viewportProps={viewportProps}\n viewportRef={viewportRef}\n >\n {children}\n </ScrollArea>\n ),\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 {showToolbar ? (\n <WorkbookToolbar\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showUploadButton={showUploadButton}\n toolbarActions={toolbarActions}\n viewportRef={viewportRef}\n workbookIdentity={workbookIdentity}\n />\n ) : null}\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <div className=\"min-h-0 flex-1 bg-muted/20\">\n <XlsxViewer\n experimentalCanvas\n allowResizeInReadOnly\n className=\"h-full min-h-0 min-w-0\"\n height=\"100%\"\n isDark={isDark}\n readOnly\n rounded={false}\n showDefaultToolbar={false}\n showImages\n fileTooLargeState={\n <div className=\"grid h-full w-full min-w-full place-items-center p-6\">\n <div className=\"max-w-sm rounded-lg border bg-background p-4 text-sm\">\n <p className=\"font-medium\">File too large</p>\n <p className=\"mt-1 text-muted-foreground\">\n This workbook exceeds the display limit. Download it to view\n the full file.\n </p>\n </div>\n </div>\n }\n loadingState={<ViewerLoadingSurface />}\n renderScroller={renderSearchableScroller}\n errorState={\n <div className=\"grid h-full w-full min-w-full place-items-center p-6 text-sm text-destructive\">\n {error?.message ?? \"Unable to display workbook.\"}\n </div>\n }\n renderTableHeaderMenu={renderTableHeaderMenu}\n />\n </div>\n <WorkbookSheetTabs workbookIdentity={workbookIdentity} />\n </div>\n </div>\n )\n}\n\nexport function XlsxViewerPreview({\n className,\n fileName,\n isDark,\n onIsDarkChange,\n showDownload = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n}: {\n className?: string\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n showDownload?: boolean\n showToolbar?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n}) {\n return (\n <XlsxViewerContent\n className={className}\n effectiveIsDark={isDark}\n fileName={fileName}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n showDownload={showDownload}\n showToolbar={showToolbar}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n url={src}\n />\n )\n}\n\nfunction XlsxViewerContent({\n className,\n effectiveIsDark,\n fileName,\n setNightRenderEnabled,\n shouldRenderNightMode,\n showDownload,\n showToolbar = true,\n showUpload,\n toolbarActions,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n showDownload: boolean\n showToolbar?: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const [uploadedWorkbook, setUploadedWorkbook] =\n React.useState<UploadedWorkbook | null>(null)\n const sourceFileName = React.useMemo(\n () =>\n url ? formatWorkbookName(fileName, url) : (fileName ?? \"workbook.xlsx\"),\n [fileName, url]\n )\n const displayFileName = React.useMemo(\n () => uploadedWorkbook?.fileName ?? sourceFileName,\n [sourceFileName, uploadedWorkbook?.fileName]\n )\n const workbookIdentity = React.useMemo(\n () => uploadedWorkbook?.identity ?? `${url ?? \"empty\"}::${displayFileName}`,\n [displayFileName, uploadedWorkbook?.identity, url]\n )\n const [workbookBuffer, setWorkbookBuffer] =\n React.useState<ArrayBuffer | null>(null)\n const [loadError, setLoadError] = React.useState<string>()\n const shouldShowLoadingSpinner = useDelayedLoadingIndicator(\n !workbookBuffer && !loadError && !uploadedWorkbook,\n XLSX_LOADING_INDICATOR_DELAY_MS\n )\n\n React.useEffect(() => {\n let isCurrent = true\n if (url) {\n setUploadedWorkbook(null)\n }\n\n async function loadWorkbook(): Promise<void> {\n if (!url) {\n setWorkbookBuffer(null)\n setLoadError(undefined)\n return\n }\n\n setWorkbookBuffer(null)\n setLoadError(undefined)\n\n try {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch XLSX (${response.status})`)\n }\n\n const nextWorkbookBuffer = await response.arrayBuffer()\n if (!isCurrent) return\n\n setWorkbookBuffer(nextWorkbookBuffer)\n } catch (error) {\n if (!isCurrent) return\n\n setLoadError(\n error instanceof Error ? error.message : \"Unknown XLSX load error\"\n )\n }\n }\n\n void loadWorkbook()\n\n return () => {\n isCurrent = false\n }\n }, [url])\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 const buffer = await file.arrayBuffer()\n setLoadError(undefined)\n setUploadedWorkbook({\n buffer,\n fileName: file.name,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n const activeBuffer = uploadedWorkbook?.buffer ?? workbookBuffer\n const activeFileName = uploadedWorkbook?.fileName ?? displayFileName\n const activeIdentity = workbookIdentity\n\n if (!url && !uploadedWorkbook) {\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=\".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n <WorkbookStandaloneToolbar\n onUploadClick={() => fileInputRef.current?.click()}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n />\n <div className=\"grid min-h-0 flex-1 place-items-center bg-muted/30 p-4\">\n <div className=\"max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs\">\n <p className=\"font-medium\">Upload a workbook to preview</p>\n <p className=\"mt-1 text-muted-foreground\">\n Pass an XLSX URL with the <code>src</code> prop or upload a file.\n </p>\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 XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (loadError && !activeBuffer) {\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=\".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n <WorkbookStandaloneToolbar\n onUploadClick={() => fileInputRef.current?.click()}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n />\n <div className=\"grid min-h-0 flex-1 place-items-center bg-muted/30 p-4\">\n <div className=\"max-w-md rounded-lg border bg-background p-4 text-sm\">\n <p className=\"font-medium\">Unable to display workbook</p>\n <p className=\"mt-1 text-muted-foreground\">{loadError}</p>\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 XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (!activeBuffer) {\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=\".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n <WorkbookStandaloneToolbar\n onUploadClick={() => fileInputRef.current?.click()}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n />\n <ViewerLoadingSurface showSpinner={shouldShowLoadingSpinner} />\n </div>\n )\n }\n\n return (\n <div className={cn(\"overflow-hidden\", className)}>\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n <XlsxWorkbookLoadedViewer\n className={className}\n fileName={activeFileName}\n isDark={effectiveIsDark}\n onDownload={() => downloadWorkbookBuffer(activeBuffer, activeFileName)}\n onIsDarkChange={setNightRenderEnabled}\n onUploadClick={() => fileInputRef.current?.click()}\n renderTableHeaderMenu={(props) => (\n <WorkbookTableHeaderMenu {...props} />\n )}\n showDownloadButton={showDownload}\n showNightRenderToggle={shouldRenderNightMode}\n showToolbar={showToolbar}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n workbookBuffer={activeBuffer}\n workbookIdentity={activeIdentity}\n />\n </div>\n )\n}\n\nfunction XlsxWorkbookLoadedViewer({\n className,\n fileName,\n isDark,\n onDownload,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showDownloadButton,\n showNightRenderToggle,\n showToolbar = true,\n showUploadButton,\n toolbarActions,\n workbookBuffer,\n workbookIdentity,\n}: {\n className?: string\n fileName: string\n isDark: boolean\n onDownload: () => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showDownloadButton: boolean\n showNightRenderToggle: boolean\n showToolbar?: boolean\n showUploadButton: boolean\n toolbarActions?: React.ReactNode\n workbookBuffer: ArrayBuffer\n workbookIdentity: string\n}) {\n const controller = useXlsxViewerController(\n React.useMemo(\n () => ({\n allowResizeInReadOnly: true,\n file: workbookBuffer,\n fileName,\n maxFileSizeBytes: XLSX_MAX_FILE_SIZE_BYTES,\n readOnly: true,\n useWorker: true,\n }),\n [fileName, workbookBuffer]\n )\n )\n\n return (\n <XlsxViewerProvider controller={controller} isDark={isDark}>\n <XlsxWorkbookSurface\n className={className}\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n renderTableHeaderMenu={renderTableHeaderMenu}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showToolbar={showToolbar}\n showUploadButton={showUploadButton}\n toolbarActions={toolbarActions}\n workbookIdentity={workbookIdentity}\n />\n </XlsxViewerProvider>\n )\n}\n"+ '"use client"\n\nimport * as React from "react"\nimport {\n useXlsxViewer,\n useXlsxViewerController,\n useXlsxViewerThumbnails,\n useXlsxViewerZoom,\n XlsxViewer,\n XlsxViewerProvider,\n type XlsxCellAddress,\n type XlsxScrollerRenderProps,\n type XlsxSheetData,\n type XlsxTableHeaderMenuRenderProps,\n type XlsxViewerController,\n} from "@extend-ai/react-xlsx"\nimport { createPortal } from "react-dom"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuRadioGroup,\n DropdownMenuRadioItem,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { Input } from "@/components/ui/input"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from "@/components/ui/popover"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nconst XLSX_LOADING_INDICATOR_DELAY_MS = 300\nconst XLSX_DROPDOWN_Z_INDEX_CLASS = "z-40"\nconst XLSX_SEARCH_BATCH_ROW_COUNT = 500\nconst XLSX_SEARCH_DEBOUNCE_MS = 300\nconst XLSX_GRID_HEADER_HEIGHT = 24\nconst XLSX_GRID_ROW_HEADER_WIDTH = 40\nconst XLSX_MAX_FILE_SIZE_BYTES = 50 * 1024 * 1024\nconst ZOOM_OPTIONS = [10, 25, 50, 75, 100, 125, 150, 175, 200, 400] as const\n\n// Stable reference so the thumbnails memo isn\'t invalidated on every render\n// (e.g. by selection changes), which would recompute every sheet thumbnail.\nconst XLSX_SHEET_TAB_THUMBNAIL_OPTIONS = {\n resolution: {\n maxHeight: 360,\n maxWidth: 560,\n },\n} as const\n\ntype UploadedWorkbook = {\n buffer: ArrayBuffer\n fileName: string\n identity: string\n}\n\ntype XlsxSearchResult = {\n cell: XlsxCellAddress\n displayValue: string\n formula?: string\n sheetIndex: number\n sheetName: string\n workbookSheetIndex: number\n}\n\ntype XlsxBatchCell = {\n col?: unknown\n formula?: unknown\n value?: unknown\n}\n\ntype XlsxBatchRow = {\n cells?: unknown\n index?: unknown\n}\n\nfunction formatWorkbookName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "workbook.xlsx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction ensureWorkbookExtension(fileName: string) {\n const lowerFileName = fileName.toLowerCase()\n return lowerFileName.endsWith(".xlsx") || lowerFileName.endsWith(".xls")\n ? fileName\n : `${fileName}.xlsx`\n}\n\nfunction downloadWorkbookBuffer(buffer: ArrayBuffer, fileName: string) {\n const resolvedFileName = ensureWorkbookExtension(fileName)\n const blob = new Blob([buffer], {\n type: resolvedFileName.toLowerCase().endsWith(".xls")\n ? "application/vnd.ms-excel"\n : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",\n })\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = resolvedFileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nfunction normalizeSearchText(value: unknown) {\n return typeof value === "string"\n ? value\n : value === null || value === undefined\n ? ""\n : String(value)\n}\n\nfunction cellValueToSearchText(value: unknown) {\n if (!value || typeof value !== "object") return normalizeSearchText(value)\n\n const record = value as {\n asBoolean?: () => boolean | null\n asError?: () => string | null\n asNumber?: () => number | null\n asText?: () => string | null\n is_boolean?: boolean\n is_empty?: boolean\n is_error?: boolean\n is_number?: boolean\n is_text?: boolean\n }\n\n if (record.is_empty) return ""\n if (record.is_error) return record.asError?.() ?? ""\n if (record.is_text) return record.asText?.() ?? ""\n if (record.is_number) return normalizeSearchText(record.asNumber?.())\n if (record.is_boolean) return record.asBoolean?.() ? "TRUE" : "FALSE"\n\n return normalizeSearchText(value)\n}\n\nfunction getCellSearchText(\n controller: XlsxViewerController,\n sheet: XlsxSheetData,\n row: number,\n col: number\n) {\n const worksheet = controller.workbook?.getSheet(sheet.workbookSheetIndex)\n if (!worksheet) return { displayValue: "", formula: "" }\n\n const formula = worksheet.getFormulaAt(row, col) ?? ""\n const cachedFormulaValue = formula\n ? sheet.cachedFormulaValues[cellAddressToA1({ row, col })]\n : undefined\n const formatted = worksheet.getFormattedValueAt(row, col)\n\n if (\n formatted &&\n !(formula && cachedFormulaValue !== undefined && formatted.startsWith("#"))\n ) {\n return { displayValue: formatted, formula }\n }\n\n const calculated = worksheet.getCalculatedValueAt(row, col)\n const displayValue =\n formula && cachedFormulaValue !== undefined && calculated.is_error\n ? cachedFormulaValue\n : cellValueToSearchText(calculated)\n\n return { displayValue, formula }\n}\n\nfunction getBatchRows(rows: unknown): XlsxBatchRow[] {\n return Array.isArray(rows) ? (rows as XlsxBatchRow[]) : []\n}\n\nfunction getBatchCells(row: XlsxBatchRow): XlsxBatchCell[] {\n return Array.isArray(row.cells) ? (row.cells as XlsxBatchCell[]) : []\n}\n\nfunction cellMatchesQuery(\n displayValue: string,\n formula: string,\n query: string\n) {\n return (\n displayValue.toLowerCase().includes(query) ||\n formula.toLowerCase().includes(query)\n )\n}\n\nfunction cellAddressToA1({ col, row }: XlsxCellAddress) {\n let columnNumber = col + 1\n let columnName = ""\n\n while (columnNumber > 0) {\n const remainder = (columnNumber - 1) % 26\n columnName = String.fromCharCode(65 + remainder) + columnName\n columnNumber = Math.floor((columnNumber - 1) / 26)\n }\n\n return `${columnName}${row + 1}`\n}\n\nasync function findXlsxSearchResults(\n controller: XlsxViewerController,\n rawQuery: string\n) {\n const query = rawQuery.trim().toLowerCase()\n if (!query) return []\n\n const results: XlsxSearchResult[] = []\n\n for (const [sheetIndex, sheet] of controller.sheets.entries()) {\n const startRow = Math.max(0, sheet.minUsedRow)\n const endRow = Math.max(startRow, sheet.maxUsedRow)\n const visibleCols = sheet.visibleCols.filter(\n (col) => col >= sheet.minUsedCol && col <= sheet.maxUsedCol\n )\n const visibleRowSet = new Set(sheet.visibleRows)\n const visibleColSet = new Set(visibleCols)\n\n if (!visibleCols.length || sheet.maxUsedRow < sheet.minUsedRow) continue\n\n const worksheet = controller.workbook?.getSheet(sheet.workbookSheetIndex)\n const worksheetWithBatch = worksheet as\n | {\n getRowsBatch?: (\n startRow: number,\n rowCount: number,\n options?: Record<string, unknown>\n ) => unknown\n }\n | undefined\n\n for (\n let batchStartRow = startRow;\n batchStartRow <= endRow;\n batchStartRow += XLSX_SEARCH_BATCH_ROW_COUNT\n ) {\n const rowCount = Math.min(\n XLSX_SEARCH_BATCH_ROW_COUNT,\n endRow - batchStartRow + 1\n )\n const rows = controller.getRowsBatchAsync\n ? await controller.getRowsBatchAsync(\n sheet.workbookSheetIndex,\n batchStartRow,\n rowCount\n )\n : worksheetWithBatch?.getRowsBatch?.(batchStartRow, rowCount, {\n includeFormulas: true,\n useFormattedValues: true,\n })\n\n if (rows) {\n for (const rowEntry of getBatchRows(rows)) {\n const row = Number(rowEntry.index)\n if (!Number.isInteger(row) || !visibleRowSet.has(row)) {\n continue\n }\n\n for (const cellEntry of getBatchCells(rowEntry)) {\n const col = Number(cellEntry.col)\n if (!Number.isInteger(col) || !visibleColSet.has(col)) continue\n\n const displayValue = normalizeSearchText(cellEntry.value)\n const formula = normalizeSearchText(cellEntry.formula)\n\n if (!cellMatchesQuery(displayValue, formula, query)) continue\n\n results.push({\n cell: { row, col },\n displayValue,\n formula,\n sheetIndex,\n sheetName: sheet.name,\n workbookSheetIndex: sheet.workbookSheetIndex,\n })\n }\n }\n continue\n }\n\n if (!worksheet) continue\n\n const batchEndRow = batchStartRow + rowCount - 1\n for (const row of sheet.visibleRows) {\n if (row < batchStartRow || row > batchEndRow) continue\n\n for (const col of visibleCols) {\n const { displayValue, formula } = getCellSearchText(\n controller,\n sheet,\n row,\n col\n )\n\n if (!cellMatchesQuery(displayValue, formula, query)) continue\n\n results.push({\n cell: { row, col },\n displayValue,\n formula,\n sheetIndex,\n sheetName: sheet.name,\n workbookSheetIndex: sheet.workbookSheetIndex,\n })\n }\n }\n }\n }\n\n return results\n}\n\nfunction sumAxisBefore(values: number[], endIndex: number, zoomFactor: number) {\n let total = 0\n for (let index = 0; index < endIndex; index += 1) {\n total += (values[index] ?? 0) * zoomFactor\n }\n return total\n}\n\nfunction scrollXlsxCellIntoView({\n controller,\n result,\n viewport,\n}: {\n controller: XlsxViewerController\n result: XlsxSearchResult\n viewport: HTMLDivElement | null\n}) {\n if (!viewport) return\n\n const sheet = controller.sheets[result.sheetIndex]\n if (!sheet) return\n\n const rowIndex = sheet.visibleRows.indexOf(result.cell.row)\n const colIndex = sheet.visibleCols.indexOf(result.cell.col)\n if (rowIndex < 0 || colIndex < 0) return\n\n const zoomFactor = Math.max(0.1, controller.zoomScale / 100)\n const headerHeight = XLSX_GRID_HEADER_HEIGHT * zoomFactor\n const rowHeaderWidth = XLSX_GRID_ROW_HEADER_WIDTH * zoomFactor\n const rowStart =\n headerHeight + sumAxisBefore(sheet.rowHeights, rowIndex, zoomFactor)\n const colStart =\n rowHeaderWidth + sumAxisBefore(sheet.colWidths, colIndex, zoomFactor)\n const rowHeight =\n (sheet.rowHeights[rowIndex] ?? sheet.defaultRowHeightPx) * zoomFactor\n const colWidth =\n (sheet.colWidths[colIndex] ?? sheet.defaultColWidthPx) * zoomFactor\n const rowEnd = rowStart + rowHeight\n const colEnd = colStart + colWidth\n let nextTop = viewport.scrollTop\n let nextLeft = viewport.scrollLeft\n const visibleTop = viewport.scrollTop + headerHeight\n const visibleLeft = viewport.scrollLeft + rowHeaderWidth\n const visibleBottom = viewport.scrollTop + viewport.clientHeight\n const visibleRight = viewport.scrollLeft + viewport.clientWidth\n\n if (rowStart < visibleTop) {\n nextTop = rowStart - headerHeight\n } else if (rowEnd > visibleBottom) {\n nextTop = rowEnd - viewport.clientHeight\n }\n\n if (colStart < visibleLeft) {\n nextLeft = colStart - rowHeaderWidth\n } else if (colEnd > visibleRight) {\n nextLeft = colEnd - viewport.clientWidth\n }\n\n viewport.scrollTo({\n left: Math.max(0, nextLeft),\n top: Math.max(0, nextTop),\n behavior: "auto",\n })\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 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 w-full min-w-full place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction WorkbookFileActionsMenu({\n isDark,\n onDownload,\n onIsDarkChange,\n onUploadClick,\n showDownloadButton,\n showNightRenderToggle = false,\n showUploadButton,\n}: {\n isDark?: boolean\n onDownload?: () => void\n onIsDarkChange?: (checked: boolean) => void\n onUploadClick: () => void\n showDownloadButton: boolean\n showNightRenderToggle?: boolean\n showUploadButton: boolean\n}) {\n const showThemeControl = showNightRenderToggle && Boolean(onIsDarkChange)\n const showFileActions = (showDownloadButton && onDownload) || showUploadButton\n if (!showThemeControl && !showFileActions) return null\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open workbook actions"\n >\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className="size-4"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align="end"\n className={cn("w-52", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n {showThemeControl ? (\n <>\n <DropdownMenuCheckboxItem\n checked={Boolean(isDark)}\n variant="switch"\n onCheckedChange={(checked) => onIsDarkChange?.(checked === true)}\n >\n <span className="flex min-w-0 items-center gap-2">\n <IconPlaceholder\n lucide="Moon"\n tabler="IconMoon"\n hugeicons="Moon02Icon"\n phosphor="MoonIcon"\n remixicon="RiMoonLine"\n className="size-4"\n />\n Dark mode\n </span>\n </DropdownMenuCheckboxItem>\n {showFileActions ? <DropdownMenuSeparator /> : null}\n </>\n ) : null}\n {showDownloadButton && onDownload ? (\n <DropdownMenuItem onClick={onDownload}>\n <IconPlaceholder\n lucide="Download"\n tabler="IconDownload"\n hugeicons="Download01Icon"\n phosphor="DownloadSimpleIcon"\n remixicon="RiDownload2Line"\n className="size-4"\n />\n Download\n </DropdownMenuItem>\n ) : null}\n {showUploadButton ? (\n <DropdownMenuItem onClick={onUploadClick}>\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nexport function renderXlsxScroller({\n children,\n viewportProps,\n}: XlsxScrollerRenderProps) {\n return (\n <ScrollArea\n className="h-full min-h-0 w-full min-w-0 flex-1"\n viewportProps={viewportProps}\n >\n {children}\n </ScrollArea>\n )\n}\n\nexport function WorkbookTableHeaderMenu({\n direction,\n sortAscending,\n sortDescending,\n triggerIcon,\n triggerProps,\n}: XlsxTableHeaderMenuRenderProps) {\n const [open, setOpen] = React.useState(false)\n\n return (\n <DropdownMenu open={open} onOpenChange={setOpen}>\n <DropdownMenuTrigger asChild>\n <Button\n {...triggerProps}\n type="button"\n variant="ghost"\n size="icon-sm"\n className={cn("size-6 rounded-sm", triggerProps.className)}\n aria-label="Column menu"\n >\n {triggerIcon ? (\n triggerIcon\n ) : (\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className="size-3.5"\n />\n )}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align="end"\n className={cn("w-40", XLSX_DROPDOWN_Z_INDEX_CLASS)}\n >\n <DropdownMenuRadioGroup\n value={direction ?? ""}\n onValueChange={(value) => {\n if (value === "ascending") {\n sortAscending()\n } else {\n sortDescending()\n }\n setOpen(false)\n }}\n >\n <DropdownMenuRadioItem value="ascending">\n Sort ascending\n </DropdownMenuRadioItem>\n <DropdownMenuRadioItem value="descending">\n Sort descending\n </DropdownMenuRadioItem>\n </DropdownMenuRadioGroup>\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction WorkbookSearchPopover({\n viewportRef,\n workbookIdentity,\n}: {\n viewportRef: React.RefObject<HTMLDivElement | null>\n workbookIdentity: string\n}) {\n const controller = useXlsxViewer()\n const [searchDraft, setSearchDraft] = React.useState("")\n const [searchQuery, setSearchQuery] = React.useState("")\n const [searchResults, setSearchResults] = React.useState<XlsxSearchResult[]>(\n []\n )\n const [activeResultIndex, setActiveResultIndex] = React.useState(0)\n const [isSearching, setIsSearching] = React.useState(false)\n const controllerRef = React.useRef(controller)\n const searchRequestIdRef = React.useRef(0)\n const appliedResultKeyRef = React.useRef("")\n const activeResult = searchResults[activeResultIndex] ?? null\n const activeResultKey = activeResult\n ? `${activeResult.workbookSheetIndex}:${activeResult.cell.row}:${activeResult.cell.col}`\n : ""\n const controlsDisabled =\n controller.isLoading ||\n Boolean(controller.error) ||\n !controller.sheets.length\n const hasActiveQuery = Boolean(searchQuery.trim())\n const resultLabel = isSearching\n ? "Searching"\n : !hasActiveQuery\n ? "No search"\n : searchResults.length\n ? `${activeResultIndex + 1} / ${searchResults.length}`\n : "No results"\n\n React.useEffect(() => {\n controllerRef.current = controller\n }, [controller])\n\n const runSearch = React.useCallback((rawQuery: string) => {\n const nextQuery = rawQuery.trim()\n const requestId = searchRequestIdRef.current + 1\n searchRequestIdRef.current = requestId\n appliedResultKeyRef.current = ""\n setSearchQuery(nextQuery)\n setActiveResultIndex(0)\n\n if (!nextQuery) {\n setSearchResults([])\n setIsSearching(false)\n return\n }\n\n setIsSearching(true)\n void findXlsxSearchResults(controllerRef.current, nextQuery)\n .then((nextResults) => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults(nextResults)\n })\n .catch(() => {\n if (searchRequestIdRef.current !== requestId) return\n setSearchResults([])\n })\n .finally(() => {\n if (searchRequestIdRef.current !== requestId) return\n setIsSearching(false)\n })\n }, [])\n\n React.useEffect(() => {\n const trimmedDraft = searchDraft.trim()\n\n if (!trimmedDraft) {\n runSearch("")\n return\n }\n\n setIsSearching(true)\n const timeoutId = window.setTimeout(() => {\n runSearch(searchDraft)\n }, XLSX_SEARCH_DEBOUNCE_MS)\n\n return () => window.clearTimeout(timeoutId)\n }, [runSearch, searchDraft])\n\n const clearSearch = React.useCallback(() => {\n searchRequestIdRef.current += 1\n setSearchDraft("")\n setSearchQuery("")\n setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = ""\n controller.clearSelection()\n }, [controller])\n\n const goToRelativeResult = React.useCallback(\n (direction: 1 | -1) => {\n if (!searchResults.length) return\n\n setActiveResultIndex((currentIndex) => {\n return (\n (currentIndex + direction + searchResults.length) %\n searchResults.length\n )\n })\n },\n [searchResults.length]\n )\n\n React.useEffect(() => {\n searchRequestIdRef.current += 1\n setSearchDraft("")\n setSearchQuery("")\n setSearchResults([])\n setActiveResultIndex(0)\n setIsSearching(false)\n appliedResultKeyRef.current = ""\n }, [workbookIdentity])\n\n React.useEffect(() => {\n if (!activeResult) return\n\n if (controller.activeSheetIndex !== activeResult.sheetIndex) {\n appliedResultKeyRef.current = ""\n controller.setActiveSheetIndex(activeResult.sheetIndex)\n return\n }\n\n if (appliedResultKeyRef.current === activeResultKey) return\n appliedResultKeyRef.current = activeResultKey\n controller.selectCell(activeResult.cell)\n\n const frame = window.requestAnimationFrame(() => {\n scrollXlsxCellIntoView({\n controller,\n result: activeResult,\n viewport: viewportRef.current,\n })\n })\n\n return () => window.cancelAnimationFrame(frame)\n }, [\n activeResult,\n activeResultKey,\n controller,\n controller.activeSheetIndex,\n viewportRef,\n ])\n\n return (\n <Popover>\n <ToolbarTooltip label="Search workbook">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search workbook"\n disabled={controlsDisabled}\n >\n <IconPlaceholder\n lucide="Search"\n tabler="IconSearch"\n hugeicons="Search01Icon"\n phosphor="MagnifyingGlassIcon"\n remixicon="RiSearchLine"\n className="size-4"\n />\n </Button>\n </PopoverTrigger>\n </ToolbarTooltip>\n <PopoverContent align="end" className="w-72">\n <div className="space-y-3">\n <Input\n placeholder="Search workbook"\n value={searchDraft}\n onChange={(event) => setSearchDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key !== "Enter") return\n\n event.preventDefault()\n if (event.shiftKey && searchResults.length) {\n goToRelativeResult(-1)\n } else if (searchResults.length) {\n goToRelativeResult(1)\n } else if (searchDraft.trim()) {\n runSearch(searchDraft)\n }\n }}\n />\n <div className="flex items-center justify-between gap-2">\n <div className="min-w-0 text-xs text-muted-foreground">\n <div className="truncate">\n {searchResults.length ? (\n <>\n <span className="text-primary">\n {activeResultIndex + 1}\n </span>\n {` / ${searchResults.length}`}\n </>\n ) : (\n resultLabel\n )}\n </div>\n {activeResult ? (\n <div className="mt-0.5 truncate">\n {activeResult.sheetName}!{cellAddressToA1(activeResult.cell)}\n </div>\n ) : null}\n </div>\n <div className="flex shrink-0 items-center gap-1">\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Previous result"\n disabled={isSearching || searchResults.length === 0}\n onClick={() => goToRelativeResult(-1)}\n >\n <IconPlaceholder\n lucide="ChevronLeft"\n tabler="IconChevronLeft"\n hugeicons="ArrowLeft01Icon"\n phosphor="CaretLeftIcon"\n remixicon="RiArrowLeftSLine"\n className="size-4"\n />\n </Button>\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Next result"\n disabled={isSearching || searchResults.length === 0}\n onClick={() => goToRelativeResult(1)}\n >\n <IconPlaceholder\n lucide="ArrowRight"\n tabler="IconArrowRight"\n hugeicons="ArrowRight01Icon"\n phosphor="ArrowRightIcon"\n remixicon="RiArrowRightLine"\n className="size-4"\n />\n </Button>\n </div>\n </div>\n <div className="flex justify-end">\n <Button\n type="button"\n variant="outline"\n size="sm"\n onClick={clearSearch}\n >\n Clear\n </Button>\n </div>\n </div>\n </PopoverContent>\n </Popover>\n )\n}\n\nfunction WorkbookToolbar({\n isDark,\n onDownload,\n onIsDarkChange,\n onUploadClick,\n showDownloadButton = true,\n showNightRenderToggle,\n showUploadButton = true,\n toolbarActions,\n viewportRef,\n workbookIdentity,\n}: {\n isDark: boolean\n onDownload?: () => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n showDownloadButton?: boolean\n showNightRenderToggle: boolean\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n viewportRef: React.RefObject<HTMLDivElement | null>\n workbookIdentity: string\n}) {\n const { canZoomIn, canZoomOut, setZoomScale, zoomIn, zoomOut, zoomScale } =\n useXlsxViewerZoom()\n const currentZoom = Math.round(zoomScale)\n\n React.useEffect(() => {\n setZoomScale(100)\n }, [setZoomScale, workbookIdentity])\n\n return (\n <div className="flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2">\n <TooltipProvider>\n <div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!canZoomOut}\n aria-label="Zoom out"\n onClick={zoomOut}\n >\n <IconPlaceholder\n lucide="CircleMinus"\n tabler="IconCircleMinus"\n hugeicons="MinusSignCircleIcon"\n phosphor="MinusCircleIcon"\n remixicon="RiIndeterminateCircleLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={currentZoom.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{currentZoom}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="end"\n alignItemWithTrigger={false}\n className={XLSX_DROPDOWN_Z_INDEX_CLASS}\n >\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={!canZoomIn}\n aria-label="Zoom in"\n onClick={zoomIn}\n >\n <IconPlaceholder\n lucide="CirclePlusIcon"\n tabler="IconCirclePlusFilled"\n hugeicons="PlusSignCircleIcon"\n phosphor="PlusCircleIcon"\n remixicon="RiAddCircleFill"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <WorkbookSearchPopover\n viewportRef={viewportRef}\n workbookIdentity={workbookIdentity}\n />\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n {(showDownloadButton && onDownload) ||\n showUploadButton ||\n showNightRenderToggle ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <WorkbookFileActionsMenu\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showUploadButton={showUploadButton}\n />\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction WorkbookStandaloneToolbar({\n onUploadClick,\n showUploadButton = true,\n toolbarActions,\n}: {\n onUploadClick: () => void\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n}) {\n return (\n <div className="flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2">\n <TooltipProvider>\n <div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">\n {toolbarActions ? <>{toolbarActions}</> : null}\n {showUploadButton ? (\n <>\n {toolbarActions ? (\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n ) : null}\n <WorkbookFileActionsMenu\n onUploadClick={onUploadClick}\n showDownloadButton={false}\n showUploadButton={showUploadButton}\n />\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\ntype WorkbookSheetTab = {\n name: string\n workbookSheetIndex: number\n}\n\ntype WorkbookSheetTabsInnerProps = {\n activeSheetIndex: number\n onActiveSheetIndexChange: (index: number) => void\n sheets: WorkbookSheetTab[]\n workbookIdentity: string\n}\n\nexport function WorkbookSheetTabs({\n workbookIdentity,\n}: {\n workbookIdentity: string\n}) {\n const { activeSheetIndex, setActiveSheetIndex, sheets } = useXlsxViewer()\n\n const handleActiveSheetIndexChange = React.useCallback(\n (index: number) => setActiveSheetIndex(index),\n [setActiveSheetIndex]\n )\n\n return (\n <WorkbookSheetTabsInner\n activeSheetIndex={activeSheetIndex}\n onActiveSheetIndexChange={handleActiveSheetIndexChange}\n sheets={sheets}\n workbookIdentity={workbookIdentity}\n />\n )\n}\n\nconst WorkbookSheetTabsInner = React.memo(function WorkbookSheetTabsInner({\n activeSheetIndex,\n onActiveSheetIndexChange,\n sheets,\n workbookIdentity,\n}: WorkbookSheetTabsInnerProps) {\n const [visiblePreviewIndex, setVisiblePreviewIndex] = React.useState<\n number | null\n >(null)\n const [previewPosition, setPreviewPosition] = React.useState({\n left: 0,\n top: 0,\n })\n const { thumbnails } = useXlsxViewerThumbnails(\n XLSX_SHEET_TAB_THUMBNAIL_OPTIONS\n )\n const [thumbnailUrls, setThumbnailUrls] = React.useState<\n Record<number, string>\n >({})\n const scrollRef = React.useRef<HTMLDivElement | null>(null)\n const itemRefs = React.useRef<Record<number, HTMLButtonElement | null>>({})\n const openTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(\n null\n )\n const closeTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(\n null\n )\n const previewWidth = 220\n const previewHeight = (previewWidth * 7) / 11\n const previewGap = 12\n const previewOpenDelayMs = 500\n\n const clearOpenTimeout = React.useCallback(() => {\n if (openTimeoutRef.current) {\n clearTimeout(openTimeoutRef.current)\n openTimeoutRef.current = null\n }\n }, [])\n\n const clearCloseTimeout = React.useCallback(() => {\n if (closeTimeoutRef.current) {\n clearTimeout(closeTimeoutRef.current)\n closeTimeoutRef.current = null\n }\n }, [])\n\n const getPreviewPosition = React.useCallback(\n (sheetIndex: number) => {\n const item = itemRefs.current[sheetIndex]\n if (!item || typeof window === "undefined") {\n return { left: 0, top: 0 }\n }\n\n const itemRect = item.getBoundingClientRect()\n const centeredLeft = itemRect.left + itemRect.width / 2 - previewWidth / 2\n const minLeft = 8\n const maxLeft = Math.max(minLeft, window.innerWidth - previewWidth - 8)\n const left = Math.max(minLeft, Math.min(centeredLeft, maxLeft))\n const top = Math.max(8, itemRect.top - previewHeight - previewGap)\n\n return { left, top }\n },\n [previewHeight]\n )\n\n const updatePreviewPosition = React.useCallback(\n (sheetIndex: number) => {\n setPreviewPosition(getPreviewPosition(sheetIndex))\n },\n [getPreviewPosition]\n )\n\n const handleItemEnter = React.useCallback(\n (sheetIndex: number) => {\n clearCloseTimeout()\n const nextPreviewPosition = getPreviewPosition(sheetIndex)\n\n if (visiblePreviewIndex !== null) {\n clearOpenTimeout()\n setPreviewPosition(nextPreviewPosition)\n setVisiblePreviewIndex(sheetIndex)\n return\n }\n\n clearOpenTimeout()\n openTimeoutRef.current = setTimeout(() => {\n setPreviewPosition(nextPreviewPosition)\n setVisiblePreviewIndex(sheetIndex)\n }, previewOpenDelayMs)\n },\n [\n clearCloseTimeout,\n clearOpenTimeout,\n getPreviewPosition,\n visiblePreviewIndex,\n ]\n )\n\n const handleContainerLeave = React.useCallback(() => {\n clearOpenTimeout()\n clearCloseTimeout()\n closeTimeoutRef.current = setTimeout(() => {\n setVisiblePreviewIndex(null)\n }, 80)\n }, [clearCloseTimeout, clearOpenTimeout])\n\n React.useEffect(() => {\n return () => {\n clearOpenTimeout()\n clearCloseTimeout()\n }\n }, [clearCloseTimeout, clearOpenTimeout])\n\n React.useEffect(() => {\n clearOpenTimeout()\n clearCloseTimeout()\n setVisiblePreviewIndex(null)\n setPreviewPosition({ left: 0, top: 0 })\n setThumbnailUrls({})\n }, [clearCloseTimeout, clearOpenTimeout, workbookIdentity])\n\n React.useEffect(() => {\n thumbnails.forEach((thumbnail) => {\n setThumbnailUrls((current) => {\n if (current[thumbnail.sheetIndex]) return current\n\n const canvas = document.createElement("canvas")\n canvas.width = thumbnail.width\n canvas.height = thumbnail.height\n\n if (!thumbnail.paint(canvas)) return current\n\n return {\n ...current,\n [thumbnail.sheetIndex]: canvas.toDataURL("image/png"),\n }\n })\n })\n }, [thumbnails])\n\n React.useEffect(() => {\n if (visiblePreviewIndex === null) return\n\n const handleReposition = () => updatePreviewPosition(visiblePreviewIndex)\n handleReposition()\n\n const scrollElement = scrollRef.current\n window.addEventListener("resize", handleReposition)\n scrollElement?.addEventListener("scroll", handleReposition, {\n passive: true,\n })\n\n return () => {\n window.removeEventListener("resize", handleReposition)\n scrollElement?.removeEventListener("scroll", handleReposition)\n }\n }, [updatePreviewPosition, visiblePreviewIndex])\n\n // The preview card portals to document.body, so it outlives the tab\n // strip\'s own visibility: when the viewer is hidden or reparented under\n // the cursor (keep-alive preview pools, a closing dialog) no mouseleave\n // fires and the card would hang on screen. While the preview is open,\n // poll the strip\'s effective visibility and dismiss as soon as it stops\n // being shown.\n React.useEffect(() => {\n if (visiblePreviewIndex === null) return\n\n const dismissWhenHidden = () => {\n const element = scrollRef.current\n const isVisible = Boolean(\n element?.isConnected &&\n (element.checkVisibility?.({ checkVisibilityCSS: true }) ?? true)\n )\n\n if (isVisible) return\n clearOpenTimeout()\n clearCloseTimeout()\n setVisiblePreviewIndex(null)\n }\n const interval = setInterval(dismissWhenHidden, 200)\n\n return () => clearInterval(interval)\n }, [clearCloseTimeout, clearOpenTimeout, visiblePreviewIndex])\n\n if (sheets.length <= 1) return null\n\n const previewSheet =\n visiblePreviewIndex === null ? null : sheets[visiblePreviewIndex]\n const previewUrl =\n visiblePreviewIndex === null\n ? null\n : (thumbnailUrls[visiblePreviewIndex] ?? null)\n\n return (\n <div\n className="border-t bg-muted/40 px-3 py-2"\n onMouseLeave={handleContainerLeave}\n >\n <Tabs\n value={String(activeSheetIndex)}\n onValueChange={(value) => onActiveSheetIndexChange(Number(value))}\n className="gap-0"\n >\n <ScrollArea\n orientation="horizontal"\n scrollbarGutter\n className="h-10 w-full has-[[data-slot=scroll-area-viewport][data-has-overflow-x]]:h-[50px]"\n viewportClassName="overflow-y-hidden"\n viewportRef={scrollRef}\n >\n <div className="flex h-full items-center">\n <TabsList className="shrink-0">\n {sheets.map((sheet, index) => (\n <TabsTrigger\n key={`${sheet.workbookSheetIndex}-${sheet.name}`}\n ref={(node) => {\n itemRefs.current[index] = node\n }}\n value={String(index)}\n className="max-w-48 flex-none"\n onMouseEnter={() => handleItemEnter(index)}\n >\n <span className="truncate">{sheet.name}</span>\n </TabsTrigger>\n ))}\n </TabsList>\n </div>\n </ScrollArea>\n </Tabs>\n {typeof document !== "undefined" &&\n previewSheet &&\n visiblePreviewIndex !== null &&\n previewUrl\n ? createPortal(\n <div\n className="pointer-events-none fixed z-40 translate-y-0 overflow-hidden rounded-lg border bg-background/95 opacity-100 shadow-xl backdrop-blur-md transition-[opacity,transform] duration-100"\n style={{\n left: previewPosition.left,\n top: previewPosition.top,\n width: previewWidth,\n }}\n >\n <div className="relative aspect-[11/7] w-full overflow-hidden bg-muted/60">\n {/* eslint-disable-next-line @next/next/no-img-element -- Workbook sheet previews are generated runtime image URLs. */}\n <img\n key={`${workbookIdentity}-${visiblePreviewIndex}-${previewUrl}`}\n src={previewUrl}\n alt={`${previewSheet.name} preview`}\n className="absolute inset-0 h-full w-full object-cover object-left-top"\n />\n </div>\n </div>,\n document.body\n )\n : null}\n </div>\n )\n})\n\nexport function XlsxWorkbookSurface({\n className,\n isDark,\n onDownload,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showDownloadButton = true,\n showNightRenderToggle,\n showToolbar = true,\n showUploadButton = true,\n toolbarActions,\n workbookIdentity,\n}: {\n className?: string\n isDark: boolean\n onDownload?: () => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showDownloadButton?: boolean\n showNightRenderToggle: boolean\n showToolbar?: boolean\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n workbookIdentity: string\n}) {\n const { error } = useXlsxViewer()\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const renderSearchableScroller = React.useCallback(\n ({ children, viewportProps }: XlsxScrollerRenderProps) => (\n <ScrollArea\n className="h-full min-h-0 w-full min-w-0 flex-1"\n viewportProps={viewportProps}\n viewportRef={viewportRef}\n >\n {children}\n </ScrollArea>\n ),\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 {showToolbar ? (\n <WorkbookToolbar\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showUploadButton={showUploadButton}\n toolbarActions={toolbarActions}\n viewportRef={viewportRef}\n workbookIdentity={workbookIdentity}\n />\n ) : null}\n <div className="flex min-h-0 flex-1 flex-col">\n <div className="min-h-0 flex-1 bg-muted/20">\n <XlsxViewer\n experimentalCanvas\n allowResizeInReadOnly\n className="h-full min-h-0 min-w-0"\n height="100%"\n isDark={isDark}\n readOnly\n rounded={false}\n showDefaultToolbar={false}\n showImages\n fileTooLargeState={\n <div className="grid h-full w-full min-w-full place-items-center p-6">\n <div className="max-w-sm rounded-lg border bg-background p-4 text-sm">\n <p className="font-medium">File too large</p>\n <p className="mt-1 text-muted-foreground">\n This workbook exceeds the display limit. Download it to view\n the full file.\n </p>\n </div>\n </div>\n }\n loadingState={<ViewerLoadingSurface />}\n renderScroller={renderSearchableScroller}\n errorState={\n <div className="grid h-full w-full min-w-full place-items-center p-6 text-sm text-destructive">\n {error?.message ?? "Unable to display workbook."}\n </div>\n }\n renderTableHeaderMenu={renderTableHeaderMenu}\n />\n </div>\n <WorkbookSheetTabs workbookIdentity={workbookIdentity} />\n </div>\n </div>\n )\n}\n\nexport function XlsxViewerPreview({\n className,\n fileName,\n isDark,\n onIsDarkChange,\n showDownload = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n}: {\n className?: string\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n showDownload?: boolean\n showToolbar?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n}) {\n return (\n <XlsxViewerContent\n className={className}\n effectiveIsDark={isDark}\n fileName={fileName}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n showDownload={showDownload}\n showToolbar={showToolbar}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n url={src}\n />\n )\n}\n\nfunction XlsxViewerContent({\n className,\n effectiveIsDark,\n fileName,\n setNightRenderEnabled,\n shouldRenderNightMode,\n showDownload,\n showToolbar = true,\n showUpload,\n toolbarActions,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n showDownload: boolean\n showToolbar?: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const [uploadedWorkbook, setUploadedWorkbook] =\n React.useState<UploadedWorkbook | null>(null)\n const sourceFileName = React.useMemo(\n () =>\n url ? formatWorkbookName(fileName, url) : (fileName ?? "workbook.xlsx"),\n [fileName, url]\n )\n const displayFileName = React.useMemo(\n () => uploadedWorkbook?.fileName ?? sourceFileName,\n [sourceFileName, uploadedWorkbook?.fileName]\n )\n const workbookIdentity = React.useMemo(\n () => uploadedWorkbook?.identity ?? `${url ?? "empty"}::${displayFileName}`,\n [displayFileName, uploadedWorkbook?.identity, url]\n )\n const [workbookBuffer, setWorkbookBuffer] =\n React.useState<ArrayBuffer | null>(null)\n const [loadError, setLoadError] = React.useState<string>()\n const shouldShowLoadingSpinner = useDelayedLoadingIndicator(\n !workbookBuffer && !loadError && !uploadedWorkbook,\n XLSX_LOADING_INDICATOR_DELAY_MS\n )\n\n React.useEffect(() => {\n let isCurrent = true\n if (url) {\n setUploadedWorkbook(null)\n }\n\n async function loadWorkbook(): Promise<void> {\n if (!url) {\n setWorkbookBuffer(null)\n setLoadError(undefined)\n return\n }\n\n setWorkbookBuffer(null)\n setLoadError(undefined)\n\n try {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch XLSX (${response.status})`)\n }\n\n const nextWorkbookBuffer = await response.arrayBuffer()\n if (!isCurrent) return\n\n setWorkbookBuffer(nextWorkbookBuffer)\n } catch (error) {\n if (!isCurrent) return\n\n setLoadError(\n error instanceof Error ? error.message : "Unknown XLSX load error"\n )\n }\n }\n\n void loadWorkbook()\n\n return () => {\n isCurrent = false\n }\n }, [url])\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 const buffer = await file.arrayBuffer()\n setLoadError(undefined)\n setUploadedWorkbook({\n buffer,\n fileName: file.name,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n const activeBuffer = uploadedWorkbook?.buffer ?? workbookBuffer\n const activeFileName = uploadedWorkbook?.fileName ?? displayFileName\n const activeIdentity = workbookIdentity\n\n if (!url && !uploadedWorkbook) {\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=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <WorkbookStandaloneToolbar\n onUploadClick={() => fileInputRef.current?.click()}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n />\n <div className="grid min-h-0 flex-1 place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-center text-sm shadow-xs">\n <p className="font-medium">Upload a workbook to preview</p>\n <p className="mt-1 text-muted-foreground">\n Pass an XLSX URL with the <code>src</code> prop or upload a file.\n </p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (loadError && !activeBuffer) {\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=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <WorkbookStandaloneToolbar\n onUploadClick={() => fileInputRef.current?.click()}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n />\n <div className="grid min-h-0 flex-1 place-items-center bg-muted/30 p-4">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm">\n <p className="font-medium">Unable to display workbook</p>\n <p className="mt-1 text-muted-foreground">{loadError}</p>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload XLSX\n </Button>\n </div>\n </div>\n </div>\n )\n }\n\n if (!activeBuffer) {\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=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <WorkbookStandaloneToolbar\n onUploadClick={() => fileInputRef.current?.click()}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n />\n <ViewerLoadingSurface showSpinner={shouldShowLoadingSpinner} />\n </div>\n )\n }\n\n return (\n <div className={cn("overflow-hidden", className)}>\n <input\n ref={fileInputRef}\n type="file"\n accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"\n className="hidden"\n onChange={handleUpload}\n />\n <XlsxWorkbookLoadedViewer\n className={className}\n fileName={activeFileName}\n isDark={effectiveIsDark}\n onDownload={() => downloadWorkbookBuffer(activeBuffer, activeFileName)}\n onIsDarkChange={setNightRenderEnabled}\n onUploadClick={() => fileInputRef.current?.click()}\n renderTableHeaderMenu={(props) => (\n <WorkbookTableHeaderMenu {...props} />\n )}\n showDownloadButton={showDownload}\n showNightRenderToggle={shouldRenderNightMode}\n showToolbar={showToolbar}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n workbookBuffer={activeBuffer}\n workbookIdentity={activeIdentity}\n />\n </div>\n )\n}\n\nfunction XlsxWorkbookLoadedViewer({\n className,\n fileName,\n isDark,\n onDownload,\n onIsDarkChange,\n onUploadClick,\n renderTableHeaderMenu,\n showDownloadButton,\n showNightRenderToggle,\n showToolbar = true,\n showUploadButton,\n toolbarActions,\n workbookBuffer,\n workbookIdentity,\n}: {\n className?: string\n fileName: string\n isDark: boolean\n onDownload: () => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n renderTableHeaderMenu: (\n props: XlsxTableHeaderMenuRenderProps\n ) => React.ReactNode\n showDownloadButton: boolean\n showNightRenderToggle: boolean\n showToolbar?: boolean\n showUploadButton: boolean\n toolbarActions?: React.ReactNode\n workbookBuffer: ArrayBuffer\n workbookIdentity: string\n}) {\n const controller = useXlsxViewerController(\n React.useMemo(\n () => ({\n allowResizeInReadOnly: true,\n file: workbookBuffer,\n fileName,\n maxFileSizeBytes: XLSX_MAX_FILE_SIZE_BYTES,\n readOnly: true,\n useWorker: true,\n }),\n [fileName, workbookBuffer]\n )\n )\n\n return (\n <XlsxViewerProvider controller={controller} isDark={isDark}>\n <XlsxWorkbookSurface\n className={className}\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onUploadClick={onUploadClick}\n renderTableHeaderMenu={renderTableHeaderMenu}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showToolbar={showToolbar}\n showUploadButton={showUploadButton}\n toolbarActions={toolbarActions}\n workbookIdentity={workbookIdentity}\n />\n </XlsxViewerProvider>\n )\n}\n'export function XlsxViewerSource() {return (diff --git a/apps/v4/content/docs/(root)/index.mdx b/apps/v4/content/docs/(root)/index.mdxindex 5e2255b..9e16042 100644--- a/apps/v4/content/docs/(root)/index.mdx+++ b/apps/v4/content/docs/(root)/index.mdx@@ -16,6 +16,6 @@ Extend is built around the work of turning raw PDFs, spreadsheets, scans, and te## Component set-The document-specific React components are maintained in Extend UI. The rest of the base primitives are from [Coss UI](https://coss.com/ui/docs), including the shared button, tooltip, select, popover, dialog, and menu patterns. Icons come from [Hugeicons](https://hugeicons.com/).+The document-specific React components are maintained in Extend UI. The rest of the base primitives are from [Coss UI](https://coss.com/ui/docs), including the shared button, tooltip, select, popover, dialog, and menu patterns. Icons follow the `iconLibrary` in your `components.json` — the CLI supports [Lucide](https://lucide.dev/), [Tabler](https://tabler.io/icons), [Hugeicons](https://hugeicons.com/), [Phosphor](https://phosphoricons.com/), and [Remix Icon](https://remixicon.com/), and this site renders Hugeicons.Start with [Components](/docs/components) for the full list, or jump into [Blocks](/blocks) for composed examples.diff --git a/apps/v4/content/docs/components/bounding-box-citations.mdx b/apps/v4/content/docs/components/bounding-box-citations.mdxindex fd0b57b..2088dd1 100644--- a/apps/v4/content/docs/components/bounding-box-citations.mdx+++ b/apps/v4/content/docs/components/bounding-box-citations.mdx@@ -50,8 +50,6 @@ import("@/components/extend/bounding-box-citations").then((mod) => mod.HumanRevinpx shadcn@latest add @extend/bounding-box-citations```-<ExtendInstallPathNote />-</TabsContent><TabsContent value="manual">@@ -61,9 +59,19 @@ npx shadcn@latest add @extend/bounding-box-citations<Step>Install the following dependencies:</Step>```bash-npm install @glideapps/[email protected] @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6 @pierre/diffs@^1.1.22+npm install @glideapps/[email protected] @pierre/diffs@^1.1.22```+<Step>Install the icon library configured in your `components.json`:</Step>++The component source references icons through the shadcn CLI's+`IconPlaceholder`, which supports every `iconLibrary` the CLI does: `lucide`,+`tabler`, `hugeicons`, `phosphor`, and `remixicon`. Installing with the CLI+replaces each placeholder with the matching icon from your configured library,+so make sure that library's package is installed. When copying the source+manually, replace each `IconPlaceholder` element with the icon named by the+prop for your library.+<Step>Copy and paste the following code into your project.</Step><HumanReviewSource />diff --git a/apps/v4/content/docs/components/csv-tsv-viewer.mdx b/apps/v4/content/docs/components/csv-tsv-viewer.mdxindex 5d1710f..6185153 100644--- a/apps/v4/content/docs/components/csv-tsv-viewer.mdx+++ b/apps/v4/content/docs/components/csv-tsv-viewer.mdx@@ -47,8 +47,6 @@ const CsvViewer = dynamic(npx shadcn@latest add @extend/csv-viewer```-<ExtendInstallPathNote />-</TabsContent><TabsContent value="manual">@@ -58,9 +56,19 @@ npx shadcn@latest add @extend/csv-viewer<Step>Install the following dependencies:</Step>```bash-npm install @glideapps/[email protected] @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6 papaparse@^5.5.3+npm install @glideapps/[email protected] papaparse@^5.5.3```+<Step>Install the icon library configured in your `components.json`:</Step>++The component source references icons through the shadcn CLI's+`IconPlaceholder`, which supports every `iconLibrary` the CLI does: `lucide`,+`tabler`, `hugeicons`, `phosphor`, and `remixicon`. Installing with the CLI+replaces each placeholder with the matching icon from your configured library,+so make sure that library's package is installed. When copying the source+manually, replace each `IconPlaceholder` element with the icon named by the+prop for your library.+<Step>Copy and paste the following code into your project.</Step><CsvViewerSource />diff --git a/apps/v4/content/docs/components/document-splits.mdx b/apps/v4/content/docs/components/document-splits.mdxindex e7f4530..cb82b49 100644--- a/apps/v4/content/docs/components/document-splits.mdx+++ b/apps/v4/content/docs/components/document-splits.mdx@@ -24,8 +24,6 @@ See it composed with the PDF Viewer in the [Document Splits block](/blocks#documnpx shadcn@latest add @extend/document-splits```-<ExtendInstallPathNote />-</TabsContent><TabsContent value="manual">@@ -35,9 +33,19 @@ npx shadcn@latest add @extend/document-splits<Step>Install the following dependencies:</Step>```bash-npm install @dnd-kit/core@^6.3.1 @dnd-kit/sortable@^10.0.0 @dnd-kit/utilities@^3.2.2 @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6+npm install @dnd-kit/core@^6.3.1 @dnd-kit/sortable@^10.0.0 @dnd-kit/utilities@^3.2.2```+<Step>Install the icon library configured in your `components.json`:</Step>++The component source references icons through the shadcn CLI's+`IconPlaceholder`, which supports every `iconLibrary` the CLI does: `lucide`,+`tabler`, `hugeicons`, `phosphor`, and `remixicon`. Installing with the CLI+replaces each placeholder with the matching icon from your configured library,+so make sure that library's package is installed. When copying the source+manually, replace each `IconPlaceholder` element with the icon named by the+prop for your library.+<Step>Copy and paste the following code into your project.</Step><DocumentSplitsSource />diff --git a/apps/v4/content/docs/components/document-viewer-sidebar.mdx b/apps/v4/content/docs/components/document-viewer-sidebar.mdxindex 440b490..7d038cf 100644--- a/apps/v4/content/docs/components/document-viewer-sidebar.mdx+++ b/apps/v4/content/docs/components/document-viewer-sidebar.mdx@@ -22,8 +22,6 @@ Document Viewer Sidebar provides the responsive shell used by document viewers tnpx shadcn@latest add @extend/document-viewer-sidebar```-<ExtendInstallPathNote />-</TabsContent><TabsContent value="manual">diff --git a/apps/v4/content/docs/components/docx-editor.mdx b/apps/v4/content/docs/components/docx-editor.mdxindex d2052fb..9d4a556 100644--- a/apps/v4/content/docs/components/docx-editor.mdx+++ b/apps/v4/content/docs/components/docx-editor.mdx@@ -23,8 +23,6 @@ The React DOCX Editor is an experimental document editing surface built on top onpx shadcn@latest add @extend/docx-editor```-<ExtendInstallPathNote />-</TabsContent><TabsContent value="manual">@@ -34,9 +32,19 @@ npx shadcn@latest add @extend/docx-editor<Step>Install the following dependencies:</Step>```bash-npm install @base-ui/react@^1.4.1 @extend-ai/react-docx@^0.8.4 @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6+npm install @base-ui/react@^1.4.1 @extend-ai/react-docx@^0.8.4```+<Step>Install the icon library configured in your `components.json`:</Step>++The component source references icons through the shadcn CLI's+`IconPlaceholder`, which supports every `iconLibrary` the CLI does: `lucide`,+`tabler`, `hugeicons`, `phosphor`, and `remixicon`. Installing with the CLI+replaces each placeholder with the matching icon from your configured library,+so make sure that library's package is installed. When copying the source+manually, replace each `IconPlaceholder` element with the icon named by the+prop for your library.+<Step>Install the File Thumbnail and Toggle components because the editor reusesthem for the page thumbnail rail and formatting controls.diff --git a/apps/v4/content/docs/components/docx-viewer.mdx b/apps/v4/content/docs/components/docx-viewer.mdxindex 5f94978..ad637cd 100644--- a/apps/v4/content/docs/components/docx-viewer.mdx+++ b/apps/v4/content/docs/components/docx-viewer.mdx@@ -23,8 +23,6 @@ The React DOCX Viewer is for contracts, proposals, reports, and internal docs whnpx shadcn@latest add @extend/docx-viewer```-<ExtendInstallPathNote />-</TabsContent><TabsContent value="manual">@@ -34,9 +32,19 @@ npx shadcn@latest add @extend/docx-viewer<Step>Install the following dependencies:</Step>```bash-npm install @extend-ai/react-docx@^0.8.4 @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6+npm install @extend-ai/react-docx@^0.8.4```+<Step>Install the icon library configured in your `components.json`:</Step>++The component source references icons through the shadcn CLI's+`IconPlaceholder`, which supports every `iconLibrary` the CLI does: `lucide`,+`tabler`, `hugeicons`, `phosphor`, and `remixicon`. Installing with the CLI+replaces each placeholder with the matching icon from your configured library,+so make sure that library's package is installed. When copying the source+manually, replace each `IconPlaceholder` element with the icon named by the+prop for your library.+<Step>Copy and paste the following code into your project.</Step><DocxViewerSource />diff --git a/apps/v4/content/docs/components/e-signature.mdx b/apps/v4/content/docs/components/e-signature.mdxindex e90ebf8..b605f00 100644--- a/apps/v4/content/docs/components/e-signature.mdx+++ b/apps/v4/content/docs/components/e-signature.mdx@@ -33,9 +33,19 @@ npx shadcn@latest add @extend/e-signature<Step>Install the following dependencies:</Step>```bash-npm install @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6 pdf-lib@^1.17.1 signature_pad@^5.1.3+npm install pdf-lib@^1.17.1 signature_pad@^5.1.3```+<Step>Install the icon library configured in your `components.json`:</Step>++The component source references icons through the shadcn CLI's+`IconPlaceholder`, which supports every `iconLibrary` the CLI does: `lucide`,+`tabler`, `hugeicons`, `phosphor`, and `remixicon`. Installing with the CLI+replaces each placeholder with the matching icon from your configured library,+so make sure that library's package is installed. When copying the source+manually, replace each `IconPlaceholder` element with the icon named by the+prop for your library.+<Step>Copy and paste the following code into your project.</Step><ESignatureSource />diff --git a/apps/v4/content/docs/components/file-system.mdx b/apps/v4/content/docs/components/file-system.mdxindex 27e5061..a2218f8 100644--- a/apps/v4/content/docs/components/file-system.mdx+++ b/apps/v4/content/docs/components/file-system.mdx@@ -22,8 +22,6 @@ File System renders a flat manifest of files and folders — the shape you get bnpx shadcn@latest add @extend/file-system```-<ExtendInstallPathNote />-</TabsContent><TabsContent value="manual">@@ -35,9 +33,19 @@ npx shadcn@latest add @extend/file-system</Step>```bash-npm install @pierre/trees @hugeicons/react @hugeicons/core-free-icons+npm install @pierre/trees```+<Step>Install the icon library configured in your `components.json`:</Step>++The component source references icons through the shadcn CLI's+`IconPlaceholder`, which supports every `iconLibrary` the CLI does: `lucide`,+`tabler`, `hugeicons`, `phosphor`, and `remixicon`. Installing with the CLI+replaces each placeholder with the matching icon from your configured library,+so make sure that library's package is installed. When copying the source+manually, replace each `IconPlaceholder` element with the icon named by the+prop for your library.+<Step>Copy `components/extend/file-system.tsx` from the registry item into yourproject.diff --git a/apps/v4/content/docs/components/file-thumbnail.mdx b/apps/v4/content/docs/components/file-thumbnail.mdxindex 0fc005a..85d84ac 100644--- a/apps/v4/content/docs/components/file-thumbnail.mdx+++ b/apps/v4/content/docs/components/file-thumbnail.mdx@@ -22,8 +22,6 @@ File Thumbnail gives document lists, upload queues, and attachment trays a consinpx shadcn@latest add @extend/file-thumbnail```-<ExtendInstallPathNote />-</TabsContent><TabsContent value="manual">diff --git a/apps/v4/content/docs/components/file-upload.mdx b/apps/v4/content/docs/components/file-upload.mdxindex 3626f37..a1f4a91 100644--- a/apps/v4/content/docs/components/file-upload.mdx+++ b/apps/v4/content/docs/components/file-upload.mdx@@ -23,8 +23,6 @@ File Upload is the starting point for document processing workflows. It should hnpx shadcn@latest add @extend/file-upload```-<ExtendInstallPathNote />-</TabsContent><TabsContent value="manual">@@ -34,9 +32,19 @@ npx shadcn@latest add @extend/file-upload<Step>Install the following dependencies:</Step>```bash-npm install @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6 border-beam@^1.0.1+npm install border-beam@^1.0.1```+<Step>Install the icon library configured in your `components.json`:</Step>++The component source references icons through the shadcn CLI's+`IconPlaceholder`, which supports every `iconLibrary` the CLI does: `lucide`,+`tabler`, `hugeicons`, `phosphor`, and `remixicon`. Installing with the CLI+replaces each placeholder with the matching icon from your configured library,+so make sure that library's package is installed. When copying the source+manually, replace each `IconPlaceholder` element with the icon named by the+prop for your library.+<Step>Install the File Thumbnail component because File Upload uses it for selectedfile rows.diff --git a/apps/v4/content/docs/components/layout-blocks.mdx b/apps/v4/content/docs/components/layout-blocks.mdxindex c486b46..61bf4d1 100644--- a/apps/v4/content/docs/components/layout-blocks.mdx+++ b/apps/v4/content/docs/components/layout-blocks.mdx@@ -24,8 +24,6 @@ See it composed with the PDF Viewer in the [Layout Blocks block](/blocks#layout-npx shadcn@latest add @extend/layout-blocks```-<ExtendInstallPathNote />-</TabsContent><TabsContent value="manual">@@ -35,9 +33,19 @@ npx shadcn@latest add @extend/layout-blocks<Step>Install the following dependencies:</Step>```bash-npm install @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6 @tanstack/react-virtual@^3.13.26 react-markdown@^10.1.0 rehype-raw@^7.0.0 rehype-sanitize@^6.0.0 remark-gfm@^4.0.1+npm install @tanstack/react-virtual@^3.13.26 react-markdown@^10.1.0 rehype-raw@^7.0.0 rehype-sanitize@^6.0.0 remark-gfm@^4.0.1```+<Step>Install the icon library configured in your `components.json`:</Step>++The component source references icons through the shadcn CLI's+`IconPlaceholder`, which supports every `iconLibrary` the CLI does: `lucide`,+`tabler`, `hugeicons`, `phosphor`, and `remixicon`. Installing with the CLI+replaces each placeholder with the matching icon from your configured library,+so make sure that library's package is installed. When copying the source+manually, replace each `IconPlaceholder` element with the icon named by the+prop for your library.+<Step>Copy and paste the following code into your project.</Step><OcrBlocksSource />diff --git a/apps/v4/content/docs/components/pdf-viewer.mdx b/apps/v4/content/docs/components/pdf-viewer.mdxindex f747f0e..6f63686 100644--- a/apps/v4/content/docs/components/pdf-viewer.mdx+++ b/apps/v4/content/docs/components/pdf-viewer.mdx@@ -27,8 +27,6 @@ PDF rendering is powered by [EmbedPDF](https://www.embedpdf.com/).npx shadcn@latest add @extend/pdf-viewer```-<ExtendInstallPathNote />-</TabsContent><TabsContent value="manual">@@ -38,9 +36,19 @@ npx shadcn@latest add @extend/pdf-viewer<Step>Install the following dependencies:</Step>```bash-npm install @embedpdf/core@^2.14.4 @embedpdf/engines@^2.14.4 @embedpdf/models@^2.14.4 @embedpdf/plugin-document-manager@^2.14.4 @embedpdf/plugin-interaction-manager@^2.14.4 @embedpdf/plugin-render@^2.14.4 @embedpdf/plugin-rotate@^2.14.4 @embedpdf/plugin-scroll@^2.14.4 @embedpdf/plugin-search@^2.14.4 @embedpdf/plugin-selection@^2.14.4 @embedpdf/plugin-thumbnail@^2.14.4 @embedpdf/plugin-tiling@^2.14.4 @embedpdf/plugin-viewport@^2.14.4 @embedpdf/plugin-zoom@^2.14.4 @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6 pdf-lib@^1.17.1+npm install @embedpdf/core@^2.14.4 @embedpdf/engines@^2.14.4 @embedpdf/models@^2.14.4 @embedpdf/plugin-document-manager@^2.14.4 @embedpdf/plugin-interaction-manager@^2.14.4 @embedpdf/plugin-render@^2.14.4 @embedpdf/plugin-rotate@^2.14.4 @embedpdf/plugin-scroll@^2.14.4 @embedpdf/plugin-search@^2.14.4 @embedpdf/plugin-selection@^2.14.4 @embedpdf/plugin-thumbnail@^2.14.4 @embedpdf/plugin-tiling@^2.14.4 @embedpdf/plugin-viewport@^2.14.4 @embedpdf/plugin-zoom@^2.14.4 pdf-lib@^1.17.1```+<Step>Install the icon library configured in your `components.json`:</Step>++The component source references icons through the shadcn CLI's+`IconPlaceholder`, which supports every `iconLibrary` the CLI does: `lucide`,+`tabler`, `hugeicons`, `phosphor`, and `remixicon`. Installing with the CLI+replaces each placeholder with the matching icon from your configured library,+so make sure that library's package is installed. When copying the source+manually, replace each `IconPlaceholder` element with the icon named by the+prop for your library.+<Step>Copy and paste the following code into your project.</Step><PdfViewerSource />diff --git a/apps/v4/content/docs/components/pptx-viewer.mdx b/apps/v4/content/docs/components/pptx-viewer.mdxindex 284a6fd..20aa081 100644--- a/apps/v4/content/docs/components/pptx-viewer.mdx+++ b/apps/v4/content/docs/components/pptx-viewer.mdx@@ -23,8 +23,6 @@ The React PowerPoint Viewer renders presentations directly in the browser as a cnpx shadcn@latest add @extend/pptx-viewer```-<ExtendInstallPathNote />-</TabsContent><TabsContent value="manual">@@ -34,9 +32,19 @@ npx shadcn@latest add @extend/pptx-viewer<Step>Install the following dependencies:</Step>```bash-npm install @extend-ai/[email protected] @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6 @tanstack/react-virtual@^3.13.12+npm install @extend-ai/[email protected] @tanstack/react-virtual@^3.13.12```+<Step>Install the icon library configured in your `components.json`:</Step>++The component source references icons through the shadcn CLI's+`IconPlaceholder`, which supports every `iconLibrary` the CLI does: `lucide`,+`tabler`, `hugeicons`, `phosphor`, and `remixicon`. Installing with the CLI+replaces each placeholder with the matching icon from your configured library,+so make sure that library's package is installed. When copying the source+manually, replace each `IconPlaceholder` element with the icon named by the+prop for your library.+<Step>Copy and paste the following code into your project.</Step><PptxViewerSource />diff --git a/apps/v4/content/docs/components/schema-builder.mdx b/apps/v4/content/docs/components/schema-builder.mdxindex ffd76a9..8be7ee7 100644--- a/apps/v4/content/docs/components/schema-builder.mdx+++ b/apps/v4/content/docs/components/schema-builder.mdx@@ -23,8 +23,6 @@ types, descriptions, enums, nested objects, and arrays.npx shadcn@latest add @extend/schema-builder```-<ExtendInstallPathNote />-</TabsContent><TabsContent value="manual">@@ -34,9 +32,19 @@ npx shadcn@latest add @extend/schema-builder<Step>Install the following dependencies:</Step>```bash-npm install @dnd-kit/core@^6.3.1 @dnd-kit/sortable@^10.0.0 @dnd-kit/utilities@^3.2.2 @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6 @pierre/diffs@^1.2.7 [email protected]+npm install @dnd-kit/core@^6.3.1 @dnd-kit/sortable@^10.0.0 @dnd-kit/utilities@^3.2.2 @pierre/diffs@^1.2.7 [email protected]```+<Step>Install the icon library configured in your `components.json`:</Step>++The component source references icons through the shadcn CLI's+`IconPlaceholder`, which supports every `iconLibrary` the CLI does: `lucide`,+`tabler`, `hugeicons`, `phosphor`, and `remixicon`. Installing with the CLI+replaces each placeholder with the matching icon from your configured library,+so make sure that library's package is installed. When copying the source+manually, replace each `IconPlaceholder` element with the icon named by the+prop for your library.+<Step>Copy and paste the following code into your project.</Step><SchemaBuilderSource />diff --git a/apps/v4/content/docs/components/xlsx-editor.mdx b/apps/v4/content/docs/components/xlsx-editor.mdxindex 0b9aa36..80d3f68 100644--- a/apps/v4/content/docs/components/xlsx-editor.mdx+++ b/apps/v4/content/docs/components/xlsx-editor.mdx@@ -23,8 +23,6 @@ The React Excel Editor is an experimental spreadsheet editing surface built on tnpx shadcn@latest add @extend/xlsx-editor```-<ExtendInstallPathNote />-</TabsContent><TabsContent value="manual">@@ -34,9 +32,19 @@ npx shadcn@latest add @extend/xlsx-editor<Step>Install the following dependencies:</Step>```bash-npm install @base-ui/react@^1.4.1 @extend-ai/[email protected] @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6 class-variance-authority@^0.7.1+npm install @base-ui/react@^1.4.1 @extend-ai/[email protected] class-variance-authority@^0.7.1```+<Step>Install the icon library configured in your `components.json`:</Step>++The component source references icons through the shadcn CLI's+`IconPlaceholder`, which supports every `iconLibrary` the CLI does: `lucide`,+`tabler`, `hugeicons`, `phosphor`, and `remixicon`. Installing with the CLI+replaces each placeholder with the matching icon from your configured library,+so make sure that library's package is installed. When copying the source+manually, replace each `IconPlaceholder` element with the icon named by the+prop for your library.+<Step>Install the Excel Viewer component because the editor reuses its sheet tabsand table header menu, plus the Group primitive used by the formula bar anddiff --git a/apps/v4/content/docs/components/xlsx-viewer.mdx b/apps/v4/content/docs/components/xlsx-viewer.mdxindex 3c082c0..01ceee5 100644--- a/apps/v4/content/docs/components/xlsx-viewer.mdx+++ b/apps/v4/content/docs/components/xlsx-viewer.mdx@@ -23,8 +23,6 @@ The React Excel Viewer is the core spreadsheet preview for XLSX workbooks, finannpx shadcn@latest add @extend/xlsx-viewer```-<ExtendInstallPathNote />-</TabsContent><TabsContent value="manual">@@ -34,9 +32,19 @@ npx shadcn@latest add @extend/xlsx-viewer<Step>Install the following dependencies:</Step>```bash-npm install @extend-ai/[email protected] @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6+npm install @extend-ai/[email protected]```+<Step>Install the icon library configured in your `components.json`:</Step>++The component source references icons through the shadcn CLI's+`IconPlaceholder`, which supports every `iconLibrary` the CLI does: `lucide`,+`tabler`, `hugeicons`, `phosphor`, and `remixicon`. Installing with the CLI+replaces each placeholder with the matching icon from your configured library,+so make sure that library's package is installed. When copying the source+manually, replace each `IconPlaceholder` element with the icon named by the+prop for your library.+<Step>Copy and paste the following code into your project.</Step><XlsxViewerSource />diff --git a/apps/v4/mdx-components.tsx b/apps/v4/mdx-components.tsxindex 2ae54e6..e523e0a 100644--- a/apps/v4/mdx-components.tsx+++ b/apps/v4/mdx-components.tsx@@ -77,15 +77,6 @@ function ComponentsListWrapper() {)}-function ExtendInstallPathNote() {- return (- <Callout variant="info" title="Default install location" className="mt-4">- The CLI installs Extend components in <code>components/extend</code> by- default, beneath the components alias in <code>components.json</code>.- </Callout>- )-}-function withMdxHrefBasePath(href: string | undefined) {return href ? withUiBasePath(href) : href}@@ -391,7 +382,6 @@ export const mdxComponents = {CodeCollapsibleWrapper,DocsMdxCodeBlock,ComponentsList: ComponentsListWrapper,- ExtendInstallPathNote,CsvViewerDemo,CsvViewerSource,DocumentViewerSidebarDemo,diff --git a/apps/v4/registry.json b/apps/v4/registry.jsonindex 2a18324..4b9d621 100644--- a/apps/v4/registry.json+++ b/apps/v4/registry.json@@ -35,11 +35,7 @@"type": "registry:ui","title": "Accordion","description": "A vertically stacked set of expandable content panels.",- "dependencies": [- "@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6"- ],+ "dependencies": ["@base-ui/react@^1.4.1"],"registryDependencies": ["utils"],"files": [{@@ -82,11 +78,7 @@"type": "registry:ui","title": "Autocomplete","description": "An autocomplete input built on Base UI primitives.",- "dependencies": [- "@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6"- ],+ "dependencies": ["@base-ui/react@^1.4.1"],"registryDependencies": ["input", "scroll-area", "utils"],"files": [{@@ -119,11 +111,7 @@"type": "registry:ui","title": "Breadcrumb","description": "Navigation breadcrumbs for page hierarchy.",- "dependencies": [- "@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6"- ],+ "dependencies": ["@base-ui/react@^1.4.1"],"registryDependencies": ["utils"],"files": [{@@ -186,10 +174,6 @@"type": "registry:ui","title": "Color Picker","description": "A compact popover color picker with hex, RGB, CSS, and HSL input formats.",- "dependencies": [- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6"- ],"registryDependencies": ["button","input",@@ -211,11 +195,7 @@"type": "registry:ui","title": "Command","description": "A command menu surface powered by cmdk.",- "dependencies": [- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6",- "cmdk@^1.1.1"- ],+ "dependencies": ["cmdk@^1.1.1"],"registryDependencies": ["dialog", "utils"],"files": [{@@ -230,11 +210,7 @@"type": "registry:ui","title": "Dialog","description": "An accessible modal dialog built on Base UI.",- "dependencies": [- "@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6"- ],+ "dependencies": ["@base-ui/react@^1.4.1"],"registryDependencies": ["button", "scroll-area", "utils"],"files": [{@@ -249,11 +225,7 @@"type": "registry:ui","title": "Dropdown Menu","description": "A dropdown menu built on Base UI menu primitives.",- "dependencies": [- "@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6"- ],+ "dependencies": ["@base-ui/react@^1.4.1"],"registryDependencies": ["utils"],"files": [{@@ -347,8 +319,6 @@"description": "A select control built on Base UI.","dependencies": ["@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6","class-variance-authority@^0.7.1"],"registryDependencies": ["utils"],@@ -380,11 +350,7 @@"type": "registry:ui","title": "Sheet","description": "A side sheet built on Base UI dialog primitives.",- "dependencies": [- "@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6"- ],+ "dependencies": ["@base-ui/react@^1.4.1"],"registryDependencies": ["button", "scroll-area", "utils"],"files": [{@@ -401,8 +367,6 @@"description": "A responsive application sidebar with menu, rail, and provider primitives.","dependencies": ["@base-ui/react@^1.4.1",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6","class-variance-authority@^0.7.1"],"registryDependencies": [@@ -441,12 +405,7 @@"type": "registry:ui","title": "Sonner","description": "A themed toast provider for Sonner.",- "dependencies": [- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6",- "[email protected]",- "sonner@^2.0.0"- ],+ "dependencies": ["[email protected]", "sonner@^2.0.0"],"files": [{"path": "registry/new-york-v4/ui/sonner.tsx",@@ -460,10 +419,6 @@"type": "registry:ui","title": "Spinner","description": "A compact loading spinner using Hugeicons.",- "dependencies": [- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6"- ],"registryDependencies": ["utils"],"files": [{@@ -523,11 +478,7 @@"type": "registry:ui","title": "Resizable","description": "Resizable panel primitives using react-resizable-panels.",- "dependencies": [- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6",- "react-resizable-panels@^4.11.2"- ],+ "dependencies": ["react-resizable-panels@^4.11.2"],"registryDependencies": ["utils"],"files": [{@@ -557,11 +508,7 @@"type": "registry:ui","title": "File Upload","description": "A drag-and-drop file upload surface with accepted file type icons and a compact file list.",- "dependencies": [- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6",- "border-beam@^1.0.1"- ],+ "dependencies": ["border-beam@^1.0.1"],"registryDependencies": ["card", "@extend/file-thumbnail", "utils"],"categories": ["documents"],"files": [@@ -591,11 +538,7 @@"type": "registry:ui","title": "File System (Finder)","description": "A macOS Finder-style file browser for flat object-store manifests with icon, list, column, and gallery views.",- "dependencies": [- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6",- "@pierre/[email protected]"- ],+ "dependencies": ["@pierre/[email protected]"],"registryDependencies": ["button","command",@@ -658,8 +601,6 @@"@embedpdf/plugin-tiling@^2.14.4","@embedpdf/plugin-viewport@^2.14.4","@embedpdf/plugin-zoom@^2.14.4",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6","pdf-lib@^1.17.1"],"registryDependencies": [@@ -697,8 +638,6 @@"description": "A DOCX viewer with upload, zoom, theme controls, and read-only rendering.","dependencies": ["@extend-ai/react-docx@^0.8.4",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6","@tanstack/react-virtual@^3.13.12"],"registryDependencies": [@@ -735,12 +674,7 @@"type": "registry:ui","title": "DOCX Editor","description": "An experimental DOCX editor with a Word-style toolbar, page thumbnails, import, export, and live document mutation.",- "dependencies": [- "@base-ui/react@^1.4.1",- "@extend-ai/react-docx@^0.8.4",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6"- ],+ "dependencies": ["@base-ui/react@^1.4.1", "@extend-ai/react-docx@^0.8.4"],"registryDependencies": ["badge","button",@@ -776,11 +710,7 @@"type": "registry:ui","title": "Excel Viewer","description": "An XLSX viewer with workbook loading, thumbnails, sheet tabs, upload, zoom, and theme controls.",- "dependencies": [- "@extend-ai/[email protected]",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6"- ],+ "dependencies": ["@extend-ai/[email protected]"],"registryDependencies": ["button","dropdown-menu",@@ -808,8 +738,6 @@"description": "A PowerPoint viewer with slide navigation, zoom, upload, download, custom scroll areas, and virtualized thumbnails.","dependencies": ["@extend-ai/[email protected]",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6","@tanstack/react-virtual@^3.13.12"],"registryDependencies": [@@ -839,14 +767,10 @@"type": "registry:ui","title": "Excel Editor","description": "An experimental XLSX editor with formula input, undo and redo, sheet controls, export, and live workbook mutation.",- "dependencies": [- "@extend-ai/[email protected]",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6"- ],+ "dependencies": ["@extend-ai/[email protected]"],"registryDependencies": ["button",- "color-picker",+ "@extend/color-picker","@extend/group","input","scroll-area",@@ -874,8 +798,6 @@"description": "A CSV and TSV viewer with parsing, upload, search, zoom, theme-aware grid rendering, and Glide Data Grid.","dependencies": ["@glideapps/[email protected]",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6","papaparse@^5.5.3"],"devDependencies": ["@types/papaparse@^5.5.2"],@@ -902,7 +824,6 @@"type": "registry:block","title": "PDF Dropzone","description": "A PDF-only upload dropzone that opens the dropped file in the shared PDF viewer.",- "dependencies": ["@hugeicons/core-free-icons@^4.2.0"],"registryDependencies": ["@extend/file-upload", "@extend/pdf-viewer"],"categories": ["documents", "blocks"],"files": [@@ -919,8 +840,6 @@"title": "Layout Blocks","description": "A structured layout review panel with typed blocks and confidence cards.","dependencies": [- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6","@tanstack/react-virtual@^3.13.26","react-markdown@^10.1.0","rehype-raw@^7.0.0",@@ -961,12 +880,7 @@"type": "registry:block","title": "E-Signature","description": "A PDF signature review block with field overlays and signing actions.",- "dependencies": [- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6",- "pdf-lib@^1.17.1",- "signature_pad@^5.1.3"- ],+ "dependencies": ["pdf-lib@^1.17.1", "signature_pad@^5.1.3"],"registryDependencies": ["button","dialog",@@ -991,8 +905,6 @@"description": "An extraction citation panel connected to source bounding boxes and editable values.","dependencies": ["@glideapps/[email protected]",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6","@pierre/diffs@^1.1.22"],"registryDependencies": [@@ -1021,8 +933,6 @@"@dnd-kit/core@^6.3.1","@dnd-kit/sortable@^10.0.0","@dnd-kit/utilities@^3.2.2",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6","@pierre/diffs@^1.2.7",],@@ -1070,9 +980,7 @@"dependencies": ["@dnd-kit/core@^6.3.1","@dnd-kit/sortable@^10.0.0",- "@dnd-kit/utilities@^3.2.2",- "@hugeicons/core-free-icons@^4.2.0",- "@hugeicons/react@^1.1.6"+ "@dnd-kit/utilities@^3.2.2"],"registryDependencies": ["button",diff --git a/apps/v4/registry/new-york-v4/blocks/e-signature.tsx b/apps/v4/registry/new-york-v4/blocks/e-signature.tsxindex 10120c3..42de421 100644--- a/apps/v4/registry/new-york-v4/blocks/e-signature.tsx+++ b/apps/v4/registry/new-york-v4/blocks/e-signature.tsx@@ -1,12 +1,6 @@"use client"import * as React from "react"-import {- Download01Icon,- FilePenIcon,- Pen01Icon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import type SignaturePad from "signature_pad"import { cn } from "@/lib/utils"@@ -23,6 +17,7 @@ import {import { ScrollArea } from "@/components/ui/scroll-area"import { PdfBlockResizableShell } from "@/components/extend/pdf-block-resizable-shell"import { PDFViewer } from "@/components/extend/pdf-viewer"+import { IconPlaceholder } from "@/components/icon-placeholder"type BoundingBox = {x: number@@ -395,7 +390,14 @@ function SignatureFieldOverlay({/>) : (<span className="flex size-full items-center justify-center gap-1.5 px-2 text-[11px] font-medium text-blue-700 dark:text-blue-300">- <HugeiconsIcon icon={Pen01Icon} className="size-3.5" />+ <IconPlaceholder+ lucide="Pen"+ tabler="IconPencil"+ hugeicons="Pen01Icon"+ phosphor="PenIcon"+ remixicon="RiPencilLine"+ className="size-3.5"+ />Signature</span>)}@@ -475,7 +477,14 @@ function SignatureFieldsPanel({<div className="rounded-lg border bg-background p-3"><div className="flex items-start gap-3"><div className="grid size-9 shrink-0 place-items-center rounded-md bg-blue-500/10 text-blue-600 dark:text-blue-300">- <HugeiconsIcon icon={FilePenIcon} className="size-4" />+ <IconPlaceholder+ lucide="FilePen"+ tabler="IconFilePencil"+ hugeicons="FilePenIcon"+ phosphor="NotePencilIcon"+ remixicon="RiFileEditLine"+ className="size-4"+ /></div><div className="min-w-0 flex-1"><div className="flex items-center justify-between gap-2">@@ -503,7 +512,14 @@ function SignatureFieldsPanel({className="flex-1"onClick={onSign}>- <HugeiconsIcon icon={Pen01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Pen"+ tabler="IconPencil"+ hugeicons="Pen01Icon"+ phosphor="PenIcon"+ remixicon="RiPencilLine"+ className="size-4"+ />{field.imageDataUrl ? "Edit" : "Sign"}</Button>{field.imageDataUrl ? (@@ -526,7 +542,14 @@ function SignatureFieldsPanel({disabled={!canExport || isDownloading}onClick={onDownload}>- <HugeiconsIcon icon={Download01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Download"+ tabler="IconDownload"+ hugeicons="Download01Icon"+ phosphor="DownloadSimpleIcon"+ remixicon="RiDownload2Line"+ className="size-4"+ />{isDownloading ? "Exporting..." : "Export signed PDF"}</Button></div>@@ -567,7 +590,14 @@ export function ESignatureBlock({ file }: { file?: string }) {disabled={!file || !field.imageDataUrl || isDownloading}onClick={handleDownload}>- <HugeiconsIcon icon={Download01Icon} className="size-4" />+ <IconPlaceholder+ lucide="Download"+ tabler="IconDownload"+ hugeicons="Download01Icon"+ phosphor="DownloadSimpleIcon"+ remixicon="RiDownload2Line"+ className="size-4"+ />Download</Button>}diff --git a/apps/v4/registry/new-york-v4/blocks/pdf-dropzone.tsx b/apps/v4/registry/new-york-v4/blocks/pdf-dropzone.tsxindex cd106ab..c3af90e 100644--- a/apps/v4/registry/new-york-v4/blocks/pdf-dropzone.tsx+++ b/apps/v4/registry/new-york-v4/blocks/pdf-dropzone.tsx@@ -1,10 +1,23 @@"use client"import * as React from "react"-import { FileUploadIcon } from "@hugeicons/core-free-icons"import { FileUpload } from "@/components/extend/file-upload"import { PDFViewer } from "@/components/extend/pdf-viewer"+import { IconPlaceholder } from "@/components/icon-placeholder"++function FileUploadGlyph(props: React.ComponentProps<"svg">) {+ return (+ <IconPlaceholder+ lucide="FileUp"+ tabler="IconFileUpload"+ hugeicons="FileUploadIcon"+ phosphor="FileArrowUpIcon"+ remixicon="RiFileUploadLine"+ {...props}+ />+ )+}const PDF_ACCEPT = "application/pdf,.pdf"const PDF_UPLOAD_DROPZONE_SELECTOR = "[data-pdf-upload-dropzone]"@@ -64,7 +77,7 @@ export function PdfDropzoneBlock() {<div data-pdf-upload-dropzone className="w-full max-w-xl"><FileUploadaccept={PDF_ACCEPT}- acceptedFileTypes={[{ label: "PDF", icon: FileUploadIcon }]}+ acceptedFileTypes={[{ label: "PDF", icon: FileUploadGlyph }]}browseLabel="Browse PDF"className="w-full"description="PDF files only"diff --git a/apps/v4/registry/new-york-v4/ui/accordion.tsx b/apps/v4/registry/new-york-v4/ui/accordion.tsxindex 7d061ca..ae09100 100644--- a/apps/v4/registry/new-york-v4/ui/accordion.tsx+++ b/apps/v4/registry/new-york-v4/ui/accordion.tsx@@ -2,10 +2,9 @@import type React from "react"import { Accordion as AccordionPrimitive } from "@base-ui/react/accordion"-import { ArrowDown01Icon } from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { cn } from "@/lib/utils"+import { IconPlaceholder } from "@/components/icon-placeholder"export function Accordion(props: AccordionPrimitive.Root.Props@@ -42,10 +41,14 @@ export function AccordionTrigger({{...props}>{children}- <HugeiconsIcon+ <IconPlaceholder+ lucide="ChevronDown"+ tabler="IconChevronDown"+ hugeicons="ArrowDown01Icon"+ phosphor="CaretDownIcon"+ remixicon="RiArrowDownSLine"className="pointer-events-none size-4 shrink-0 translate-y-0.5 opacity-80 transition-transform duration-200 ease-in-out"data-slot="accordion-indicator"- icon={ArrowDown01Icon}/></AccordionPrimitive.Trigger></AccordionPrimitive.Header>diff --git a/apps/v4/registry/new-york-v4/ui/autocomplete.tsx b/apps/v4/registry/new-york-v4/ui/autocomplete.tsxindex c47a3f4..8bd3ab7 100644--- a/apps/v4/registry/new-york-v4/ui/autocomplete.tsx+++ b/apps/v4/registry/new-york-v4/ui/autocomplete.tsx@@ -2,12 +2,11 @@import type React from "react"import { Autocomplete as AutocompletePrimitive } from "@base-ui/react/autocomplete"-import { ArrowUpDownIcon, Cancel01Icon } from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { cn } from "@/lib/utils"import { Input } from "@/components/ui/input"import { ScrollArea } from "@/components/ui/scroll-area"+import { IconPlaceholder } from "@/components/icon-placeholder"export const Autocomplete: typeof AutocompletePrimitive.Root =AutocompletePrimitive.Root@@ -68,7 +67,13 @@ export function AutocompleteInput({{...triggerProps}><AutocompletePrimitive.Icon data-slot="autocomplete-icon">- <HugeiconsIcon icon={ArrowUpDownIcon} />+ <IconPlaceholder+ lucide="ArrowUpDown"+ tabler="IconArrowsUpDown"+ hugeicons="ArrowUpDownIcon"+ phosphor="ArrowsDownUpIcon"+ remixicon="RiArrowUpDownLine"+ /></AutocompletePrimitive.Icon></AutocompleteTrigger>)}@@ -80,7 +85,13 @@ export function AutocompleteInput({)}{...clearProps}>- <HugeiconsIcon icon={Cancel01Icon} />+ <IconPlaceholder+ lucide="X"+ tabler="IconX"+ hugeicons="Cancel01Icon"+ phosphor="XIcon"+ remixicon="RiCloseLine"+ /></AutocompleteClear>)}</AutocompletePrimitive.InputGroup>@@ -264,7 +275,13 @@ export function AutocompleteClear({data-slot="autocomplete-clear"{...props}>- <HugeiconsIcon icon={Cancel01Icon} />+ <IconPlaceholder+ lucide="X"+ tabler="IconX"+ hugeicons="Cancel01Icon"+ phosphor="XIcon"+ remixicon="RiCloseLine"+ /></AutocompletePrimitive.Clear>)}diff --git a/apps/v4/registry/new-york-v4/ui/breadcrumb.tsx b/apps/v4/registry/new-york-v4/ui/breadcrumb.tsxindex 396080a..08ccd03 100644--- a/apps/v4/registry/new-york-v4/ui/breadcrumb.tsx+++ b/apps/v4/registry/new-york-v4/ui/breadcrumb.tsx@@ -3,13 +3,9 @@import * as React from "react"import { mergeProps } from "@base-ui/react/merge-props"import { useRender } from "@base-ui/react/use-render"-import {- ArrowRight01Icon,- MoreHorizontalIcon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { cn } from "@/lib/utils"+import { IconPlaceholder } from "@/components/icon-placeholder"export function Breadcrumb({...props@@ -100,7 +96,15 @@ export function BreadcrumbSeparator({role="presentation"{...props}>- {children ?? <HugeiconsIcon icon={ArrowRight01Icon} />}+ {children ?? (+ <IconPlaceholder+ lucide="ArrowRight"+ tabler="IconArrowRight"+ hugeicons="ArrowRight01Icon"+ phosphor="ArrowRightIcon"+ remixicon="RiArrowRightLine"+ />+ )}</li>)}@@ -117,7 +121,14 @@ export function BreadcrumbEllipsis({role="presentation"{...props}>- <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />+ <IconPlaceholder+ lucide="Ellipsis"+ tabler="IconDots"+ hugeicons="MoreHorizontalIcon"+ phosphor="DotsThreeIcon"+ remixicon="RiMoreLine"+ className="size-4"+ /><span className="sr-only">More</span></span>)diff --git a/apps/v4/registry/new-york-v4/ui/command.tsx b/apps/v4/registry/new-york-v4/ui/command.tsxindex defad06..ad6c5ef 100644--- a/apps/v4/registry/new-york-v4/ui/command.tsx+++ b/apps/v4/registry/new-york-v4/ui/command.tsx@@ -1,8 +1,6 @@"use client"import * as React from "react"-import { Search01Icon } from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { Command as CommandPrimitive } from "cmdk"import { cn } from "@/lib/utils"@@ -13,6 +11,7 @@ import {DialogHeader,DialogTitle,} from "@/components/ui/dialog"+import { IconPlaceholder } from "@/components/icon-placeholder"function Command({className,@@ -71,8 +70,12 @@ function CommandInput({data-slot="command-input-wrapper"className="flex h-9 items-center gap-2 border-b px-3">- <HugeiconsIcon- icon={Search01Icon}+ <IconPlaceholder+ lucide="Search"+ tabler="IconSearch"+ hugeicons="Search01Icon"+ phosphor="MagnifyingGlassIcon"+ remixicon="RiSearchLine"className="size-4 shrink-0 opacity-50"/><CommandPrimitive.Inputdiff --git a/apps/v4/registry/new-york-v4/ui/dialog.tsx b/apps/v4/registry/new-york-v4/ui/dialog.tsxindex dc9861d..e7e01bd 100644--- a/apps/v4/registry/new-york-v4/ui/dialog.tsx+++ b/apps/v4/registry/new-york-v4/ui/dialog.tsx@@ -5,12 +5,11 @@ import { isValidElement } from "react"import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"import { mergeProps } from "@base-ui/react/merge-props"import { useRender } from "@base-ui/react/use-render"-import { Cancel01Icon } from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"import { ScrollArea } from "@/components/ui/scroll-area"+import { IconPlaceholder } from "@/components/icon-placeholder"export const DialogCreateHandle: typeof DialogPrimitive.createHandle =DialogPrimitive.createHandle@@ -123,7 +122,13 @@ export function DialogPopup({render={<Button size="icon" variant="ghost" />}{...closeProps}>- <HugeiconsIcon icon={Cancel01Icon} />+ <IconPlaceholder+ lucide="X"+ tabler="IconX"+ hugeicons="Cancel01Icon"+ phosphor="XIcon"+ remixicon="RiCloseLine"+ /></DialogPrimitive.Close>)}</DialogPrimitive.Popup>diff --git a/apps/v4/registry/new-york-v4/ui/dropdown-menu.tsx b/apps/v4/registry/new-york-v4/ui/dropdown-menu.tsxindex 3d227e3..f640a5c 100644--- a/apps/v4/registry/new-york-v4/ui/dropdown-menu.tsx+++ b/apps/v4/registry/new-york-v4/ui/dropdown-menu.tsx@@ -2,10 +2,9 @@import * as React from "react"import { Menu as DropdownMenuPrimitive } from "@base-ui/react/menu"-import { ArrowRight01Icon, Tick02Icon } from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { cn } from "@/lib/utils"+import { IconPlaceholder } from "@/components/icon-placeholder"function childContent(asChild: boolean | undefined,@@ -169,7 +168,13 @@ function DropdownMenuCheckboxItem({{variant === "switch" ? null : (<span className="pointer-events-none absolute start-2 flex size-4 items-center justify-center"><DropdownMenuPrimitive.CheckboxItemIndicator>- <HugeiconsIcon icon={Tick02Icon} />+ <IconPlaceholder+ lucide="Check"+ tabler="IconCheck"+ hugeicons="Tick02Icon"+ phosphor="CheckIcon"+ remixicon="RiCheckLine"+ /></DropdownMenuPrimitive.CheckboxItemIndicator></span>)}@@ -304,7 +309,14 @@ function DropdownMenuSubTrigger({{...props}>{children}- <HugeiconsIcon icon={ArrowRight01Icon} className="ms-auto size-4" />+ <IconPlaceholder+ lucide="ArrowRight"+ tabler="IconArrowRight"+ hugeicons="ArrowRight01Icon"+ phosphor="ArrowRightIcon"+ remixicon="RiArrowRightLine"+ className="ms-auto size-4"+ /></DropdownMenuPrimitive.SubmenuTrigger>)}diff --git a/apps/v4/registry/new-york-v4/ui/select.tsx b/apps/v4/registry/new-york-v4/ui/select.tsxindex 20dad22..e9c8531 100644--- a/apps/v4/registry/new-york-v4/ui/select.tsx+++ b/apps/v4/registry/new-york-v4/ui/select.tsx@@ -4,11 +4,10 @@ import type * as React from "react"import { mergeProps } from "@base-ui/react/merge-props"import { Select as SelectPrimitive } from "@base-ui/react/select"import { useRender } from "@base-ui/react/use-render"-import { ChevronDown, ChevronUp } from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { cva, type VariantProps } from "class-variance-authority"import { cn } from "@/lib/utils"+import { IconPlaceholder } from "@/components/icon-placeholder"export const Select: typeof SelectPrimitive.Root = SelectPrimitive.Root@@ -50,9 +49,13 @@ export function SelectButton({<span className="flex-1 truncate in-data-placeholder:text-muted-foreground/72">{children}</span>- <HugeiconsIcon+ <IconPlaceholder+ lucide="ChevronDown"+ tabler="IconChevronDown"+ hugeicons="ChevronDown"+ phosphor="CaretDownIcon"+ remixicon="RiArrowDownSLine"className={selectTriggerIconClassName}- icon={ChevronDown}/></>),@@ -83,9 +86,13 @@ export function SelectTrigger({>{children}<SelectPrimitive.Icon data-slot="select-icon">- <HugeiconsIcon+ <IconPlaceholder+ lucide="ChevronDown"+ tabler="IconChevronDown"+ hugeicons="ChevronDown"+ phosphor="CaretDownIcon"+ remixicon="RiArrowDownSLine"className={selectTriggerIconClassName}- icon={ChevronDown}/></SelectPrimitive.Icon></SelectPrimitive.Trigger>@@ -149,9 +156,13 @@ export function SelectPopup({className="top-0 z-50 flex h-6 w-full cursor-default items-center justify-center before:pointer-events-none before:absolute before:inset-x-px before:top-px before:h-[200%] before:rounded-t-[calc(var(--radius-lg)-1px)] before:bg-linear-to-b before:from-popover before:from-50%"data-slot="select-scroll-up-arrow">- <HugeiconsIcon+ <IconPlaceholder+ lucide="ChevronUp"+ tabler="IconChevronUp"+ hugeicons="ChevronUp"+ phosphor="CaretUpIcon"+ remixicon="RiArrowUpSLine"className="relative size-4.5 sm:size-4"- icon={ChevronUp}/></SelectPrimitive.ScrollUpArrow><div className="relative h-full min-w-(--anchor-width) rounded-lg border bg-popover shadow-lg/5 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%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]">@@ -169,9 +180,13 @@ export function SelectPopup({className="bottom-0 z-50 flex h-6 w-full cursor-default items-center justify-center before:pointer-events-none before:absolute before:inset-x-px before:bottom-px before:h-[200%] before:rounded-b-[calc(var(--radius-lg)-1px)] before:bg-linear-to-t before:from-popover before:from-50%"data-slot="select-scroll-down-arrow">- <HugeiconsIcon+ <IconPlaceholder+ lucide="ChevronDown"+ tabler="IconChevronDown"+ hugeicons="ChevronDown"+ phosphor="CaretDownIcon"+ remixicon="RiArrowDownSLine"className="relative size-4.5 sm:size-4"- icon={ChevronDown}/></SelectPrimitive.ScrollDownArrow></SelectPrimitive.Popup>diff --git a/apps/v4/registry/new-york-v4/ui/sheet.tsx b/apps/v4/registry/new-york-v4/ui/sheet.tsxindex a7af871..c9fd052 100644--- a/apps/v4/registry/new-york-v4/ui/sheet.tsx+++ b/apps/v4/registry/new-york-v4/ui/sheet.tsx@@ -5,12 +5,11 @@ import { isValidElement } from "react"import { Dialog as SheetPrimitive } from "@base-ui/react/dialog"import { mergeProps } from "@base-ui/react/merge-props"import { useRender } from "@base-ui/react/use-render"-import { Cancel01Icon } from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"import { ScrollArea } from "@/components/ui/scroll-area"+import { IconPlaceholder } from "@/components/icon-placeholder"export const Sheet: typeof SheetPrimitive.Root = SheetPrimitive.Root@@ -134,7 +133,13 @@ export function SheetPopup({render={<Button size="icon" variant="ghost" />}{...closeProps}>- <HugeiconsIcon icon={Cancel01Icon} />+ <IconPlaceholder+ lucide="X"+ tabler="IconX"+ hugeicons="Cancel01Icon"+ phosphor="XIcon"+ remixicon="RiCloseLine"+ /></SheetPrimitive.Close>)}</SheetPrimitive.Popup>diff --git a/apps/v4/registry/new-york-v4/ui/sidebar.tsx b/apps/v4/registry/new-york-v4/ui/sidebar.tsxindex fdff725..819f74f 100644--- a/apps/v4/registry/new-york-v4/ui/sidebar.tsx+++ b/apps/v4/registry/new-york-v4/ui/sidebar.tsx@@ -3,8 +3,6 @@import * as React from "react"import { mergeProps } from "@base-ui/react/merge-props"import { useRender } from "@base-ui/react/use-render"-import { SidebarLeftIcon } from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { cva, type VariantProps } from "class-variance-authority"import { cn } from "@/lib/utils"@@ -21,11 +19,8 @@ import {SheetTitle,} from "@/components/ui/sheet"import { Skeleton } from "@/components/ui/skeleton"-import {- Tooltip,- TooltipPopup,- TooltipTrigger,-} from "@/components/ui/tooltip"+import { Tooltip, TooltipPopup, TooltipTrigger } from "@/components/ui/tooltip"+import { IconPlaceholder } from "@/components/icon-placeholder"const SIDEBAR_COOKIE_NAME: string = "sidebar_state"const SIDEBAR_COOKIE_MAX_AGE: number = 60 * 60 * 24 * 7@@ -301,7 +296,13 @@ export function SidebarTrigger({variant="ghost"{...props}>- <HugeiconsIcon icon={SidebarLeftIcon} />+ <IconPlaceholder+ lucide="PanelLeft"+ tabler="IconLayoutSidebar"+ hugeicons="SidebarLeftIcon"+ phosphor="SidebarIcon"+ remixicon="RiLayoutLeftLine"+ /><span className="sr-only">Toggle Sidebar</span></Button>)diff --git a/apps/v4/registry/new-york-v4/ui/sonner.tsx b/apps/v4/registry/new-york-v4/ui/sonner.tsxindex 5f0feaf..c5bfaed 100644--- a/apps/v4/registry/new-york-v4/ui/sonner.tsx+++ b/apps/v4/registry/new-york-v4/ui/sonner.tsx@@ -1,16 +1,10 @@"use client"-import {- Alert01Icon,- CancelCircleIcon,- CheckmarkCircle01Icon,- InformationCircleIcon,- Loading03Icon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { useTheme } from "next-themes"import { Toaster as Sonner, type ToasterProps } from "sonner"+import { IconPlaceholder } from "@/components/icon-placeholder"+const Toaster = ({ ...props }: ToasterProps) => {const { theme = "system" } = useTheme()@@ -20,13 +14,54 @@ const Toaster = ({ ...props }: ToasterProps) => {className="toaster group"icons={{success: (- <HugeiconsIcon icon={CheckmarkCircle01Icon} className="size-4" />+ <IconPlaceholder+ lucide="CircleCheckIcon"+ tabler="IconCircleCheckFilled"+ hugeicons="CheckmarkCircle01Icon"+ phosphor="CheckCircleIcon"+ remixicon="RiCheckboxCircleFill"+ className="size-4"+ />+ ),+ info: (+ <IconPlaceholder+ lucide="Info"+ tabler="IconInfoCircle"+ hugeicons="InformationCircleIcon"+ phosphor="InfoIcon"+ remixicon="RiInformationLine"+ className="size-4"+ />+ ),+ warning: (+ <IconPlaceholder+ lucide="TriangleAlert"+ tabler="IconAlertTriangle"+ hugeicons="Alert01Icon"+ phosphor="WarningIcon"+ remixicon="RiAlertLine"+ className="size-4"+ />+ ),+ error: (+ <IconPlaceholder+ lucide="CircleX"+ tabler="IconCircleX"+ hugeicons="CancelCircleIcon"+ phosphor="XCircleIcon"+ remixicon="RiCloseCircleLine"+ className="size-4"+ />),- info: <HugeiconsIcon icon={InformationCircleIcon} className="size-4" />,- warning: <HugeiconsIcon icon={Alert01Icon} className="size-4" />,- error: <HugeiconsIcon icon={CancelCircleIcon} className="size-4" />,loading: (- <HugeiconsIcon icon={Loading03Icon} className="size-4 animate-spin" />+ <IconPlaceholder+ lucide="Loader2"+ tabler="IconLoader"+ hugeicons="Loading03Icon"+ phosphor="SpinnerIcon"+ remixicon="RiLoaderLine"+ className="size-4 animate-spin"+ />),}}style={diff --git a/apps/v4/registry/new-york-v4/ui/spinner.tsx b/apps/v4/registry/new-york-v4/ui/spinner.tsxindex b1edbb9..ef78d90 100644--- a/apps/v4/registry/new-york-v4/ui/spinner.tsx+++ b/apps/v4/registry/new-york-v4/ui/spinner.tsx@@ -1,21 +1,21 @@import type React from "react"-import { Loading03Icon } from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"import { cn } from "@/lib/utils"+import { IconPlaceholder } from "@/components/icon-placeholder"export function Spinner({className,...props-}: Omit<- React.ComponentProps<typeof HugeiconsIcon>,- "icon"->): React.ReactElement {+}: React.ComponentProps<"svg">): React.ReactElement {return (- <HugeiconsIcon+ <IconPlaceholder+ lucide="Loader2"+ tabler="IconLoader"+ hugeicons="Loading03Icon"+ phosphor="SpinnerIcon"+ remixicon="RiLoaderLine"aria-label="Loading"className={cn("animate-spin", className)}- icon={Loading03Icon}role="status"{...props}/>