TypeScript
Refactor UI registry and viewer rendering
Andrew Luo848aa83d7d4d
diff --git a/apps/v4/components/bounding-box-citations-docs.tsx b/apps/v4/components/bounding-box-citations-docs.tsxindex e017dcb..ebe4358 100644--- a/apps/v4/components/bounding-box-citations-docs.tsx+++ b/apps/v4/components/bounding-box-citations-docs.tsx@@ -2320,7 +2320,7 @@ function HumanReviewFieldCardBase({</div><spanclassName={cn(- "size-2 shrink-0 rounded-full bg-amber-400 transition-opacity",+ "size-2 shrink-0 rounded-full bg-amber-400",!modified && "opacity-0")}/>@@ -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 transition-opacity",\n !modified && "opacity-0"\n )}\n />\n </div>\n <div className="truncate text-xs text-muted-foreground">\n {field.key}\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-1">\n {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 {\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'export function HumanReviewSource() {return (diff --git a/apps/v4/components/document-splitter-docs.tsx b/apps/v4/components/document-splitter-docs.tsxindex 82394cc..0995968 100644--- a/apps/v4/components/document-splitter-docs.tsx+++ b/apps/v4/components/document-splitter-docs.tsx@@ -34,7 +34,6 @@ import {DragDropVerticalIcon,} from "@hugeicons/core-free-icons"import { HugeiconsIcon } from "@hugeicons/react"-import type * as ReactPdf from "react-pdf"import { cn } from "@/lib/utils"import { withUiBasePath } from "@/lib/zone-path"@@ -58,8 +57,11 @@ import {DocsViewCodeBlock,} from "@/components/docs-code-block"import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"+import {+ getPdfPageCount,+ renderPdfThumbnailUrl,+} from "@/components/pdf-thumbnail-utils"-type ReactPdfModule = typeof ReactPdfexport type DocumentSplitPageId = `page-${number}`export type DocumentSplitItemId = stringtype PageId = DocumentSplitItemId@@ -79,10 +81,6 @@ const XLSX_THUMBNAIL_FILE = {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",url: XLSX_URL,}-const PDF_WORKER_URL = new URL(- "pdfjs-dist/legacy/build/pdf.worker.min.mjs",- import.meta.url-).toString()const THUMBNAIL_WIDTH = 72const THUMBNAIL_HEIGHT = 92const DEFAULT_THUMBNAIL_SIZE = {@@ -1106,130 +1104,48 @@ export function DocumentSplits({)}-function usePdfThumbnailImages(documentKey: string) {+function usePdfThumbnailImages(documentKey: string, splits: SplitGroup[]) {const [thumbnailImages, setThumbnailImages] = React.useState<Record<PageId, string>>({})- const thumbnailObjectUrlsRef = React.useRef(new Set<string>())- const clearCachedThumbnails = React.useCallback(() => {- thumbnailObjectUrlsRef.current.forEach((imageUrl) => {- URL.revokeObjectURL(imageUrl)- })- thumbnailObjectUrlsRef.current.clear()- setThumbnailImages({})- }, [])+ const pageIds = React.useMemo(+ () => Array.from(new Set(splits.flatMap((split) => split.pages))),+ [splits]+ )React.useEffect(() => {- clearCachedThumbnails()- }, [clearCachedThumbnails, documentKey])+ setThumbnailImages({})+ }, [documentKey])React.useEffect(() => {- const objectUrls = thumbnailObjectUrlsRef.current-- return () => {- objectUrls.forEach((imageUrl) => {- URL.revokeObjectURL(imageUrl)- })- objectUrls.clear()- }- }, [])-- const handleThumbnailReady = React.useCallback(- (pageId: PageId, imageUrl: string) => {- setThumbnailImages((currentImages) => {- if (currentImages[pageId]) {- URL.revokeObjectURL(imageUrl)- return currentImages- }-- thumbnailObjectUrlsRef.current.add(imageUrl)- return { ...currentImages, [pageId]: imageUrl }- })- },- []- )-- return { thumbnailImages, onThumbnailReady: handleThumbnailReady }-}--function PdfThumbnailCacheItem({- pageId,- reactPdf,- onThumbnailReady,-}: {- pageId: PageId- reactPdf: ReactPdfModule- onThumbnailReady: (pageId: PageId, imageUrl: string) => void-}) {- const rootRef = React.useRef<HTMLDivElement>(null)- const pageNumber = getPageNumber(pageId)+ let isCurrent = true++ void (async () => {+ for (const pageId of pageIds) {+ const imageUrl = await renderPdfThumbnailUrl({+ pageIndex: getPageNumber(pageId) - 1,+ url: documentKey,+ width: THUMBNAIL_WIDTH,+ })- return (- <div ref={rootRef} className="size-[1px] overflow-hidden">- <reactPdf.Thumbnail- pageNumber={pageNumber}- width={THUMBNAIL_WIDTH}- className="block [&_.react-pdf__Thumbnail__page]:!m-0"- onRenderSuccess={() => {- window.requestAnimationFrame(() => {- const canvas = rootRef.current?.querySelector("canvas")-- if (!canvas) return-- try {- canvas.toBlob((blob) => {- if (!blob) return-- onThumbnailReady(pageId, URL.createObjectURL(blob))- }, "image/png")- } catch {- // Canvas export can fail if the browser marks it tainted.- }- })- }}- loading={null}- />- </div>- )-}+ if (!isCurrent) return+ if (!imageUrl) continue-function PdfThumbnailCache({- splits,- thumbnailImages,- reactPdf,- onThumbnailReady,-}: {- splits: SplitGroup[]- thumbnailImages: Record<PageId, string>- reactPdf: ReactPdfModule- onThumbnailReady: (pageId: PageId, imageUrl: string) => void-}) {- const uncachedPageIds = React.useMemo(- () =>- Array.from(new Set(splits.flatMap((split) => split.pages))).filter(- (pageId) => !thumbnailImages[pageId]- ),- [splits, thumbnailImages]- )+ setThumbnailImages((currentImages) =>+ currentImages[pageId]+ ? currentImages+ : { ...currentImages, [pageId]: imageUrl }+ )+ }+ })().catch(() => undefined)- if (uncachedPageIds.length === 0) return null+ return () => {+ isCurrent = false+ }+ }, [documentKey, pageIds])- return (- <div- aria-hidden="true"- className="pointer-events-none fixed top-0 left-[-10000px] z-[-1] opacity-0"- >- {uncachedPageIds.map((pageId) => (- <PdfThumbnailCacheItem- key={pageId}- pageId={pageId}- reactPdf={reactPdf}- onThumbnailReady={onThumbnailReady}- />- ))}- </div>- )+ return thumbnailImages}function WorkbookViewerPane({@@ -1360,31 +1276,28 @@ export function DocumentSplitsBlock({defaultViewerZoom?: numberheightClassName?: string} = {}) {- const [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null)const [pdfUrl, setPdfUrl] = React.useState(PDF_URL)const [numPages, setNumPages] = React.useState(0)const [splits, setSplits] = React.useState<SplitGroup[]>(() =>createInitialGroups(DEFAULT_PREVIEW_PAGE_COUNT))- const { thumbnailImages, onThumbnailReady } = usePdfThumbnailImages(pdfUrl)+ const thumbnailImages = usePdfThumbnailImages(pdfUrl, splits)const viewerRef = React.useRef<PDFViewerHandle>(null)const uploadedPdfUrlRef = React.useRef<string | null>(null)React.useEffect(() => {- let isMounted = true+ let isCurrent = true- import("react-pdf").then((module) => {- module.pdfjs.GlobalWorkerOptions.workerSrc = PDF_WORKER_URL-- if (isMounted) {- setReactPdf(module)- }- })+ void getPdfPageCount(pdfUrl)+ .then((pageCount) => {+ if (isCurrent) setNumPages(pageCount)+ })+ .catch(() => undefined)return () => {- isMounted = false+ isCurrent = false}- }, [])+ }, [pdfUrl])React.useEffect(() => {return () => {@@ -1398,13 +1311,6 @@ export function DocumentSplitsBlock({setSplits(createInitialGroups(numPages || DEFAULT_PREVIEW_PAGE_COUNT))}, [numPages, pdfUrl])- const handleLoadSuccess = React.useCallback(- ({ numPages: pageCount }: { numPages: number }) => {- setNumPages(pageCount)- },- []- )-const handlePdfUpload = React.useCallback((file: File) => {const nextUrl = URL.createObjectURL(file)@@ -1430,7 +1336,7 @@ export function DocumentSplitsBlock({})}, [])- const renderShell = () => (+ return (<PdfBlockResizableShellautoSaveId="pdf-block-document-splits"heightClassName={heightClassName}@@ -1457,28 +1363,6 @@ export function DocumentSplitsBlock({}/>)-- return (- <>- {renderShell()}- {reactPdf ? (- <reactPdf.Document- file={pdfUrl}- className="pointer-events-none fixed top-0 left-[-10000px] z-[-1] size-px overflow-hidden opacity-0"- onLoadSuccess={handleLoadSuccess}- loading={null}- error={null}- >- <PdfThumbnailCache- splits={splits}- thumbnailImages={thumbnailImages}- reactPdf={reactPdf}- onThumbnailReady={onThumbnailReady}- />- </reactPdf.Document>- ) : null}- </>- )}function DocumentSplitExampleCard({@@ -1552,34 +1436,31 @@ function DocumentSplitsExample() {}function DocumentSplitsPreview({ file }: { file: string }) {- const [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null)const [pageCount, setPageCount] = React.useState(0)const [splits, setSplits] = React.useState<SplitGroup[]>(() =>createInitialGroups(DEFAULT_PREVIEW_PAGE_COUNT))- const { thumbnailImages, onThumbnailReady } = usePdfThumbnailImages(file)+ const thumbnailImages = usePdfThumbnailImages(file, splits)React.useEffect(() => {- let isMounted = true+ let isCurrent = true- import("react-pdf").then((module) => {- module.pdfjs.GlobalWorkerOptions.workerSrc = PDF_WORKER_URL-- if (isMounted) {- setReactPdf(module)- }- })+ void getPdfPageCount(file)+ .then((nextPageCount) => {+ if (isCurrent) setPageCount(nextPageCount)+ })+ .catch(() => undefined)return () => {- isMounted = false+ isCurrent = false}- }, [])+ }, [file])React.useEffect(() => {setSplits(createInitialGroups(pageCount || DEFAULT_PREVIEW_PAGE_COUNT))}, [file, pageCount])- const panel = (+ return (<DocumentSplitsclassName="h-[620px]"splits={splits}@@ -1589,29 +1470,6 @@ function DocumentSplitsPreview({ file }: { file: string }) {onSelectPage={() => {}}/>)-- if (!reactPdf) return panel-- return (- <reactPdf.Document- file={file}- onLoadSuccess={({ numPages }) => setPageCount(numPages)}- loading={panel}- error={- <div className="grid h-[620px] place-items-center bg-background text-sm text-muted-foreground">- Unable to load PDF.- </div>- }- >- <PdfThumbnailCache- splits={splits}- thumbnailImages={thumbnailImages}- reactPdf={reactPdf}- onThumbnailReady={onThumbnailReady}- />- {panel}- </reactPdf.Document>- )}export function DocumentSplitsDemo() {@@ -1635,14 +1493,12 @@ import {type DocumentSplit,type DocumentSplitPageId,} from "@/components/ui/document-splits";--type ReactPdfModule = typeof import("react-pdf");+import {+ getPdfPageCount,+ renderPdfThumbnailUrl,+} from "@/components/pdf-thumbnail-utils";const PDF_FILE = "/samples/attention.pdf";-const PDF_WORKER_URL = new URL(- "pdfjs-dist/legacy/build/pdf.worker.min.mjs",- import.meta.url,-).toString();const THUMBNAIL_WIDTH = 72;const DEFAULT_PAGE_COUNT = 15;@@ -1664,126 +1520,61 @@ function createInitialSplits(pageCount: number): DocumentSplit[] {].filter((split) => split.pages.length > 0);}-function usePdfThumbnailImages(documentKey: string) {+function usePdfThumbnailImages(documentKey: string, splits: DocumentSplit[]) {const [thumbnailImages, setThumbnailImages] = React.useState<Record<DocumentSplitPageId, string>>({});- const objectUrlsRef = React.useRef(new Set<string>());+ const pageIds = React.useMemo(+ () => Array.from(new Set(splits.flatMap((split) => split.pages))),+ [splits],+ );React.useEffect(() => {- objectUrlsRef.current.forEach((imageUrl) => URL.revokeObjectURL(imageUrl));- objectUrlsRef.current.clear();setThumbnailImages({});}, [documentKey]);React.useEffect(() => {- const objectUrls = objectUrlsRef.current;+ let isCurrent = true;++ void (async () => {+ for (const pageId of pageIds) {+ const imageUrl = await renderPdfThumbnailUrl({+ pageIndex: getPageNumber(pageId) - 1,+ url: documentKey,+ width: THUMBNAIL_WIDTH,+ });++ if (!isCurrent) return;+ if (!imageUrl) continue;++ setThumbnailImages((currentImages) =>+ currentImages[pageId]+ ? currentImages+ : { ...currentImages, [pageId]: imageUrl },+ );+ }+ })().catch(() => undefined);return () => {- objectUrls.forEach((imageUrl) => URL.revokeObjectURL(imageUrl));- objectUrls.clear();+ isCurrent = false;};- }, []);-- const onThumbnailReady = React.useCallback((pageId: DocumentSplitPageId, imageUrl: string) => {- setThumbnailImages((currentImages) => {- if (currentImages[pageId]) {- URL.revokeObjectURL(imageUrl);- return currentImages;- }-- objectUrlsRef.current.add(imageUrl);- return { ...currentImages, [pageId]: imageUrl };- });- }, []);-- return { thumbnailImages, onThumbnailReady };-}+ }, [documentKey, pageIds]);-function PdfThumbnailCacheItem({- pageId,- reactPdf,- onThumbnailReady,-}: {- pageId: DocumentSplitPageId;- reactPdf: ReactPdfModule;- onThumbnailReady: (pageId: DocumentSplitPageId, imageUrl: string) => void;-}) {- const rootRef = React.useRef<HTMLDivElement>(null);-- return (- <div ref={rootRef} className="size-[1px] overflow-hidden">- <reactPdf.Thumbnail- pageNumber={getPageNumber(pageId)}- width={THUMBNAIL_WIDTH}- loading={null}- onRenderSuccess={() => {- window.requestAnimationFrame(() => {- const canvas = rootRef.current?.querySelector("canvas");-- if (!canvas) return;-- canvas.toBlob((blob) => {- if (!blob) return;- onThumbnailReady(pageId, URL.createObjectURL(blob));- }, "image/png");- });- }}- />- </div>- );-}--function PdfThumbnailCache({- splits,- thumbnailImages,- reactPdf,- onThumbnailReady,-}: {- splits: DocumentSplit[];- thumbnailImages: Record<DocumentSplitPageId, string>;- reactPdf: ReactPdfModule;- onThumbnailReady: (pageId: DocumentSplitPageId, imageUrl: string) => void;-}) {- const uncachedPageIds = React.useMemo(- () =>- Array.from(new Set(splits.flatMap((split) => split.pages))).filter(- (pageId) => !thumbnailImages[pageId],- ),- [splits, thumbnailImages],- );-- if (uncachedPageIds.length === 0) return null;-- return (- <div aria-hidden="true" className="pointer-events-none fixed top-0 left-[-10000px] z-[-1] opacity-0">- {uncachedPageIds.map((pageId) => (- <PdfThumbnailCacheItem- key={pageId}- pageId={pageId}- reactPdf={reactPdf}- onThumbnailReady={onThumbnailReady}- />- ))}- </div>- );+ return thumbnailImages;}export function DocumentSplitsExample() {- const [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null);const [pageCount, setPageCount] = React.useState(0);const [splits, setSplits] = React.useState<DocumentSplit[]>(() => createInitialSplits(DEFAULT_PAGE_COUNT));- const { thumbnailImages, onThumbnailReady } = usePdfThumbnailImages(PDF_FILE);+ const thumbnailImages = usePdfThumbnailImages(PDF_FILE, splits);React.useEffect(() => {- let isMounted = true;+ let isCurrent = true;- import("react-pdf").then((module) => {- module.pdfjs.GlobalWorkerOptions.workerSrc = PDF_WORKER_URL;-- if (isMounted) setReactPdf(module);+ getPdfPageCount(PDF_FILE).then((nextPageCount) => {+ if (isCurrent) setPageCount(nextPageCount);});return () => {- isMounted = false;+ isCurrent = false;};}, []);@@ -1791,7 +1582,7 @@ export function DocumentSplitsExample() {setSplits(createInitialSplits(pageCount || DEFAULT_PAGE_COUNT));}, [pageCount]);- const panel = (+ return (<DocumentSplitsclassName="h-[620px]"splits={splits}@@ -1801,20 +1592,6 @@ export function DocumentSplitsExample() {onSelectPage={() => {}}/>);-- if (!reactPdf) return panel;-- return (- <reactPdf.Document file={PDF_FILE} onLoadSuccess={({ numPages }) => setPageCount(numPages)} loading={panel}>- <PdfThumbnailCache- splits={splits}- thumbnailImages={thumbnailImages}- reactPdf={reactPdf}- onThumbnailReady={onThumbnailReady}- />- {panel}- </reactPdf.Document>- );}`const documentSplitterSourceCode =diff --git a/apps/v4/components/document-viewer-sidebar-docs.tsx b/apps/v4/components/document-viewer-sidebar-docs.tsxindex fd3264b..e1e7631 100644--- a/apps/v4/components/document-viewer-sidebar-docs.tsx+++ b/apps/v4/components/document-viewer-sidebar-docs.tsx@@ -134,7 +134,7 @@ function DocumentViewerSidebarPreview() {variant="ghost"size="sm"className={cn(- "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",+ "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none transition-none hover:bg-sidebar-accent",page.id === activePageId? "bg-sidebar-accent text-foreground": "text-muted-foreground"diff --git a/apps/v4/components/docx-viewer-docs.tsx b/apps/v4/components/docx-viewer-docs.tsxindex 86425eb..20f25b4 100644--- a/apps/v4/components/docx-viewer-docs.tsx+++ b/apps/v4/components/docx-viewer-docs.tsx@@ -59,7 +59,7 @@ export function DocxViewerExample() {}`const docxViewerSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n useDocxEditor,\n useDocxViewerThumbnails,\n type DocxDocumentTheme,\n type DocxEditorController,\n} from "@extend-ai/react-docx"\nimport {\n Download01Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n SidebarLeftIcon,\n Sun03Icon,\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 {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Input } from "@/components/ui/input"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { 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 ZOOM_OPTIONS = [10, 25, 50, 75, 100, 125, 150, 175, 200, 400] as const\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\n\ntype UploadedDocxFile = {\n file: File\n identity: string\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 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 useControllableDarkMode({\n defaultIsDark = false,\n isDark,\n onIsDarkChange,\n}: {\n defaultIsDark?: boolean\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n}) {\n const [uncontrolledIsDark, setUncontrolledIsDark] =\n React.useState(defaultIsDark)\n const resolvedIsDark = isDark ?? uncontrolledIsDark\n\n const setIsDark = React.useCallback(\n (nextIsDark: boolean) => {\n if (isDark === undefined) {\n setUncontrolledIsDark(nextIsDark)\n }\n\n onIsDarkChange?.(nextIsDark)\n },\n [isDark, onIsDarkChange]\n )\n\n return [resolvedIsDark, setIsDark] as const\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction ViewerLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction DocxPageNumberControl({\n activePage,\n controlsDisabled,\n onPageChange,\n pageCount,\n}: {\n activePage: number\n controlsDisabled: boolean\n onPageChange: (pageNumber: number) => void\n pageCount: number\n}) {\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 if (parsedPage < 1 || parsedPage > pageCount) return\n\n onPageChange(parsedPage)\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="xs"\n className="mx-0.5 h-auto min-w-7 rounded-sm px-1.5 py-0 text-sm leading-normal font-normal text-primary sm:text-sm"\n aria-label={`Current page ${displayPage}. Edit page number`}\n disabled={controlsDisabled || !pageCount}\n onClick={() => setIsEditing(true)}\n >\n {displayPage}\n </Button>\n )}\n <span>of {pageCount || "-"}</span>\n </div>\n )\n}\n\nfunction DocxToolbar({\n activePage,\n controlsDisabled,\n isDark,\n isPreparingDownload,\n onDownload,\n onIsDarkChange,\n onPageChange,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showDownloadButton = true,\n showNightRenderToggle,\n showUploadButton = true,\n toolbarActions,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n isDark: boolean\n isPreparingDownload: boolean\n onDownload: () => void\n onIsDarkChange: (checked: boolean) => void\n onPageChange: (pageNumber: number) => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showDownloadButton?: boolean\n showNightRenderToggle: 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 activePage={activePage}\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 {showNightRenderToggle ? (\n <ToolbarTooltip\n label={isDark ? "Use light document" : "Use dark document"}\n >\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled}\n aria-label={isDark ? "Use light document" : "Use dark document"}\n onClick={() => onIsDarkChange(!isDark)}\n >\n <HugeiconsIcon\n icon={isDark ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n ) : null}\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\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 {showDownloadButton ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <ToolbarTooltip label="Download DOCX">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Download DOCX"\n disabled={controlsDisabled || isPreparingDownload}\n onClick={onDownload}\n >\n {isPreparingDownload ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n )}\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n {showUploadButton ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <ToolbarTooltip label="Upload DOCX">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Upload DOCX"\n onClick={onUploadClick}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\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\nexport function DocxViewerPreview({\n className,\n defaultThumbnailSidebarOpen = false,\n defaultIsDark = false,\n fileName,\n isDark: controlledIsDark,\n onIsDarkChange,\n rounded = false,\n showDownload = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n}: {\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n defaultIsDark?: boolean\n fileName?: string\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n rounded?: boolean\n showDownload?: boolean\n showToolbar?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n}) {\n const [effectiveIsDark, setIsDark] = useControllableDarkMode({\n defaultIsDark,\n isDark: controlledIsDark,\n onIsDarkChange,\n })\n\n return (\n <DocxViewerContent\n className={className}\n defaultThumbnailSidebarOpen={defaultThumbnailSidebarOpen}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setIsDark}\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 defaultThumbnailSidebarOpen,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled,\n shouldRenderNightMode,\n showDownload,\n showToolbar = true,\n showUpload,\n toolbarActions,\n url,\n}: {\n className?: string\n defaultThumbnailSidebarOpen: boolean\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n 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 [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(\n defaultThumbnailSidebarOpen\n )\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { importDocxFile, setDocumentTheme, status } = editor\n const [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 // Thumbnails paint from mounted page DOM, so they can only render\n // while the sidebar is showing them; skip the work when it is closed.\n disabled: !sidebarOpen,\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n [sidebarOpen]\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const [zoomScale, setZoomScale] = React.useState(100)\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 hasDocument = Boolean(url || uploadedDocxFile)\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 handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n const handleDownload = React.useCallback(async () => {\n if (isPreparingDownload) return\n if (!uploadedDocxFile && !url) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadDocxFile({\n file: uploadedDocxFile?.file,\n fileName: displayFileName,\n url,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [displayFileName, isPreparingDownload, uploadedDocxFile, url])\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(100)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n // 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 (!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 importQueueRef.current = importQueueRef.current.then(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((pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport || !page) return\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n }, [])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomScale(100)\n setActivePage(1)\n setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n {showToolbar ? (\n <DocxToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n isDark={effectiveIsDark}\n isPreparingDownload={isPreparingDownload}\n onDownload={handleDownload}\n onIsDarkChange={setNightRenderEnabled}\n onPageChange={scrollToPage}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showDownloadButton={showDownload}\n showNightRenderToggle={shouldRenderNightMode}\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={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <ScrollArea className="h-full" scrollFade>\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 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={cn("min-h-0 flex-1", rounded && "rounded-b-lg")}\n style={{ backgroundColor: viewerBackgroundColor }}\n viewportClassName="p-4"\n viewportRef={viewportRef}\n >\n {!url && !uploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">Upload a DOCX to preview</div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to display DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="mx-auto flex min-h-full justify-center">\n <div\n className={cn(\n "origin-top",\n effectiveIsDark && "docx-night-reader-shell"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode="read-only"\n loadingState={loadingState}\n pageBackgroundColor={effectiveIsDark ? "#0a0a0a" : undefined}\n pageGapBackgroundColor={viewerBackgroundColor}\n // Sidebar thumbnails can only paint from mounted page DOM,\n // so every page must mount while the sidebar is open;\n // otherwise let the viewer virtualize off-screen pages.\n pageVirtualization={{ enabled: !sidebarOpen }}\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 useDocxEditor,\n useDocxViewerThumbnails,\n type DocxDocumentTheme,\n type DocxEditorController,\n} from \"@extend-ai/react-docx\"\nimport {\n Download01Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n SidebarLeftIcon,\n Sun03Icon,\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 {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from \"@/components/ui/document-viewer-sidebar\"\nimport { FileThumbnail } from \"@/components/ui/file-thumbnail\"\nimport { Input } from \"@/components/ui/input\"\nimport { ScrollArea } from \"@/components/ui/scroll-area\"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from \"@/components/ui/select\"\nimport { 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 ZOOM_OPTIONS = [10, 25, 50, 75, 100, 125, 150, 175, 200, 400] as const\nconst DOCX_PADDING_WARNING_TEXT = \"a style property during rerender\"\n\ntype UploadedDocxFile = {\n file: File\n identity: string\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 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 useControllableDarkMode({\n defaultIsDark = false,\n isDark,\n onIsDarkChange,\n}: {\n defaultIsDark?: boolean\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n}) {\n const [uncontrolledIsDark, setUncontrolledIsDark] =\n React.useState(defaultIsDark)\n const resolvedIsDark = isDark ?? uncontrolledIsDark\n\n const setIsDark = React.useCallback(\n (nextIsDark: boolean) => {\n if (isDark === undefined) {\n setUncontrolledIsDark(nextIsDark)\n }\n\n onIsDarkChange?.(nextIsDark)\n },\n [isDark, onIsDarkChange]\n )\n\n return [resolvedIsDark, setIsDark] as const\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === \"string\" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes(\"padding\"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className=\"inline-flex\">{children}</span>\n </TooltipTrigger>\n <TooltipContent side=\"bottom\">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction ViewerLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className=\"grid h-full min-h-52 place-items-center bg-transparent\">\n {showSpinner ? <Spinner className=\"size-4\" /> : null}\n </div>\n )\n}\n\nfunction DocxPageNumberControl({\n activePage,\n controlsDisabled,\n onPageChange,\n pageCount,\n}: {\n activePage: number\n controlsDisabled: boolean\n onPageChange: (pageNumber: number) => void\n pageCount: number\n}) {\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 if (parsedPage < 1 || parsedPage > pageCount) return\n\n onPageChange(parsedPage)\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={() => setIsEditing(true)}\n >\n {displayPage}\n </Button>\n )}\n <span>of {pageCount || \"-\"}</span>\n </div>\n )\n}\n\nfunction DocxToolbar({\n activePage,\n controlsDisabled,\n isDark,\n isPreparingDownload,\n onDownload,\n onIsDarkChange,\n onPageChange,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showDownloadButton = true,\n showNightRenderToggle,\n showUploadButton = true,\n toolbarActions,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n isDark: boolean\n isPreparingDownload: boolean\n onDownload: () => void\n onIsDarkChange: (checked: boolean) => void\n onPageChange: (pageNumber: number) => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showDownloadButton?: boolean\n showNightRenderToggle: 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 activePage={activePage}\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 {showNightRenderToggle ? (\n <ToolbarTooltip\n label={isDark ? \"Use light document\" : \"Use dark document\"}\n >\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n disabled={controlsDisabled}\n aria-label={isDark ? \"Use light document\" : \"Use dark document\"}\n onClick={() => onIsDarkChange(!isDark)}\n >\n <HugeiconsIcon\n icon={isDark ? Sun03Icon : Moon02Icon}\n className=\"size-4\"\n />\n </Button>\n </ToolbarTooltip>\n ) : null}\n <Separator orientation=\"vertical\" className=\"mx-1 h-4 self-center\" />\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 {showDownloadButton ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n <ToolbarTooltip label=\"Download DOCX\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Download DOCX\"\n disabled={controlsDisabled || isPreparingDownload}\n onClick={onDownload}\n >\n {isPreparingDownload ? (\n <Spinner className=\"size-4\" />\n ) : (\n <HugeiconsIcon icon={Download01Icon} className=\"size-4\" />\n )}\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n {showUploadButton ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n <ToolbarTooltip label=\"Upload DOCX\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Upload DOCX\"\n onClick={onUploadClick}\n >\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n {toolbarActions ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n {toolbarActions}\n </>\n ) : null}\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\nexport function DocxViewerPreview({\n className,\n defaultThumbnailSidebarOpen = false,\n defaultIsDark = false,\n fileName,\n isDark: controlledIsDark,\n onIsDarkChange,\n rounded = false,\n showDownload = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n}: {\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n defaultIsDark?: boolean\n fileName?: string\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n rounded?: boolean\n showDownload?: boolean\n showToolbar?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n}) {\n const [effectiveIsDark, setIsDark] = useControllableDarkMode({\n defaultIsDark,\n isDark: controlledIsDark,\n onIsDarkChange,\n })\n\n return (\n <DocxViewerContent\n className={className}\n defaultThumbnailSidebarOpen={defaultThumbnailSidebarOpen}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setIsDark}\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 defaultThumbnailSidebarOpen,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled,\n shouldRenderNightMode,\n showDownload,\n showToolbar = true,\n showUpload,\n toolbarActions,\n url,\n}: {\n className?: string\n defaultThumbnailSidebarOpen: boolean\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n 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 [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(\n defaultThumbnailSidebarOpen\n )\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewerBackgroundColor =\n \"color-mix(in oklab, var(--muted) 40%, transparent)\"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? \"document.docx\")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? \"dark\" : \"light\"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { importDocxFile, setDocumentTheme, status } = editor\n const [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 // Thumbnails paint from mounted page DOM, so they can only render\n // while the sidebar is showing them; skip the work when it is closed.\n disabled: !sidebarOpen,\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n [sidebarOpen]\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const [zoomScale, setZoomScale] = React.useState(100)\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 hasDocument = Boolean(url || uploadedDocxFile)\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 handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n const setViewportRef = React.useCallback(\n (element: HTMLDivElement | null) => {\n viewportRef.current = element\n setViewportElement(element)\n },\n []\n )\n const pageVirtualization = React.useMemo(\n () => ({\n // Sidebar thumbnails can only paint from mounted page DOM,\n // so every page must mount while the sidebar is open;\n // otherwise let the viewer virtualize off-screen pages.\n enabled: !sidebarOpen,\n scrollElement: viewportElement,\n zoomScale: zoomScale / 100,\n }),\n [sidebarOpen, viewportElement, zoomScale]\n )\n const handleDownload = React.useCallback(async () => {\n if (isPreparingDownload) return\n if (!uploadedDocxFile && !url) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadDocxFile({\n file: uploadedDocxFile?.file,\n fileName: displayFileName,\n url,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [displayFileName, isPreparingDownload, uploadedDocxFile, url])\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(100)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? \"dark\" : \"light\")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith(\"Failed to load file\") ||\n status === \"Only .docx files are supported\"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n // 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 (!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 importQueueRef.current = importQueueRef.current.then(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((pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper=\"true\"][data-index=\"${targetPageIndex}\"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport || !page) return\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: \"auto\",\n })\n }, [])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = \"\"\n\n if (!file) return\n\n setZoomScale(100)\n setActivePage(1)\n setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n return (\n <div\n className={cn(\n \"flex h-[640px] min-h-0 flex-col overflow-hidden bg-background\",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document\"\n className=\"hidden\"\n onChange={handleUpload}\n />\n {showToolbar ? (\n <DocxToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n isDark={effectiveIsDark}\n isPreparingDownload={isPreparingDownload}\n onDownload={handleDownload}\n onIsDarkChange={setNightRenderEnabled}\n onPageChange={scrollToPage}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showDownloadButton={showDownload}\n showNightRenderToggle={shouldRenderNightMode}\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={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <ScrollArea className=\"h-full\" scrollFade>\n <div className=\"p-4\">\n {isLoadingDocument ? (\n <>\n <div className=\"mx-auto h-28 w-20 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 transition-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={cn(\"min-h-0 flex-1\", rounded && \"rounded-b-lg\")}\n style={{ backgroundColor: viewerBackgroundColor }}\n viewportClassName=\"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 preview</div>\n <div className=\"mt-1 text-muted-foreground\">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n className=\"mt-4\"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className=\"grid h-full min-h-96 place-items-center p-6 text-center\">\n <div className=\"max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs\">\n <div className=\"font-medium\">Unable to display DOCX</div>\n <div className=\"mt-1 text-muted-foreground\">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className=\"mx-auto flex min-h-full justify-center\">\n <div\n className={cn(\n \"origin-top\",\n effectiveIsDark && \"docx-night-reader-shell\"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode=\"read-only\"\n loadingState={loadingState}\n pageBackgroundColor={effectiveIsDark ? \"#0a0a0a\" : undefined}\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={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/file-system-docs.tsx b/apps/v4/components/file-system-docs.tsxindex c5f9a12..1e48912 100644--- a/apps/v4/components/file-system-docs.tsx+++ b/apps/v4/components/file-system-docs.tsx@@ -2,8 +2,6 @@import * as React from "react"import dynamic from "next/dynamic"-import type { PDFDocumentProxy } from "pdfjs-dist"-import type * as ReactPdf from "react-pdf"import { cn } from "@/lib/utils"import { withUiBasePath } from "@/lib/zone-path"@@ -14,6 +12,10 @@ import {} from "@/components/ui/file-system"import { DocsViewCodeBlock } from "@/components/docs-code-block"import { FileSystemSourceCode } from "@/components/file-system-source-code"+import {+ getPdfPageCount,+ renderPdfThumbnailUrl,+} from "@/components/pdf-thumbnail-utils"import { FileSystemBlock } from "@/registry/new-york-v4/blocks/file-system-block"const DOCX_MIME_TYPE =@@ -206,10 +208,6 @@ function generateAuroraItems(): FileSystemItem[] {const AURORA_ITEMS = generateAuroraItems()-function getPdfWorkerUrl(pdfjsVersion: string) {- return `//unpkg.com/pdfjs-dist@${pdfjsVersion}/legacy/build/pdf.worker.min.mjs`-}-// Pages rendered eagerly per PDF; the rest load on demand through the// component's `loadPreviewImageUrl` as the pager reaches them.const EAGER_PAGE_THUMBNAILS = 2@@ -233,55 +231,12 @@ const XlsxThumbnailUrlGenerator = dynamic({ ssr: false })-type PdfjsModule = (typeof ReactPdf)["pdfjs"]--let pdfjsModulePromise: Promise<PdfjsModule> | null = null--function loadPdfjs() {- pdfjsModulePromise ??= import("react-pdf").then((reactPdf) => {- reactPdf.pdfjs.GlobalWorkerOptions.workerSrc = getPdfWorkerUrl(- reactPdf.pdfjs.version- )- return reactPdf.pdfjs- })- return pdfjsModulePromise-}--const pdfDocumentCache = new Map<string, Promise<PDFDocumentProxy>>()--function loadPdfDocument(url: string) {- let documentPromise = pdfDocumentCache.get(url)-- if (!documentPromise) {- documentPromise = loadPdfjs().then(- (pdfjs) => pdfjs.getDocument(url).promise- )- pdfDocumentCache.set(url, documentPromise)- }- return documentPromise-}-async function renderPdfPageThumbnail(url: string, pageIndex: number) {- const pdf = await loadPdfDocument(url)-- if (pageIndex >= pdf.numPages) return null-- const page = await pdf.getPage(pageIndex + 1)- const baseViewport = page.getViewport({ scale: 1 })- const viewport = page.getViewport({- scale: THUMBNAIL_WIDTH / baseViewport.width,+ return renderPdfThumbnailUrl({+ pageIndex,+ url,+ width: THUMBNAIL_WIDTH,})- const canvas = document.createElement("canvas")-- canvas.width = Math.ceil(viewport.width)- canvas.height = Math.ceil(viewport.height)-- const canvasContext = canvas.getContext("2d")-- if (!canvasContext) return null-- await page.render({ canvas, canvasContext, viewport }).promise- return canvas.toDataURL("image/png")}function PdfThumbnailUrlGenerator({@@ -295,8 +250,8 @@ function PdfThumbnailUrlGenerator({let isCurrent = truevoid (async () => {- const pdf = await loadPdfDocument(url)- const eagerPageCount = Math.min(pdf.numPages, EAGER_PAGE_THUMBNAILS)+ const pageCount = await getPdfPageCount(url)+ const eagerPageCount = Math.min(pageCount, EAGER_PAGE_THUMBNAILS)const dataUrls: string[] = []for (let pageIndex = 0; pageIndex < eagerPageCount; pageIndex += 1) {@@ -309,7 +264,7 @@ function PdfThumbnailUrlGenerator({dataUrls.push(dataUrl)}if (isCurrent && dataUrls.length) {- onUrls(dataUrls, pdf.numPages)+ onUrls(dataUrls, pageCount)}})().catch(() => {})diff --git a/apps/v4/components/file-thumbnail-docs.tsx b/apps/v4/components/file-thumbnail-docs.tsxindex e302c10..ad7c49d 100644--- a/apps/v4/components/file-thumbnail-docs.tsx+++ b/apps/v4/components/file-thumbnail-docs.tsx@@ -12,7 +12,6 @@ import {useXlsxViewerThumbnails,XlsxViewerProvider,} from "@extend-ai/react-xlsx"-import type * as ReactPdf from "react-pdf"import { withUiBasePath } from "@/lib/zone-path"import { Button } from "@/components/ui/button"@@ -24,16 +23,16 @@ import {DocsSourceCodeBlock,DocsViewCodeBlock,} from "@/components/docs-code-block"+import { renderPdfThumbnailUrl } from "@/components/pdf-thumbnail-utils"const DOCX_MIME_TYPE ="application/vnd.openxmlformats-officedocument.wordprocessingml.document"const XLSX_MIME_TYPE ="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"+const PDF_THUMBNAIL_WIDTH = 240const DOCX_THUMBNAIL_WIDTH = 240const XLSX_THUMBNAIL_WIDTH = 520-type ReactPdfModule = typeof ReactPdf-type DemoFileKind = "image" | "pdf" | "docx" | "xlsx"type DemoFile = ThumbnailFile & {@@ -81,38 +80,6 @@ export const SAMPLE_FILES: DemoFile[] = [},]-function getPdfWorkerUrl(pdfjsVersion: string) {- return `//unpkg.com/pdfjs-dist@${pdfjsVersion}/legacy/build/pdf.worker.min.mjs`-}--function getPdfAssetBaseUrl(pdfjsVersion: string) {- return `//unpkg.com/pdfjs-dist@${pdfjsVersion}`-}--const defaultPdfDocumentOptionsByVersion = new Map<- string,- ReactPdf.DocumentProps["options"]->()--function getDefaultPdfDocumentOptions(pdfjsVersion: string) {- const cachedOptions = defaultPdfDocumentOptionsByVersion.get(pdfjsVersion)-- if (cachedOptions) {- return cachedOptions- }-- const assetBaseUrl = getPdfAssetBaseUrl(pdfjsVersion)- const options = {- cMapPacked: true,- cMapUrl: `${assetBaseUrl}/cmaps/`,- standardFontDataUrl: `${assetBaseUrl}/standard_fonts/`,- }-- defaultPdfDocumentOptionsByVersion.set(pdfjsVersion, options)-- return options-}-async function fetchFile(file: DemoFile) {const response = await fetch(file.url)@@ -160,67 +127,44 @@ function PdfThumbnailPreview({file: DemoFilepreviewAspectRatio?: number}) {- const [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null)- const [isReady, setIsReady] = React.useState(false)+ const [imageUrl, setImageUrl] = React.useState<string | null>(null)const [hasError, setHasError] = React.useState(false)- const pdfjsVersion = reactPdf?.pdfjs.version- const documentOptions = React.useMemo(- () =>- pdfjsVersion ? getDefaultPdfDocumentOptions(pdfjsVersion) : undefined,- [pdfjsVersion]- )React.useEffect(() => {- let isMounted = true+ let isCurrent = true- void import("react-pdf")- .then((module) => {- module.pdfjs.GlobalWorkerOptions.workerSrc = getPdfWorkerUrl(- module.pdfjs.version- )+ setImageUrl(null)+ setHasError(false)- if (isMounted) {- setReactPdf(module)+ void renderPdfThumbnailUrl({+ pageIndex: 0,+ url: file.url,+ width: PDF_THUMBNAIL_WIDTH,+ })+ .then((nextImageUrl) => {+ if (isCurrent) {+ setImageUrl(nextImageUrl)+ setHasError(!nextImageUrl)}}).catch(() => {- if (isMounted) {+ if (isCurrent) {setHasError(true)}})return () => {- isMounted = false+ isCurrent = false}- }, [])+ }, [file.url])return (<FileThumbnailfile={file}previewAspectRatio={previewAspectRatio ?? 0.77}previewClassName="bg-white"- previewContent={- reactPdf && !hasError ? (- <reactPdf.Document- file={file.url}- options={documentOptions}- loading={null}- error={null}- onLoadError={() => setHasError(true)}- >- <reactPdf.Thumbnail- pageNumber={1}- width={DOCX_THUMBNAIL_WIDTH}- loading={null}- error={null}- onRenderSuccess={() => setIsReady(true)}- onRenderError={() => setHasError(true)}- className="flex size-full items-center justify-center [&_.react-pdf__Thumbnail__page]:!m-0 [&_.react-pdf__Thumbnail__page]:!h-auto [&_.react-pdf__Thumbnail__page]:!w-full [&_.react-pdf__Thumbnail__page]:overflow-hidden [&_canvas]:!h-auto [&_canvas]:!w-full"- />- </reactPdf.Document>- ) : null- }- isLoading={!isReady && !hasError}+ previewImageUrl={imageUrl}+ isLoading={!imageUrl && !hasError}hasError={hasError}/>)@@ -592,18 +536,34 @@ import {} from "@extend-ai/react-xlsx"import { FileThumbnail } from "@/components/ui/file-thumbnail"+import { renderPdfThumbnailUrl } from "@/components/pdf-thumbnail-utils"++export function PdfAttachmentThumbnail({ fileUrl }) {+ const [imageUrl, setImageUrl] = React.useState(null)++ React.useEffect(() => {+ let isCurrent = true++ renderPdfThumbnailUrl({+ pageIndex: 0,+ url: fileUrl,+ width: 240,+ }).then((nextImageUrl) => {+ if (isCurrent) setImageUrl(nextImageUrl)+ })++ return () => {+ isCurrent = false+ }+ }, [fileUrl])-export function PdfAttachmentThumbnail({ reactPdf, fileUrl }) {return (<FileThumbnailfile={{ name: "contract.pdf", type: "application/pdf" }}previewAspectRatio={0.77}previewClassName="bg-white"- previewContent={- <reactPdf.Document file={fileUrl} loading={null} error={null}>- <reactPdf.Thumbnail pageNumber={1} width={240} />- </reactPdf.Document>- }+ previewImageUrl={imageUrl}+ isLoading={!imageUrl}/>)}diff --git a/apps/v4/components/layout-blocks-docs.tsx b/apps/v4/components/layout-blocks-docs.tsxindex 48fcc42..2c4abce 100644--- a/apps/v4/components/layout-blocks-docs.tsx+++ b/apps/v4/components/layout-blocks-docs.tsx@@ -8384,7 +8384,7 @@ const OcrBlockButton = React.memo(function OcrBlockButton({onMouseEnter={() => onFocusBlock(block)}onFocus={() => onFocusBlock(block)}className={cn(- "w-full rounded-lg border bg-background p-3 text-left transition-[border-color,background-color,box-shadow] hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",+ "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",isActive && cn("shadow-[0_0_0_1px_rgb(0_0_0_/_4%)]", style.ring))}>@@ -8526,7 +8526,7 @@ function OcrExampleCard({<buttontype="button"className={cn(- "w-full rounded-lg border bg-background p-3 text-left transition-[border-color,background-color,box-shadow] hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",+ "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",active &&(activeClassName ??"border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(0_0_0_/_4%)]")@@ -8614,7 +8614,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 const PDF_URL = "/samples/attention-rotated.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\nexport function blockToArea(block: OcrBlock): React.CSSProperties {\n const { left, top, right, bottom } = getBoundingBox(block)\n\n return {\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\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 transition-colors 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}: {\n block: OcrBlock\n isActive?: boolean\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(block)}\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 {\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 const PDF_URL = "/samples/attention-rotated.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\nexport function blockToArea(block: OcrBlock): React.CSSProperties {\n const { left, top, right, bottom } = getBoundingBox(block)\n\n return {\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\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}: {\n block: OcrBlock\n isActive?: boolean\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(block)}\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-thumbnail-utils.ts b/apps/v4/components/pdf-thumbnail-utils.tsnew file mode 100644index 0000000..f51dd69--- /dev/null+++ b/apps/v4/components/pdf-thumbnail-utils.ts@@ -0,0 +1,79 @@+import type { PdfDocumentObject, PdfEngine } from "@embedpdf/models"++const PDFIUM_VERSION = "2.14.4"+const PDFIUM_WASM_URL = `https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@${PDFIUM_VERSION}/dist/pdfium.wasm`++let sharedEnginePromise: Promise<PdfEngine> | null = null+const pdfDocumentCache = new Map<string, Promise<PdfDocumentObject>>()+const thumbnailUrlCache = new Map<string, Promise<string | null>>()++export function loadSharedPdfEngine() {+ sharedEnginePromise ??= import("@embedpdf/engines/pdfium-worker-engine").then(+ ({ createPdfiumEngine }) => createPdfiumEngine(PDFIUM_WASM_URL, {})+ )++ return sharedEnginePromise+}++export async function loadPdfDocument(url: string) {+ let documentPromise = pdfDocumentCache.get(url)++ if (!documentPromise) {+ documentPromise = loadSharedPdfEngine().then((engine) =>+ engine+ .openDocumentUrl(+ { id: url, url },+ { mode: url.startsWith("blob:") ? "full-fetch" : "auto" }+ )+ .toPromise()+ )+ pdfDocumentCache.set(url, documentPromise)+ }++ return documentPromise+}++export async function getPdfPageCount(url: string) {+ return (await loadPdfDocument(url)).pageCount+}++export function renderPdfThumbnailUrl({+ dpr = typeof window === "undefined" ? 1 : window.devicePixelRatio || 1,+ pageIndex,+ url,+ width,+}: {+ dpr?: number+ pageIndex: number+ url: string+ width: number+}) {+ const cacheKey = `${url}#${pageIndex}@${width}x${dpr}`+ let thumbnailPromise = thumbnailUrlCache.get(cacheKey)++ if (!thumbnailPromise) {+ thumbnailPromise = (async () => {+ const [engine, document] = await Promise.all([+ loadSharedPdfEngine(),+ loadPdfDocument(url),+ ])+ const page = document.pages[pageIndex]++ if (!page) return null++ const blob = await engine+ .renderThumbnail(document, page, {+ dpr,+ imageType: "image/png",+ scaleFactor: width / page.size.width,+ withAnnotations: true,+ })+ .toPromise()++ return URL.createObjectURL(blob)+ })()+ thumbnailUrlCache.set(cacheKey, thumbnailPromise)+ }++ return thumbnailPromise+}diff --git a/apps/v4/components/pdf-viewer-source-code.tsx b/apps/v4/components/pdf-viewer-source-code.tsxindex 3ab4247..3b5f38b 100644--- a/apps/v4/components/pdf-viewer-source-code.tsx+++ b/apps/v4/components/pdf-viewer-source-code.tsx@@ -2,8 +2,10 @@import { DocsSourceCodeBlock } from "@/components/docs-code-block"-const pdfViewerSourceCode =- "\"use client\"\n\nimport * as React from \"react\"\nimport {\n Download01Icon,\n MinusSignCircleIcon,\n PlusSignCircleIcon,\n RotateClockwiseIcon,\n Search01Icon,\n SidebarLeftIcon,\n Upload01Icon,\n} from \"@hugeicons/core-free-icons\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { useVirtualizer } from \"@tanstack/react-virtual\"\nimport type { PDFDocumentProxy } from \"pdfjs-dist\"\nimport type * as ReactPdf from \"react-pdf\"\n\nimport \"react-pdf/dist/Page/TextLayer.css\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport {\n DocumentViewerSidebarSkeleton,\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from \"@/components/ui/document-viewer-sidebar\"\nimport { FileThumbnail } from \"@/components/ui/file-thumbnail\"\nimport { Input } from \"@/components/ui/input\"\nimport {\n 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\"\n\ntype ReactPdfModule = typeof ReactPdf\ntype PageRotationDeltas = Map<number, number>\n\ntype PDFPageMetrics = {\n width: number\n height: number\n rotation: number\n}\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 PDFViewerScrollDirection = \"forward\" | \"backward\" | \"none\"\n\nexport type PDFViewerVisiblePagesRange = {\n activePage: number\n endPage: number\n isFastScrolling: boolean\n numPages: number\n pageRenderBuffer: number\n scrollDirection: PDFViewerScrollDirection\n startPage: number\n}\n\nexport type PDFViewerRenderRange = {\n endPage: number\n startPage: number\n}\n\nexport type PDFViewerProps = {\n file?: string\n className?: string\n documentOptions?: ReactPdf.DocumentProps[\"options\"]\n defaultThumbnailSidebarOpen?: boolean\n defaultZoom?: number\n pageWidth?: number\n pageHeight?: number\n pageNumbers?: number[]\n pageRenderBuffer?: number\n setRenderRange?: (\n visiblePagesRange: PDFViewerVisiblePagesRange\n ) => PDFViewerRenderRange\n downloadFileName?: 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 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_PAGE_WIDTH = 612\nconst DEFAULT_PAGE_HEIGHT = 792\nconst DEFAULT_ZOOM = 1\nconst ZOOM_OPTIONS = [0.5, 0.75, 1, 1.25, 1.5, 2]\nconst MAX_DEVICE_PIXEL_RATIO = 2\nconst DEFAULT_PAGE_RENDER_BUFFER = 4\nconst FAST_SCROLL_VELOCITY_PX_PER_MS = 1\nconst SCROLL_IDLE_TIMEOUT_MS = 180\nconst PAGE_VIRTUALIZER_PADDING = 24\nconst PAGE_VIRTUALIZER_GAP = 24\nconst THUMBNAIL_VIRTUALIZER_PADDING = 16\nconst THUMBNAIL_ITEM_CHROME_HEIGHT = 48\nconst THUMBNAIL_ITEM_GAP = 12\nconst THUMBNAIL_WIDTH = 92\ntype SearchHighlight = {\n id: string\n left: number\n top: number\n width: number\n height: number\n}\n\nfunction areNumberSetsEqual(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 getPdfWorkerUrl(pdfjsVersion: string) {\n return `//unpkg.com/pdfjs-dist@${pdfjsVersion}/legacy/build/pdf.worker.min.mjs`\n}\n\nfunction getPdfAssetBaseUrl(pdfjsVersion: string) {\n return `https://unpkg.com/pdfjs-dist@${pdfjsVersion}`\n}\n\nfunction getDefaultPdfDocumentOptions(\n pdfjsVersion: string\n): ReactPdf.DocumentProps[\"options\"] {\n const assetBaseUrl = getPdfAssetBaseUrl(pdfjsVersion)\n\n return {\n cMapPacked: true,\n cMapUrl: `${assetBaseUrl}/cmaps/`,\n standardFontDataUrl: `${assetBaseUrl}/standard_fonts/`,\n }\n}\n\nfunction normalizeRotation(rotation: number) {\n return (((Math.round(rotation / 90) * 90) % 360) + 360) % 360\n}\n\nfunction isQuarterTurn(rotation: number) {\n return Math.abs(normalizeRotation(rotation) / 90) % 2 === 1\n}\n\nfunction getPageDimensions(metrics: PDFPageMetrics, rotation: number) {\n return isQuarterTurn(rotation)\n ? { width: metrics.height, height: metrics.width }\n : { width: metrics.width, height: metrics.height }\n}\n\nfunction ensurePdfExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(\".pdf\") ? fileName : `${fileName}.pdf`\n}\n\nfunction getPdfDownloadFileName(fileName: string | undefined, file: string) {\n if (fileName?.trim()) return ensurePdfExtension(fileName.trim())\n\n const pathname = file.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 getPdfPageMetrics(\n pdf: PDFDocumentProxy,\n pageNumber: number\n): Promise<PDFPageMetrics> {\n const page = await pdf.getPage(pageNumber)\n const viewport = page.getViewport({ scale: 1, rotation: 0 })\n\n return {\n width: viewport.width,\n height: viewport.height,\n rotation: normalizeRotation(page.rotate),\n }\n}\n\nasync function downloadPdfWithPageRotations({\n file,\n fileName,\n pageRotationDeltas,\n}: {\n file: string\n fileName: string\n pageRotationDeltas: PageRotationDeltas\n}) {\n const response = await fetch(file)\n\n if (!response.ok) {\n throw new Error(`Failed to download PDF (${response.status})`)\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, index) => {\n const pageNumber = index + 1\n const rotationDelta = pageRotationDeltas.get(pageNumber) ?? 0\n\n if (!rotationDelta) return\n\n page.setRotation(\n degrees(normalizeRotation(page.getRotation().angle + rotationDelta))\n )\n })\n\n const nextPdfBytes = await pdfDocument.save()\n const nextPdfBuffer = new ArrayBuffer(nextPdfBytes.byteLength)\n new Uint8Array(nextPdfBuffer).set(nextPdfBytes)\n const hasPageRotationChanges = pageRotationDeltas.size > 0\n\n downloadBlob(\n new Blob([nextPdfBuffer], { type: \"application/pdf\" }),\n hasPageRotationChanges ? getRotatedPdfDownloadFileName(fileName) : fileName\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 inline={sidebarInline} />\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\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 SearchInput({\n value,\n onValueChange,\n onApply,\n onClear,\n}: {\n value: string\n onValueChange: (value: string) => void\n onApply: () => void\n onClear: () => void\n}) {\n return (\n <div className=\"space-y-3\">\n <Input\n placeholder=\"Search text\"\n value={value}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) =>\n onValueChange(event.target.value)\n }\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === \"Enter\") {\n onApply()\n }\n }}\n />\n <div className=\"flex justify-end gap-2\">\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={onClear}>\n Clear\n </Button>\n <Button type=\"button\" size=\"sm\" onClick={onApply}>\n Search\n </Button>\n </div>\n </div>\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 [isEditing, setIsEditing] = React.useState(false)\n const [draftPage, setDraftPage] = React.useState(() => String(activePage))\n\n React.useEffect(() => {\n if (!isEditing) {\n setDraftPage(String(activePage))\n }\n }, [activePage, 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(parsedPage)\n },\n [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=\"xs\"\n className=\"mx-0.5 h-auto min-w-7 rounded-sm px-1.5 py-0 text-sm leading-normal font-normal text-primary sm:text-sm\"\n aria-label={`Current page ${activePage}. Edit page number`}\n disabled={controlsDisabled}\n onClick={() => setIsEditing(true)}\n >\n {activePage}\n </Button>\n )}\n <span>of {numPages || \"-\"}</span>\n </div>\n )\n}\n\nfunction PDFSidebarThumbnail({\n pageMetrics,\n pageNumber,\n reactPdf,\n rotation,\n thumbnailAspectRatio,\n}: {\n pageMetrics: PDFPageMetrics\n pageNumber: number\n reactPdf: ReactPdfModule\n rotation: number\n thumbnailAspectRatio: number\n}) {\n const effectiveRotation = normalizeRotation(pageMetrics.rotation + rotation)\n\n return (\n <FileThumbnail\n file={{\n name: `Page ${pageNumber}.pdf`,\n type: \"application/pdf\",\n }}\n previewAspectRatio={thumbnailAspectRatio}\n previewClassName=\"rounded-md bg-white\"\n previewContent={\n <reactPdf.Thumbnail\n pageNumber={pageNumber}\n width={THUMBNAIL_WIDTH}\n rotate={effectiveRotation}\n className=\"flex size-full items-center justify-center [&_.react-pdf__Thumbnail__page]:!m-0 [&_.react-pdf__Thumbnail__page]:!h-auto [&_.react-pdf__Thumbnail__page]:!w-full [&_.react-pdf__Thumbnail__page]:overflow-hidden [&_canvas]:!h-auto [&_canvas]:!w-full\"\n />\n }\n className=\"w-[92px] rounded-md border-0 shadow-xs ring-0\"\n />\n )\n}\n\nfunction clampPageNumber(pageNumber: number, renderedPageNumbers: number[]) {\n if (!renderedPageNumbers.length) return pageNumber\n\n const minPage = Math.min(...renderedPageNumbers)\n const maxPage = Math.max(...renderedPageNumbers)\n\n return Math.min(Math.max(pageNumber, minPage), maxPage)\n}\n\nfunction normalizeRenderRange(\n range: PDFViewerRenderRange,\n renderedPageNumbers: number[]\n) {\n const startPage = clampPageNumber(\n Math.min(range.startPage, range.endPage),\n renderedPageNumbers\n )\n const endPage = clampPageNumber(\n Math.max(range.startPage, range.endPage),\n renderedPageNumbers\n )\n\n return { startPage, endPage }\n}\n\nfunction getPageRenderPriority({\n activePage,\n pageNumber,\n scrollDirection,\n}: {\n activePage: number\n pageNumber: number\n scrollDirection: PDFViewerScrollDirection\n}) {\n const distance = Math.abs(pageNumber - activePage)\n\n if (pageNumber === activePage) return -1000\n\n if (scrollDirection === \"forward\") {\n return pageNumber > activePage ? distance : distance + 1000\n }\n\n if (scrollDirection === \"backward\") {\n return pageNumber < activePage ? distance : distance + 1000\n }\n\n return distance\n}\n\nfunction PDFViewerPage({\n devicePixelRatioLimit,\n effectiveRotation,\n reactPdf,\n pageNumber,\n pageStyle,\n renderedPageWidth,\n zoom,\n shouldRenderPage,\n searchQuery,\n pageClassName,\n renderPageOverlay,\n onPageSettled,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n}: {\n devicePixelRatioLimit: number\n effectiveRotation: number\n reactPdf: ReactPdfModule\n pageNumber: number\n pageStyle: React.CSSProperties & { width: number; height: number }\n renderedPageWidth: number\n zoom: number\n shouldRenderPage: boolean\n searchQuery: string\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onPageSettled: (pageNumber: number, devicePixelRatioLimit: number) => 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 const pageRef = React.useRef<HTMLDivElement>(null)\n const [searchHighlights, setSearchHighlights] = React.useState<\n SearchHighlight[]\n >([])\n const hasSearchQuery = Boolean(searchQuery.trim())\n const clearSearchHighlights = React.useCallback(() => {\n setSearchHighlights((currentHighlights) =>\n currentHighlights.length ? [] : currentHighlights\n )\n }, [])\n\n const updateSearchHighlights = React.useCallback(() => {\n const pageElement = pageRef.current\n const query = searchQuery.trim().toLowerCase()\n\n if (!pageElement || !query) {\n clearSearchHighlights()\n return\n }\n\n const textLayer = pageElement.querySelector<HTMLElement>(\n \".react-pdf__Page__textContent\"\n )\n\n if (!textLayer) {\n clearSearchHighlights()\n return\n }\n\n const pageRect = pageElement.getBoundingClientRect()\n const nextHighlights: SearchHighlight[] = []\n\n textLayer.querySelectorAll<HTMLElement>(\"span\").forEach((span, index) => {\n const textNode = Array.from(span.childNodes).find(\n (node): node is Text => node.nodeType === Node.TEXT_NODE\n )\n const text = textNode?.textContent ?? \"\"\n const normalizedText = text.toLowerCase()\n let matchIndex = normalizedText.indexOf(query)\n\n while (textNode && matchIndex !== -1) {\n const range = document.createRange()\n range.setStart(textNode, matchIndex)\n range.setEnd(textNode, matchIndex + query.length)\n\n Array.from(range.getClientRects()).forEach((rect, rectIndex) => {\n if (rect.width <= 0 || rect.height <= 0) return\n\n nextHighlights.push({\n id: `${pageNumber}-${index}-${matchIndex}-${rectIndex}`,\n left: rect.left - pageRect.left,\n top: rect.top - pageRect.top,\n width: rect.width,\n height: rect.height,\n })\n })\n\n range.detach()\n matchIndex = normalizedText.indexOf(query, matchIndex + query.length)\n }\n })\n\n setSearchHighlights(nextHighlights)\n }, [clearSearchHighlights, pageNumber, searchQuery])\n\n React.useEffect(() => {\n if (!shouldRenderPage || !hasSearchQuery) {\n clearSearchHighlights()\n return\n }\n\n const frame = window.requestAnimationFrame(updateSearchHighlights)\n return () => window.cancelAnimationFrame(frame)\n }, [\n clearSearchHighlights,\n hasSearchQuery,\n shouldRenderPage,\n updateSearchHighlights,\n ])\n\n return (\n <div\n ref={pageRef}\n data-pdf-viewer-page={pageNumber}\n className={cn(\"relative\", pageClassName?.(pageNumber))}\n style={pageStyle}\n onPointerDown={(event) => onPagePointerDown?.(event, pageNumber)}\n onPointerMove={(event) => onPagePointerMove?.(event, pageNumber)}\n onPointerUp={(event) => onPagePointerUp?.(event, pageNumber)}\n onPointerCancel={(event) => onPagePointerCancel?.(event, pageNumber)}\n >\n {shouldRenderPage ? (\n <>\n <reactPdf.Page\n pageNumber={pageNumber}\n width={renderedPageWidth}\n rotate={effectiveRotation}\n className=\"overflow-hidden border bg-background shadow-xs\"\n renderAnnotationLayer={false}\n renderTextLayer={hasSearchQuery}\n devicePixelRatio={\n typeof window === \"undefined\"\n ? 1\n : Math.min(devicePixelRatioLimit, window.devicePixelRatio || 1)\n }\n loading={\n <div className=\"grid place-items-center\" style={pageStyle}>\n <Spinner className=\"size-4\" />\n </div>\n }\n onRenderSuccess={() =>\n onPageSettled(pageNumber, devicePixelRatioLimit)\n }\n onRenderTextLayerSuccess={updateSearchHighlights}\n onRenderError={() =>\n onPageSettled(pageNumber, devicePixelRatioLimit)\n }\n />\n {searchHighlights.length ? (\n <div className=\"pointer-events-none absolute inset-0 z-10\">\n {searchHighlights.map((highlight) => (\n <div\n key={highlight.id}\n className=\"absolute rounded-[2px] bg-yellow-300/45 mix-blend-multiply ring-1 ring-yellow-500/20 dark:bg-yellow-300/35\"\n style={{\n left: highlight.left,\n top: highlight.top,\n width: highlight.width,\n height: highlight.height,\n }}\n />\n ))}\n </div>\n ) : null}\n </>\n ) : (\n <div className=\"size-full border bg-white shadow-xs\" />\n )}\n {renderPageOverlay?.({\n pageNumber,\n pageWidth: pageStyle.width,\n pageHeight: pageStyle.height,\n scale: zoom,\n rotation: effectiveRotation,\n })}\n </div>\n )\n}\n\nexport const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(\n function PDFViewer(\n {\n file,\n className,\n documentOptions,\n defaultThumbnailSidebarOpen = false,\n defaultZoom = DEFAULT_ZOOM,\n pageWidth = DEFAULT_PAGE_WIDTH,\n pageHeight = DEFAULT_PAGE_HEIGHT,\n pageNumbers,\n pageRenderBuffer = DEFAULT_PAGE_RENDER_BUFFER,\n setRenderRange,\n downloadFileName,\n showDownload = true,\n showRotateControls = true,\n showToolbar = true,\n showUpload = true,\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 [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null)\n const [pdfDocument, setPdfDocument] =\n React.useState<PDFDocumentProxy | null>(null)\n const [pdfFile, setPdfFile] = React.useState(file ?? \"\")\n const [uploadedPdfUrl, setUploadedPdfUrl] = React.useState<string | null>(\n null\n )\n const [numPages, setNumPages] = React.useState(0)\n const [activePage, setActivePage] = React.useState(1)\n const [zoom, setZoom] = React.useState(defaultZoom)\n const [pageRotationDeltas, setPageRotationDeltas] =\n React.useState<PageRotationDeltas>(() => new Map())\n const [pageMetrics, setPageMetrics] = React.useState<\n Map<number, PDFPageMetrics>\n >(() => new Map())\n const [sidebarOpen, setSidebarOpen] = React.useState(\n defaultThumbnailSidebarOpen\n )\n const [searchDraft, setSearchDraft] = React.useState(\"\")\n const [searchQuery, setSearchQuery] = React.useState(\"\")\n const [isDocumentLoading, setIsDocumentLoading] = React.useState(true)\n const [isFirstPageRendering, setIsFirstPageRendering] = React.useState(true)\n const [settledPageNumbers, setSettledPageNumbers] = React.useState<\n Set<number>\n >(() => new Set())\n const [lowResolutionPageNumbers, setLowResolutionPageNumbers] =\n React.useState<Set<number>>(() => new Set())\n const [visiblePageNumbers, setVisiblePageNumbers] = React.useState<\n Set<number>\n >(() => new Set([1]))\n const [scrollState, setScrollState] = React.useState<{\n direction: PDFViewerScrollDirection\n isFastScrolling: boolean\n }>({ direction: \"none\", isFastScrolling: false })\n const [loadError, setLoadError] = React.useState(false)\n const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)\n const viewportRef = React.useRef<HTMLDivElement>(null)\n const thumbnailViewportRef = React.useRef<HTMLDivElement>(null)\n const wasThumbnailSidebarVisibleRef = React.useRef(false)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const thumbnailClickScrollYRef = React.useRef<number | null>(null)\n const pendingPageMetricsRef = React.useRef<Set<number>>(new Set())\n const pageMetricsGenerationRef = React.useRef(0)\n const scrollTrackerRef = React.useRef({\n scrollTop: 0,\n timestamp: 0,\n })\n\n React.useEffect(() => {\n setPdfFile(file ?? \"\")\n setLoadError(false)\n setIsDocumentLoading(Boolean(file))\n setIsFirstPageRendering(Boolean(file))\n setSettledPageNumbers(new Set())\n setPdfDocument(null)\n pendingPageMetricsRef.current.clear()\n pageMetricsGenerationRef.current += 1\n setNumPages(0)\n setActivePage(1)\n setPageMetrics(new Map())\n setPageRotationDeltas(new Map())\n setLowResolutionPageNumbers(new Set())\n setVisiblePageNumbers(new Set([1]))\n setScrollState({ direction: \"none\", isFastScrolling: false })\n }, [file])\n\n React.useEffect(() => {\n let mounted = true\n\n void import(\"react-pdf\")\n .then((module) => {\n module.pdfjs.GlobalWorkerOptions.workerSrc = getPdfWorkerUrl(\n module.pdfjs.version\n )\n\n if (mounted) {\n setReactPdf(module)\n }\n })\n .catch(() => {\n if (mounted) {\n setLoadError(true)\n setIsDocumentLoading(false)\n setIsFirstPageRendering(false)\n }\n })\n\n return () => {\n mounted = false\n }\n }, [])\n\n React.useEffect(() => {\n return () => {\n if (uploadedPdfUrl) {\n URL.revokeObjectURL(uploadedPdfUrl)\n }\n }\n }, [uploadedPdfUrl])\n\n const renderedPageNumbers = React.useMemo(() => {\n if (pageNumbers?.length) return pageNumbers\n\n return Array.from({ length: numPages || 1 }, (_, index) => index + 1)\n }, [numPages, pageNumbers])\n\n const firstRenderedPage = renderedPageNumbers[0] ?? 1\n const defaultPageMetrics = React.useMemo<PDFPageMetrics>(\n () => ({ width: pageWidth, height: pageHeight, rotation: 0 }),\n [pageHeight, pageWidth]\n )\n const getPageMetrics = React.useCallback(\n (pageNumber: number) => pageMetrics.get(pageNumber) ?? defaultPageMetrics,\n [defaultPageMetrics, pageMetrics]\n )\n const getEstimatedPageSize = React.useCallback(\n (index: number) => {\n const pageNumber = renderedPageNumbers[index] ?? firstRenderedPage\n const metrics = getPageMetrics(pageNumber)\n const rotationDelta = pageRotationDeltas.get(pageNumber) ?? 0\n const effectiveRotation = normalizeRotation(\n metrics.rotation + rotationDelta\n )\n const dimensions = getPageDimensions(metrics, effectiveRotation)\n\n return dimensions.height * zoom + PAGE_VIRTUALIZER_GAP\n },\n [\n firstRenderedPage,\n getPageMetrics,\n pageRotationDeltas,\n renderedPageNumbers,\n zoom,\n ]\n )\n const getEstimatedPageWidth = React.useCallback(\n (pageNumber: number) => {\n const metrics = getPageMetrics(pageNumber)\n const rotationDelta = pageRotationDeltas.get(pageNumber) ?? 0\n const effectiveRotation = normalizeRotation(\n metrics.rotation + rotationDelta\n )\n const dimensions = getPageDimensions(metrics, effectiveRotation)\n\n return dimensions.width * zoom\n },\n [getPageMetrics, pageRotationDeltas, zoom]\n )\n const pageVirtualizer = useVirtualizer({\n count: renderedPageNumbers.length,\n estimateSize: getEstimatedPageSize,\n getItemKey: (index) => renderedPageNumbers[index] ?? index,\n getScrollElement: () => viewportRef.current,\n overscan: scrollState.isFastScrolling ? 14 : 8,\n paddingEnd: PAGE_VIRTUALIZER_PADDING,\n paddingStart: PAGE_VIRTUALIZER_PADDING,\n scrollPaddingStart: PAGE_VIRTUALIZER_PADDING,\n })\n const virtualPageItems = pageVirtualizer.getVirtualItems()\n const virtualPageNumbers = React.useMemo(\n () =>\n virtualPageItems.flatMap((virtualPage) => {\n const pageNumber = renderedPageNumbers[virtualPage.index]\n\n return pageNumber ? [pageNumber] : []\n }),\n [renderedPageNumbers, virtualPageItems]\n )\n const virtualPageNumbersKey = virtualPageNumbers.join(\",\")\n const virtualPageNumberSet = React.useMemo(\n () =>\n new Set(\n virtualPageNumbersKey\n ? virtualPageNumbersKey\n .split(\",\")\n .map((pageNumber) => Number(pageNumber))\n : []\n ),\n [virtualPageNumbersKey]\n )\n const maxEstimatedPageWidth = React.useMemo(() => {\n if (!renderedPageNumbers.length) return pageWidth * zoom\n\n return renderedPageNumbers.reduce(\n (maxWidth, pageNumber) =>\n Math.max(maxWidth, getEstimatedPageWidth(pageNumber)),\n 0\n )\n }, [getEstimatedPageWidth, pageWidth, renderedPageNumbers, zoom])\n const activePageIndex = React.useMemo(\n () => renderedPageNumbers.indexOf(activePage),\n [activePage, renderedPageNumbers]\n )\n const loadPageMetrics = React.useCallback(\n async (pageNumbersToLoad: number[]) => {\n const pdf = pdfDocument\n\n if (!pdf) return\n\n const generation = pageMetricsGenerationRef.current\n const uniquePageNumbers = Array.from(new Set(pageNumbersToLoad)).filter(\n (pageNumber) =>\n pageNumber >= 1 &&\n pageNumber <= pdf.numPages &&\n !pageMetrics.has(pageNumber) &&\n !pendingPageMetricsRef.current.has(pageNumber)\n )\n\n if (!uniquePageNumbers.length) return\n\n uniquePageNumbers.forEach((pageNumber) => {\n pendingPageMetricsRef.current.add(pageNumber)\n })\n\n const pageMetricEntries = await Promise.all(\n uniquePageNumbers.map(async (pageNumber) => {\n try {\n return [\n pageNumber,\n await getPdfPageMetrics(pdf, pageNumber),\n ] as const\n } catch {\n return null\n }\n })\n )\n\n uniquePageNumbers.forEach((pageNumber) => {\n pendingPageMetricsRef.current.delete(pageNumber)\n })\n\n if (generation !== pageMetricsGenerationRef.current) return\n\n const resolvedPageMetricEntries = pageMetricEntries.filter(\n (entry): entry is readonly [number, PDFPageMetrics] => Boolean(entry)\n )\n\n if (!resolvedPageMetricEntries.length) return\n\n setPageMetrics((currentMetrics) => {\n const nextMetrics = new Map(currentMetrics)\n let changed = false\n\n resolvedPageMetricEntries.forEach(([pageNumber, metrics]) => {\n if (nextMetrics.has(pageNumber)) return\n nextMetrics.set(pageNumber, metrics)\n changed = true\n })\n\n return changed ? nextMetrics : currentMetrics\n })\n },\n [pageMetrics, pdfDocument]\n )\n const resolvedDownloadFileName = React.useMemo(\n () => getPdfDownloadFileName(downloadFileName, pdfFile),\n [downloadFileName, pdfFile]\n )\n const defaultDocumentOptions = React.useMemo(\n () =>\n reactPdf\n ? getDefaultPdfDocumentOptions(reactPdf.pdfjs.version)\n : undefined,\n [reactPdf]\n )\n const resolvedDocumentOptions = documentOptions ?? defaultDocumentOptions\n const hasPdfFile = Boolean(pdfFile)\n const controlsDisabled = !hasPdfFile || !reactPdf || !numPages\n const downloadDisabled = controlsDisabled || isPreparingDownload\n const isLoading =\n hasPdfFile && (!reactPdf || isDocumentLoading || isFirstPageRendering)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const thumbnailSidebarVisible = Boolean(\n sidebarOpen && !isLoading && !loadError\n )\n const normalizedPageRenderBuffer = Math.max(0, Math.floor(pageRenderBuffer))\n const getEstimatedThumbnailItemSize = React.useCallback(\n (index: number) => {\n const pageNumber = renderedPageNumbers[index] ?? firstRenderedPage\n const metrics = getPageMetrics(pageNumber)\n const rotationDelta = pageRotationDeltas.get(pageNumber) ?? 0\n const effectiveRotation = normalizeRotation(\n metrics.rotation + rotationDelta\n )\n const dimensions = getPageDimensions(metrics, effectiveRotation)\n const thumbnailAspectRatio = dimensions.width / dimensions.height\n\n return (\n THUMBNAIL_WIDTH / thumbnailAspectRatio +\n THUMBNAIL_ITEM_CHROME_HEIGHT +\n THUMBNAIL_ITEM_GAP\n )\n },\n [\n firstRenderedPage,\n getPageMetrics,\n pageRotationDeltas,\n renderedPageNumbers,\n ]\n )\n const thumbnailVirtualizer = useVirtualizer({\n count: thumbnailSidebarVisible ? renderedPageNumbers.length : 0,\n estimateSize: getEstimatedThumbnailItemSize,\n getItemKey: (index) => renderedPageNumbers[index] ?? index,\n getScrollElement: () => thumbnailViewportRef.current,\n overscan: 10,\n paddingEnd: THUMBNAIL_VIRTUALIZER_PADDING,\n paddingStart: THUMBNAIL_VIRTUALIZER_PADDING,\n scrollPaddingStart: THUMBNAIL_VIRTUALIZER_PADDING,\n })\n\n const renderRange = React.useMemo(() => {\n if (!renderedPageNumbers.length) {\n return { startPage: 1, endPage: 1 }\n }\n\n const slowTrailingBuffer =\n scrollState.direction === \"none\"\n ? 0\n : Math.min(2, normalizedPageRenderBuffer)\n const fastAheadBuffer = Math.max(normalizedPageRenderBuffer + 6, 8)\n const fastBehindBuffer = Math.min(1, normalizedPageRenderBuffer)\n const beforeBuffer = scrollState.isFastScrolling\n ? scrollState.direction === \"backward\"\n ? fastAheadBuffer\n : fastBehindBuffer\n : normalizedPageRenderBuffer +\n (scrollState.direction === \"backward\" ? slowTrailingBuffer : 0)\n const afterBuffer = scrollState.isFastScrolling\n ? scrollState.direction === \"forward\"\n ? fastAheadBuffer\n : fastBehindBuffer\n : normalizedPageRenderBuffer +\n (scrollState.direction === \"forward\" ? slowTrailingBuffer : 0)\n const defaultRange = normalizeRenderRange(\n {\n startPage: activePage - beforeBuffer,\n endPage: activePage + afterBuffer,\n },\n renderedPageNumbers\n )\n const customRange = setRenderRange?.({\n ...defaultRange,\n activePage,\n isFastScrolling: scrollState.isFastScrolling,\n numPages,\n pageRenderBuffer: normalizedPageRenderBuffer,\n scrollDirection: scrollState.direction,\n })\n\n return normalizeRenderRange(\n customRange ?? defaultRange,\n renderedPageNumbers\n )\n }, [\n activePage,\n normalizedPageRenderBuffer,\n numPages,\n renderedPageNumbers,\n scrollState.direction,\n scrollState.isFastScrolling,\n setRenderRange,\n ])\n\n React.useEffect(() => {\n if (lowResolutionPageNumbers.size === 0) {\n return\n }\n\n let hasStalePageNumber = false\n\n lowResolutionPageNumbers.forEach((pageNumber) => {\n if (!virtualPageNumberSet.has(pageNumber)) {\n hasStalePageNumber = true\n }\n })\n\n if (!hasStalePageNumber) {\n return\n }\n\n setLowResolutionPageNumbers((currentPageNumbers) => {\n let changed = false\n const nextPageNumbers = new Set(currentPageNumbers)\n\n currentPageNumbers.forEach((pageNumber) => {\n if (!virtualPageNumberSet.has(pageNumber)) {\n nextPageNumbers.delete(pageNumber)\n changed = true\n }\n })\n\n return changed ? nextPageNumbers : currentPageNumbers\n })\n }, [lowResolutionPageNumbers, virtualPageNumberSet])\n\n const queuedPageNumbers = React.useMemo(() => {\n if (renderedPageNumbers.length <= 3) {\n return new Set(renderedPageNumbers)\n }\n\n const maxUnsettledPages = scrollState.isFastScrolling ? 4 : 8\n const visibleUnsettledCandidates = virtualPageNumbers.filter(\n (pageNumber) =>\n visiblePageNumbers.has(pageNumber) &&\n !settledPageNumbers.has(pageNumber)\n )\n const unsettledCandidates = virtualPageNumbers\n .filter(\n (pageNumber) =>\n pageNumber >= renderRange.startPage &&\n pageNumber <= renderRange.endPage &&\n !visiblePageNumbers.has(pageNumber) &&\n !settledPageNumbers.has(pageNumber)\n )\n .sort(\n (leftPage, rightPage) =>\n getPageRenderPriority({\n activePage,\n pageNumber: leftPage,\n scrollDirection: scrollState.direction,\n }) -\n getPageRenderPriority({\n activePage,\n pageNumber: rightPage,\n scrollDirection: scrollState.direction,\n })\n )\n\n return new Set(\n [...visibleUnsettledCandidates, ...unsettledCandidates].slice(\n 0,\n maxUnsettledPages\n )\n )\n }, [\n activePage,\n renderRange.endPage,\n renderRange.startPage,\n renderedPageNumbers,\n scrollState.direction,\n scrollState.isFastScrolling,\n settledPageNumbers,\n visiblePageNumbers,\n virtualPageNumbers,\n ])\n\n const pageNumbersForMetrics = React.useMemo(() => {\n const nextPageNumbers = new Set<number>([\n firstRenderedPage,\n activePage,\n ...visiblePageNumbers,\n ...virtualPageNumbers,\n ])\n\n renderedPageNumbers.forEach((pageNumber) => {\n if (\n pageNumber >= renderRange.startPage &&\n pageNumber <= renderRange.endPage\n ) {\n nextPageNumbers.add(pageNumber)\n }\n })\n\n return Array.from(nextPageNumbers)\n }, [\n activePage,\n firstRenderedPage,\n renderRange.endPage,\n renderRange.startPage,\n renderedPageNumbers,\n visiblePageNumbers,\n virtualPageNumbers,\n ])\n\n React.useEffect(() => {\n void loadPageMetrics(pageNumbersForMetrics)\n }, [loadPageMetrics, pageNumbersForMetrics])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !renderedPageNumbers.length) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n const nextVisiblePageNumbers = new Set<number>()\n let closestPage = renderedPageNumbers[0] ?? 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\"[data-pdf-viewer-page]\")\n .forEach((pageElement) => {\n const pageNumber = Number(pageElement.dataset.pdfViewerPage)\n\n if (!pageNumber) return\n\n const pageRect = pageElement.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (\n pageRect.bottom > viewportRect.top &&\n pageRect.top < viewportRect.bottom\n ) {\n nextVisiblePageNumbers.add(pageNumber)\n }\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageNumber\n }\n })\n\n if (!nextVisiblePageNumbers.size) {\n nextVisiblePageNumbers.add(closestPage)\n }\n\n setActivePage((currentPage) => {\n if (currentPage === closestPage) return currentPage\n onActivePageChange?.(closestPage)\n return closestPage\n })\n\n setVisiblePageNumbers((currentPageNumbers) =>\n areNumberSetsEqual(currentPageNumbers, nextVisiblePageNumbers)\n ? currentPageNumbers\n : nextVisiblePageNumbers\n )\n }, [onActivePageChange, renderedPageNumbers])\n\n React.useEffect(() => {\n const frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n\n return () => window.cancelAnimationFrame(frameId)\n }, [updateActivePageFromViewport, virtualPageNumbersKey])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !numPages) return\n\n let frameId = 0\n let idleTimeoutId = 0\n const handleScroll = () => {\n const currentScrollTop = viewport.scrollTop\n const currentTimestamp = performance.now()\n const previous = scrollTrackerRef.current\n const delta = currentScrollTop - previous.scrollTop\n const elapsed = Math.max(1, currentTimestamp - previous.timestamp)\n const speed = Math.abs(delta) / elapsed\n const direction: PDFViewerScrollDirection =\n delta > 0 ? \"forward\" : delta < 0 ? \"backward\" : \"none\"\n const isFastScrolling = speed >= FAST_SCROLL_VELOCITY_PX_PER_MS\n\n scrollTrackerRef.current = {\n scrollTop: currentScrollTop,\n timestamp: currentTimestamp,\n }\n\n if (direction !== \"none\") {\n setScrollState((currentState) =>\n currentState.direction === direction &&\n currentState.isFastScrolling === isFastScrolling\n ? currentState\n : { direction, isFastScrolling }\n )\n }\n\n window.clearTimeout(idleTimeoutId)\n idleTimeoutId = window.setTimeout(() => {\n setScrollState((currentState) =>\n currentState.direction === \"none\" && !currentState.isFastScrolling\n ? currentState\n : { direction: \"none\", isFastScrolling: false }\n )\n }, SCROLL_IDLE_TIMEOUT_MS)\n\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n scrollTrackerRef.current = {\n scrollTop: viewport.scrollTop,\n timestamp: performance.now(),\n }\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener(\"scroll\", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n window.clearTimeout(idleTimeoutId)\n viewport.removeEventListener(\"scroll\", handleScroll)\n }\n }, [numPages, updateActivePageFromViewport])\n\n React.useImperativeHandle(\n ref,\n () => ({\n scrollToPage: (pageNumber, options) => {\n const pageIndex = renderedPageNumbers.indexOf(pageNumber)\n if (pageIndex === -1) return\n\n pageVirtualizer.scrollToIndex(pageIndex, {\n align: \"start\",\n behavior: options?.behavior ?? \"auto\",\n })\n },\n scrollToPageArea: (pageNumber, area, options) => {\n const viewport = viewportRef.current\n const pageIndex = renderedPageNumbers.indexOf(pageNumber)\n const pageOffset = pageVirtualizer.getOffsetForIndex(\n pageIndex,\n \"start\"\n )?.[0]\n\n if (!viewport || pageIndex === -1 || pageOffset === undefined) return\n\n const metrics = getPageMetrics(pageNumber)\n const rotationDelta = pageRotationDeltas.get(pageNumber) ?? 0\n const effectiveRotation = normalizeRotation(\n metrics.rotation + rotationDelta\n )\n const dimensions = getPageDimensions(metrics, effectiveRotation)\n const targetTop =\n pageOffset + (area.top / 100) * dimensions.height * zoom - 96\n\n viewport.scrollTo({\n top: Math.max(0, targetTop),\n behavior: \"smooth\",\n ...options,\n })\n },\n getViewportElement: () => viewportRef.current,\n }),\n [\n getPageMetrics,\n pageRotationDeltas,\n pageVirtualizer,\n renderedPageNumbers,\n zoom,\n ]\n )\n\n const restoreWindowScroll = React.useCallback((scrollY: number) => {\n window.scrollTo({ top: scrollY })\n window.requestAnimationFrame(() => {\n window.scrollTo({ top: scrollY })\n window.requestAnimationFrame(() => {\n window.scrollTo({ top: scrollY })\n })\n })\n ;[0, 50, 150, 300].forEach((delay) => {\n window.setTimeout(() => {\n window.scrollTo({ top: scrollY })\n }, delay)\n })\n }, [])\n\n const scrollToPage = React.useCallback(\n (pageNumber: number) => {\n const windowScrollY = thumbnailClickScrollYRef.current ?? window.scrollY\n setActivePage(pageNumber)\n onActivePageChange?.(pageNumber)\n\n const pageIndex = renderedPageNumbers.indexOf(pageNumber)\n\n if (pageIndex === -1) {\n restoreWindowScroll(windowScrollY)\n return\n }\n\n pageVirtualizer.scrollToIndex(pageIndex, {\n align: \"start\",\n behavior: \"auto\",\n })\n restoreWindowScroll(windowScrollY)\n window.setTimeout(() => {\n if (thumbnailClickScrollYRef.current === windowScrollY) {\n thumbnailClickScrollYRef.current = null\n }\n }, 350)\n },\n [\n onActivePageChange,\n pageVirtualizer,\n renderedPageNumbers,\n restoreWindowScroll,\n ]\n )\n\n const handlePageNumberChange = React.useCallback(\n (pageNumber: number) => {\n if (!renderedPageNumbers.includes(pageNumber)) return\n\n scrollToPage(pageNumber)\n },\n [renderedPageNumbers, scrollToPage]\n )\n\n const preserveThumbnailClickScroll = React.useCallback(\n (event: React.PointerEvent | React.MouseEvent) => {\n event.preventDefault()\n\n if (thumbnailClickScrollYRef.current === null) {\n thumbnailClickScrollYRef.current = window.scrollY\n }\n },\n []\n )\n\n const scrollActiveThumbnailIntoView = React.useCallback(() => {\n if (activePageIndex === -1) return\n\n thumbnailVirtualizer.scrollToIndex(activePageIndex, {\n align: \"center\",\n behavior: \"auto\",\n })\n }, [activePageIndex, thumbnailVirtualizer])\n\n React.useEffect(() => {\n const wasThumbnailSidebarVisible = wasThumbnailSidebarVisibleRef.current\n wasThumbnailSidebarVisibleRef.current = thumbnailSidebarVisible\n\n if (!thumbnailSidebarVisible || wasThumbnailSidebarVisible) return\n\n const frameId = window.requestAnimationFrame(\n scrollActiveThumbnailIntoView\n )\n\n return () => window.cancelAnimationFrame(frameId)\n }, [scrollActiveThumbnailIntoView, thumbnailSidebarVisible])\n\n const handleLoadStart = React.useCallback(() => {\n setIsDocumentLoading(true)\n setIsFirstPageRendering(true)\n setLoadError(false)\n setPdfDocument(null)\n pendingPageMetricsRef.current.clear()\n pageMetricsGenerationRef.current += 1\n setNumPages(0)\n setActivePage(1)\n setPageMetrics(new Map())\n setPageRotationDeltas(new Map())\n setSettledPageNumbers(new Set())\n setLowResolutionPageNumbers(new Set())\n setVisiblePageNumbers(new Set([1]))\n setScrollState({ direction: \"none\", isFastScrolling: false })\n onActivePageChange?.(1)\n setSearchQuery(\"\")\n setSearchDraft(\"\")\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [onActivePageChange])\n\n const handleLoadSuccess = React.useCallback(\n async (pdf: PDFDocumentProxy) => {\n const nextNumPages = pdf.numPages\n const nextGeneration = pageMetricsGenerationRef.current + 1\n\n pageMetricsGenerationRef.current = nextGeneration\n pendingPageMetricsRef.current.clear()\n setPdfDocument(pdf)\n setNumPages(nextNumPages)\n setIsFirstPageRendering(true)\n setSettledPageNumbers(new Set())\n setLowResolutionPageNumbers(new Set())\n setVisiblePageNumbers(new Set([1]))\n setLoadError(false)\n setActivePage(1)\n onActivePageChange?.(1)\n onDocumentLoadSuccess?.(nextNumPages)\n setSearchQuery(\"\")\n setSearchDraft(\"\")\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n\n try {\n const initialPageNumber = pageNumbers?.[0] ?? 1\n const initialMetrics = await getPdfPageMetrics(pdf, initialPageNumber)\n\n if (nextGeneration === pageMetricsGenerationRef.current) {\n setPageMetrics(new Map([[initialPageNumber, initialMetrics]]))\n }\n } catch {\n setPageMetrics(new Map())\n } finally {\n setIsDocumentLoading(false)\n }\n },\n [onActivePageChange, onDocumentLoadSuccess, pageNumbers]\n )\n\n const handleLoadError = React.useCallback(() => {\n setIsDocumentLoading(false)\n setIsFirstPageRendering(false)\n setLoadError(true)\n setPdfDocument(null)\n pendingPageMetricsRef.current.clear()\n pageMetricsGenerationRef.current += 1\n setNumPages(0)\n setPageMetrics(new Map())\n setPageRotationDeltas(new Map())\n setSettledPageNumbers(new Set())\n setLowResolutionPageNumbers(new Set())\n setVisiblePageNumbers(new Set([1]))\n }, [])\n\n const handlePageSettled = React.useCallback(\n (pageNumber: number, devicePixelRatioLimit: number) => {\n setSettledPageNumbers((currentPageNumbers) => {\n if (currentPageNumbers.has(pageNumber)) return currentPageNumbers\n\n const nextPageNumbers = new Set(currentPageNumbers)\n nextPageNumbers.add(pageNumber)\n return nextPageNumbers\n })\n setLowResolutionPageNumbers((currentPageNumbers) => {\n const isLowResolutionRender =\n devicePixelRatioLimit < MAX_DEVICE_PIXEL_RATIO\n const alreadyLowResolution = currentPageNumbers.has(pageNumber)\n\n if (isLowResolutionRender && alreadyLowResolution) {\n return currentPageNumbers\n }\n\n if (!isLowResolutionRender && !alreadyLowResolution) {\n return currentPageNumbers\n }\n\n const nextPageNumbers = new Set(currentPageNumbers)\n\n if (isLowResolutionRender) {\n nextPageNumbers.add(pageNumber)\n } else {\n nextPageNumbers.delete(pageNumber)\n }\n\n return nextPageNumbers\n })\n\n if (pageNumber === firstRenderedPage) {\n setIsFirstPageRendering(false)\n }\n },\n [firstRenderedPage]\n )\n\n React.useEffect(() => {\n setSettledPageNumbers(new Set())\n setLowResolutionPageNumbers(new Set())\n setVisiblePageNumbers(new Set([1]))\n setIsFirstPageRendering(Boolean(pdfFile))\n }, [pdfFile])\n\n const rotateActivePage = React.useCallback(\n (rotationDelta: number) => {\n setPageRotationDeltas((currentRotations) => {\n const currentRotation = currentRotations.get(activePage) ?? 0\n const nextRotation = normalizeRotation(\n currentRotation + rotationDelta\n )\n const nextRotations = new Map(currentRotations)\n\n if (nextRotation) {\n nextRotations.set(activePage, nextRotation)\n } else {\n nextRotations.delete(activePage)\n }\n\n return nextRotations\n })\n },\n [activePage]\n )\n\n const handleDownload = React.useCallback(async () => {\n if (!pdfFile || isPreparingDownload) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadPdfWithPageRotations({\n file: pdfFile,\n fileName: resolvedDownloadFileName,\n pageRotationDeltas,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [\n isPreparingDownload,\n pageRotationDeltas,\n pdfFile,\n resolvedDownloadFileName,\n ])\n\n const handleUpload = React.useCallback(\n (file: File) => {\n const nextUrl = URL.createObjectURL(file)\n\n setUploadedPdfUrl((previousUrl) => {\n if (previousUrl) URL.revokeObjectURL(previousUrl)\n return nextUrl\n })\n setPdfFile(nextUrl)\n onPdfUpload?.(file)\n },\n [onPdfUpload]\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 <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={() => setSidebarOpen((open) => !open)}\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={handlePageNumberChange}\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 page counterclockwise\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Rotate page counterclockwise\"\n disabled={controlsDisabled}\n onClick={() => rotateActivePage(-90)}\n >\n <HugeiconsIcon\n icon={RotateClockwiseIcon}\n className=\"size-4 -scale-x-100\"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label=\"Rotate page clockwise\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Rotate page clockwise\"\n disabled={controlsDisabled}\n onClick={() => rotateActivePage(90)}\n >\n <HugeiconsIcon\n icon={RotateClockwiseIcon}\n className=\"size-4\"\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={controlsDisabled || zoom <= ZOOM_OPTIONS[0]}\n onClick={() => {\n const currentIndex = ZOOM_OPTIONS.indexOf(zoom)\n setZoom(\n ZOOM_OPTIONS[Math.max(0, currentIndex - 1)] ?? zoom\n )\n }}\n >\n <HugeiconsIcon\n icon={MinusSignCircleIcon}\n className=\"size-4\"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(zoom)}\n onValueChange={(value) => setZoom(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(zoom * 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 zoom >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n }\n onClick={() => {\n const currentIndex = ZOOM_OPTIONS.indexOf(zoom)\n setZoom(\n ZOOM_OPTIONS[\n Math.min(ZOOM_OPTIONS.length - 1, currentIndex + 1)\n ] ?? zoom\n )\n }}\n >\n <HugeiconsIcon\n icon={PlusSignCircleIcon}\n className=\"size-4\"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\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-64\">\n <SearchInput\n value={searchDraft}\n onValueChange={setSearchDraft}\n onApply={() => setSearchQuery(searchDraft)}\n onClear={() => {\n setSearchDraft(\"\")\n setSearchQuery(\"\")\n }}\n />\n </PopoverContent>\n </Popover>\n {showDownload ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n <ToolbarTooltip label=\"Download PDF\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Download PDF\"\n disabled={downloadDisabled}\n onClick={handleDownload}\n >\n {isPreparingDownload ? (\n <Spinner className=\"size-4\" />\n ) : (\n <HugeiconsIcon\n icon={Download01Icon}\n className=\"size-4\"\n />\n )}\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n {showUpload ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n <ToolbarTooltip label=\"Upload PDF\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Upload PDF\"\n render={\n <label>\n <input\n type=\"file\"\n accept=\"application/pdf,.pdf\"\n className=\"sr-only\"\n onChange={(event) => {\n const nextFile = event.target.files?.[0]\n\n if (nextFile) {\n handleUpload(nextFile)\n event.currentTarget.value = \"\"\n }\n }}\n />\n <HugeiconsIcon\n icon={Upload01Icon}\n className=\"size-4\"\n />\n </label>\n }\n />\n </ToolbarTooltip>\n </>\n ) : null}\n {toolbarActions ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n {toolbarActions}\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\n ) : null}\n <div\n ref={viewerShellRef}\n className=\"relative flex min-h-0 flex-1 overflow-hidden bg-muted/30\"\n >\n {!hasPdfFile ? (\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>file</code> prop or use the\n upload control.\n </div>\n </div>\n </div>\n ) : null}\n {isLoading && !loadError ? (\n <PDFViewerLoadingSkeleton\n sidebarInline={sidebarInline}\n sidebarOpen={sidebarOpen}\n />\n ) : null}\n {loadError ? (\n <div className=\"absolute inset-0 z-20 grid place-items-center bg-background p-6 text-sm text-muted-foreground\">\n Unable to load the PDF preview.\n </div>\n ) : null}\n {reactPdf && hasPdfFile ? (\n <reactPdf.Document\n file={pdfFile}\n options={resolvedDocumentOptions}\n className={cn(\n \"flex h-full min-h-0 w-full flex-1\",\n (isLoading || loadError) && \"invisible\"\n )}\n loading={null}\n error={null}\n onLoadStart={handleLoadStart}\n onLoadSuccess={handleLoadSuccess}\n onLoadError={handleLoadError}\n onItemClick={({ pageNumber }) => scrollToPage(pageNumber)}\n >\n <div className=\"flex h-full max-h-full min-h-0 w-full flex-1 overflow-hidden\">\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={thumbnailSidebarVisible}\n >\n {thumbnailSidebarVisible ? (\n <ScrollArea\n className=\"h-full\"\n scrollFade\n viewportRef={thumbnailViewportRef}\n >\n <div\n className=\"relative\"\n style={{ height: thumbnailVirtualizer.getTotalSize() }}\n >\n {thumbnailVirtualizer\n .getVirtualItems()\n .map((virtualThumbnail) => {\n const pageNumber =\n renderedPageNumbers[virtualThumbnail.index]\n\n if (!pageNumber) return null\n\n const metrics = getPageMetrics(pageNumber)\n const rotationDelta =\n pageRotationDeltas.get(pageNumber) ?? 0\n const effectiveRotation = normalizeRotation(\n metrics.rotation + rotationDelta\n )\n const thumbnailDimensions = getPageDimensions(\n metrics,\n effectiveRotation\n )\n const thumbnailAspectRatio =\n thumbnailDimensions.width /\n thumbnailDimensions.height\n\n return (\n <div\n key={virtualThumbnail.key}\n className=\"absolute top-0 right-4 left-4 flex justify-center [contain:layout_paint]\"\n style={{\n transform: `translateY(${virtualThumbnail.start}px)`,\n }}\n >\n <Button\n data-pdf-viewer-thumbnail={pageNumber}\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 pageNumber === activePage\n ? \"bg-sidebar-accent text-foreground\"\n : \"text-muted-foreground\"\n )}\n onFocus={(event) =>\n event.currentTarget.blur()\n }\n onMouseDown={preserveThumbnailClickScroll}\n onPointerDown={preserveThumbnailClickScroll}\n onClick={() => scrollToPage(pageNumber)}\n >\n <PDFSidebarThumbnail\n pageMetrics={metrics}\n pageNumber={pageNumber}\n reactPdf={reactPdf}\n rotation={rotationDelta}\n thumbnailAspectRatio={thumbnailAspectRatio}\n />\n {pageNumber}\n </Button>\n </div>\n )\n })}\n </div>\n </ScrollArea>\n ) : null}\n </DocumentViewerThumbnailSidebar>\n <ScrollArea\n className=\"h-full max-h-full min-h-0 min-w-0 flex-1\"\n viewportClassName={cn(\n isFirstPageRendering && !loadError && \"invisible\"\n )}\n viewportRef={viewportRef}\n >\n <div\n className=\"relative min-h-full min-w-full\"\n style={{\n height: pageVirtualizer.getTotalSize(),\n width:\n maxEstimatedPageWidth + PAGE_VIRTUALIZER_PADDING * 2,\n }}\n >\n {virtualPageItems.map((virtualPage) => {\n const pageNumber = renderedPageNumbers[virtualPage.index]\n\n if (!pageNumber) return null\n\n const metrics = getPageMetrics(pageNumber)\n const rotationDelta =\n pageRotationDeltas.get(pageNumber) ?? 0\n const effectiveRotation = normalizeRotation(\n metrics.rotation + rotationDelta\n )\n const dimensions = getPageDimensions(\n metrics,\n effectiveRotation\n )\n const shouldRenderPage =\n settledPageNumbers.has(pageNumber) ||\n queuedPageNumbers.has(pageNumber)\n const devicePixelRatioLimit =\n (scrollState.isFastScrolling &&\n !settledPageNumbers.has(pageNumber)) ||\n lowResolutionPageNumbers.has(pageNumber)\n ? 1\n : MAX_DEVICE_PIXEL_RATIO\n const pageStyle = {\n width: dimensions.width * zoom,\n height: dimensions.height * zoom,\n }\n const pageSearchQuery =\n searchQuery.trim() &&\n Math.abs(pageNumber - activePage) <= 1\n ? searchQuery\n : \"\"\n\n return (\n <div\n key={virtualPage.key}\n className=\"absolute top-0 left-1/2 [contain:layout_paint]\"\n style={{\n height: pageStyle.height,\n transform: `translateX(-50%) translateY(${virtualPage.start}px)`,\n width: pageStyle.width,\n }}\n >\n <PDFViewerPage\n devicePixelRatioLimit={devicePixelRatioLimit}\n effectiveRotation={effectiveRotation}\n reactPdf={reactPdf}\n pageNumber={pageNumber}\n pageStyle={pageStyle}\n renderedPageWidth={pageStyle.width}\n zoom={zoom}\n shouldRenderPage={shouldRenderPage}\n searchQuery={pageSearchQuery}\n pageClassName={pageClassName}\n renderPageOverlay={renderPageOverlay}\n onPageSettled={handlePageSettled}\n onPagePointerDown={onPagePointerDown}\n onPagePointerMove={onPagePointerMove}\n onPagePointerUp={onPagePointerUp}\n onPagePointerCancel={onPagePointerCancel}\n />\n </div>\n )\n })}\n </div>\n </ScrollArea>\n </div>\n </reactPdf.Document>\n ) : null}\n </div>\n </div>\n )\n }\n)\n"+// Generated from components/ui/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 type WindowState,\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 ArrowDown01Icon,\n ArrowUp01Icon,\n Download01Icon,\n MinusSignCircleIcon,\n PlusSignCircleIcon,\n RotateClockwiseIcon,\n Search01Icon,\n SidebarLeftIcon,\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 {\n DocumentViewerSidebarSkeleton,\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from \"@/components/ui/document-viewer-sidebar\"\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 \"@/components/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 PDFViewerProps = {\n file?: string\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n defaultZoom?: number\n /** Retained for API compatibility; page sizes come from the document. */\n pageWidth?: number\n /** Retained for API compatibility; page sizes come from the document. */\n pageHeight?: number\n downloadFileName?: 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 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 TEXT_SELECTION_BACKGROUND = \"rgba(59, 130, 246, 0.14)\"\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, file: string) {\n if (fileName?.trim()) return ensurePdfExtension(fileName.trim())\n\n const pathname = file.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 file,\n fileName,\n pageRotationDeltas,\n}: {\n file: string\n fileName: string\n pageRotationDeltas: PageRotationDeltas\n}) {\n const response = await fetch(file)\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 as the\n// full viewer, with only the upload control usable.\nfunction PDFViewerFallbackShell({\n className,\n showToolbar,\n showUpload,\n sidebarOpen,\n state,\n onUploadFile,\n}: {\n className?: string\n showToolbar: boolean\n showUpload: boolean\n sidebarOpen: boolean\n state: \"loading\" | \"error\" | \"empty\"\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 <div className=\"flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2\">\n {showUpload && onUploadFile ? (\n <PDFViewerUploadControl onUploadFile={onUploadFile} />\n ) : null}\n </div>\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 Unable to load the PDF preview.\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>file</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 PDFViewerUploadControl({\n onUploadFile,\n}: {\n onUploadFile: (file: File) => void\n}) {\n const inputRef = React.useRef<HTMLInputElement>(null)\n\n return (\n <>\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 <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Upload PDF\"\n onClick={() => inputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className=\"size-4\" />\n </Button>\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) {\n setDraftPage(String(displayPage))\n }\n }, [displayPage, isEditing])\n\n React.useEffect(() => {\n if (!isEditing) return\n\n inputRef.current?.focus()\n inputRef.current?.setSelectionRange(draftPage.length, draftPage.length)\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\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 const applySearch = React.useCallback(() => {\n const query = searchDraft.trim()\n\n if (!provides) return\n\n if (!query) {\n provides.stopSearch()\n return\n }\n\n provides.startSearch()\n provides.searchAllPages(query).wait(\n (result) => {\n const firstResult = result.results[0]\n\n if (firstResult && scroll) {\n provides.goToResult(0)\n const firstRect = firstResult.rects[0]\n\n scroll.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 },\n () => undefined\n )\n }, [provides, scroll, searchDraft])\n\n const clearSearch = React.useCallback(() => {\n setSearchDraft(\"\")\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={(event) => setSearchDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === \"Enter\") {\n applySearch()\n }\n }}\n />\n <div className=\"flex items-center justify-between gap-2\">\n <div className=\"flex items-center gap-1\">\n <ToolbarTooltip label=\"Previous match\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Previous match\"\n disabled={state.total === 0}\n onClick={() => navigate(-1)}\n >\n <HugeiconsIcon icon={ArrowUp01Icon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label=\"Next match\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Next match\"\n disabled={state.total === 0}\n onClick={() => navigate(1)}\n >\n <HugeiconsIcon icon={ArrowDown01Icon} className=\"size-4\" />\n </Button>\n </ToolbarTooltip>\n {state.active && state.query ? (\n <span className=\"text-xs text-muted-foreground tabular-nums\">\n {state.total === 0\n ? \"No matches\"\n : `${state.activeResultIndex + 1} of ${state.total}`}\n </span>\n ) : null}\n </div>\n <div className=\"flex gap-2\">\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={clearSearch}\n >\n Clear\n </Button>\n <Button type=\"button\" size=\"sm\" onClick={applySearch}>\n Search\n </Button>\n </div>\n </div>\n </div>\n </PopoverContent>\n </Popover>\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=\"absolute right-0 left-0 flex justify-center\"\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-none select-none hover:bg-sidebar-accent\",\n isActive || isSelected\n ? \"bg-sidebar-accent text-foreground\"\n : \"text-muted-foreground\"\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 [windowData, setWindowData] = React.useState<{\n docId: string | null\n window: WindowState | null\n }>({ docId: null, window: null })\n const [viewportMetrics, setViewportMetrics] = React.useState({\n clientHeight: 0,\n scrollTop: 0,\n })\n\n const windowState = windowData.docId === documentId ? windowData.window : null\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 if (!thumbnailPlugin) return\n\n const scope = thumbnailPlugin.provides().forDocument(documentId)\n const initialWindow = scope.getWindow()\n\n if (initialWindow) {\n setWindowData({ docId: documentId, window: initialWindow })\n }\n\n const unsubscribe = scope.onWindow((nextWindow) => {\n setWindowData({ docId: documentId, window: nextWindow })\n })\n\n return () => {\n unsubscribe()\n setWindowData({ docId: null, window: null })\n }\n }, [documentId, thumbnailPlugin])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailPlugin) return\n\n const scope = thumbnailPlugin.provides().forDocument(documentId)\n const updateWindow = () => {\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n scope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n }\n\n viewport.addEventListener(\"scroll\", updateWindow)\n updateWindow()\n\n return () => viewport.removeEventListener(\"scroll\", updateWindow)\n }, [documentId, thumbnailPlugin])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailPlugin) return\n\n const scope = thumbnailPlugin.provides().forDocument(documentId)\n const resizeObserver = new ResizeObserver(() => {\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n scope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n })\n\n resizeObserver.observe(viewport)\n\n return () => resizeObserver.disconnect()\n }, [documentId, thumbnailPlugin])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailPlugin) return\n\n const scope = thumbnailPlugin.provides().forDocument(documentId)\n setViewportMetrics({\n clientHeight: viewport.clientHeight,\n scrollTop: viewport.scrollTop,\n })\n scope.updateWindow(viewport.scrollTop, viewport.clientHeight)\n }, [documentId, thumbnailPlugin, windowState, thumbnailLayout])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !thumbnailPlugin || !windowState) return\n\n const scope = thumbnailPlugin.provides().forDocument(documentId)\n\n return scope.onScrollTo(({ top, behavior }) => {\n viewport.scrollTo({ top, behavior })\n })\n }, [documentId, thumbnailPlugin, Boolean(windowState)])\n\n return (\n <ScrollArea\n className=\"h-full w-full\"\n orientation=\"vertical\"\n scrollFade\n viewportClassName=\"px-4\"\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 </ScrollArea>\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, setViewportGap] = React.useState(0)\n\n React.useEffect(() => {\n if (!viewport) return\n\n setViewportGap(viewport.getViewportGap())\n }, [viewport])\n\n return (\n <ViewportElementContext.Provider value={viewportRef}>\n <ScrollArea\n className={className}\n orientation=\"both\"\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 </ScrollArea>\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\n const unsubscribe = scrollPlugin.onScrollerData(documentId, (layout) => {\n setLayoutData({ docId: documentId, layout })\n })\n\n return () => {\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 defaultThumbnailSidebarOpen: boolean\n downloadFileName?: 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 defaultThumbnailSidebarOpen,\n downloadFileName,\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(\n defaultThumbnailSidebarOpen\n )\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 [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 const basePageRotationsRef = React.useRef<Rotation[]>([])\n const basePageRotationsDocumentRef = 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 const emptyDeltas = new Map<number, Rotation>()\n pageRotationDeltasRef.current = emptyDeltas\n setPageRotationDeltas(emptyDeltas)\n const emptySelection = new Set<number>()\n selectedPageIndexesRef.current = emptySelection\n setSelectedPageIndexes(emptySelection)\n selectionAnchorPageIndexRef.current = null\n suppressActivePageSelectionSyncRef.current = null\n initializedSelectionDocumentRef.current = null\n basePageRotationsRef.current = []\n basePageRotationsDocumentRef.current = null\n }, [documentId])\n\n React.useEffect(() => {\n if (!pdfDocument || basePageRotationsDocumentRef.current === documentId) {\n return\n }\n\n basePageRotationsRef.current = pdfDocument.pages.map((page) =>\n normalizeRotation(page.rotation)\n )\n basePageRotationsDocumentRef.current = documentId\n }, [documentId, pdfDocument])\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 file: pdfFile,\n fileName: getPdfDownloadFileName(downloadFileName, pdfFile),\n pageRotationDeltas,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [downloadFileName, 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 basePageRotationsRef.current[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 pageRotationDeltasRef.current = nextDeltas\n setPageRotationDeltas(nextDeltas)\n\n const store = registry.getStore()\n\n store.dispatchToCore(refreshPages(documentId, targetPageIndexes))\n const viewport = viewportElementRef.current\n\n if (viewport && scrollDelta !== 0) {\n window.requestAnimationFrame(() => {\n viewport.scrollTop += scrollDelta\n })\n }\n ;(\n thumbnailPlugin as {\n calculateWindowState?: (documentId: string) => void\n } | null\n )?.calculateWindowState?.(documentId)\n },\n [\n activePage,\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 basePageRotationsRef.current[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 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 \"select-none selection:bg-transparent selection:text-inherit\",\n className\n )}\n >\n {showToolbar ? (\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={() => setSidebarOpen((open) => !open)}\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={scrollToPage}\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={() => rotateSelectedPages(-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={() => rotateSelectedPages(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 zoom?.requestZoom(nextZoom ?? ZOOM_OPTIONS[0])\n }}\n >\n <HugeiconsIcon\n icon={MinusSignCircleIcon}\n className=\"size-4\"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={String(currentZoomLevel)}\n onValueChange={(value) => zoom?.requestZoom(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 zoom?.requestZoom(\n nextZoom ?? ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n )\n }}\n >\n <HugeiconsIcon\n icon={PlusSignCircleIcon}\n className=\"size-4\"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n <PDFViewerSearchControl\n key={documentId}\n documentId={documentId}\n controlsDisabled={controlsDisabled}\n />\n {showDownload ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n <ToolbarTooltip label=\"Download PDF\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Download PDF\"\n disabled={downloadDisabled}\n onClick={handleDownload}\n >\n {isPreparingDownload ? (\n <Spinner className=\"size-4\" />\n ) : (\n <HugeiconsIcon\n icon={Download01Icon}\n className=\"size-4\"\n />\n )}\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n {showUpload ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n <ToolbarTooltip label=\"Upload PDF\">\n <PDFViewerUploadControl onUploadFile={handleUpload} />\n </ToolbarTooltip>\n </>\n ) : null}\n {toolbarActions ? (\n <>\n <Separator\n orientation=\"vertical\"\n className=\"mx-1 h-4 self-center\"\n />\n {toolbarActions}\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\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={basePageRotationsRef.current}\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={basePageRotationsRef.current}\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 showToolbar={innerProps.showToolbar}\n showUpload={innerProps.showUpload}\n sidebarOpen={innerProps.defaultThumbnailSidebarOpen}\n state={!pdfFile ? \"empty\" : documentFailed ? \"error\" : \"loading\"}\n onUploadFile={(file) => {\n innerProps.onUploadFile(file)\n innerProps.onPdfUpload?.(file)\n }}\n />\n )\n }\n\n return (\n <PDFViewerInner\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 file,\n className,\n defaultThumbnailSidebarOpen = false,\n defaultZoom = DEFAULT_ZOOM,\n pageWidth: _pageWidth,\n pageHeight: _pageHeight,\n downloadFileName,\n showDownload = true,\n showRotateControls = true,\n showToolbar = true,\n showUpload = true,\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 [pdfFile, setPdfFile] = React.useState(file ?? \"\")\n const [uploadedPdfUrl, setUploadedPdfUrl] = React.useState<string | null>(\n null\n )\n\n React.useEffect(() => {\n setPdfFile(file ?? \"\")\n }, [file])\n\n React.useEffect(\n () => () => {\n if (uploadedPdfUrl) URL.revokeObjectURL(uploadedPdfUrl)\n },\n [uploadedPdfUrl]\n )\n\n const handleUploadFile = React.useCallback((nextFile: File) => {\n const nextUrl = URL.createObjectURL(nextFile)\n\n setUploadedPdfUrl((previousUrl) => {\n if (previousUrl) URL.revokeObjectURL(previousUrl)\n return nextUrl\n })\n setPdfFile(nextUrl)\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 <div\n data-slot=\"pdf-viewer\"\n className={cn(\n \"grid h-full w-full place-items-center bg-background p-6 text-sm text-muted-foreground\",\n className\n )}\n >\n Unable to load the PDF engine.\n </div>\n )\n }\n\n if (!engine) {\n return (\n <div\n data-slot=\"pdf-viewer\"\n className={cn(\n \"relative flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background\",\n className\n )}\n >\n {showToolbar ? (\n <div className=\"min-h-12 border-b bg-background\" />\n ) : null}\n <div className=\"relative min-h-0 flex-1\">\n <PDFViewerLoadingSkeleton\n sidebarInline\n sidebarOpen={defaultThumbnailSidebarOpen}\n />\n </div>\n </div>\n )\n }\n\n return (\n <EmbedPDF engine={engine} plugins={plugins}>\n <PDFViewerDocumentLoader\n viewerRef={ref}\n pdfFile={pdfFile}\n defaultZoom={defaultZoom}\n className={className}\n defaultThumbnailSidebarOpen={defaultThumbnailSidebarOpen}\n downloadFileName={downloadFileName}\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 )\n }\n)\n"export function PdfViewerSourceCode() {return (diff --git a/apps/v4/components/ui/document-viewer-sidebar.tsx b/apps/v4/components/ui/document-viewer-sidebar.tsxindex 19ad193..a458bdd 100644--- a/apps/v4/components/ui/document-viewer-sidebar.tsx+++ b/apps/v4/components/ui/document-viewer-sidebar.tsx@@ -44,13 +44,17 @@ export function useInlineThumbnailSidebar(width: number) {export function DocumentViewerThumbnailSidebar({children,className,+ closedInlineClassName = "-ml-40",inline,open,+ widthClassName = "w-40",}: {children: React.ReactNodeclassName?: string+ closedInlineClassName?: stringinline: booleanopen: boolean+ widthClassName?: string}) {const [transitionsReady, setTransitionsReady] = React.useState(false)const shouldAnimateSidebar = transitionsReady && open@@ -75,7 +79,8 @@ export function DocumentViewerThumbnailSidebar({data-sidebar-mode={inline ? "inline" : "overlay"}data-sidebar-open={open ? "true" : "false"}className={cn(- "absolute inset-y-0 left-0 z-30 w-40 shrink-0 overflow-hidden border-r bg-sidebar shadow-lg",+ "absolute inset-y-0 left-0 z-30 shrink-0 overflow-hidden border-r bg-sidebar shadow-lg",+ widthClassName,shouldAnimateSidebar? "transition-[translate,margin-left,border-color] duration-200 ease-out": "transition-none",@@ -83,7 +88,7 @@ export function DocumentViewerThumbnailSidebar({open? "ml-0 translate-x-0": inline- ? "pointer-events-auto -ml-40 border-r-0"+ ? cn("pointer-events-auto border-r-0", closedInlineClassName): "pointer-events-none -translate-x-full border-r-0",className)}@@ -93,11 +98,17 @@ export function DocumentViewerThumbnailSidebar({)}-export function DocumentViewerSidebarSkeleton({ inline }: { inline: boolean }) {+export function DocumentViewerSidebarSkeleton({+ className,+ inline,+}: {+ className?: string+ inline: boolean+}) {if (!inline) return nullreturn (- <div className="w-40 shrink-0 border-r bg-sidebar p-4">+ <div className={cn("w-40 shrink-0 border-r bg-sidebar p-4", className)}><div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs"><div className="h-full animate-pulse bg-muted" /></div>diff --git a/apps/v4/components/ui/docx-viewer.tsx b/apps/v4/components/ui/docx-viewer.tsxindex 20e893d..cb41a27 100644--- a/apps/v4/components/ui/docx-viewer.tsx+++ b/apps/v4/components/ui/docx-viewer.tsx@@ -330,8 +330,8 @@ function DocxPageNumberControl({<Buttontype="button"variant="ghost"- size="xs"- className="mx-0.5 h-auto min-w-7 rounded-sm px-1.5 py-0 text-sm leading-normal font-normal text-primary sm:text-sm"+ size="sm"+ className="font-normal"aria-label={`Current page ${displayPage}. Edit page number`}disabled={controlsDisabled || !pageCount}onClick={() => setIsEditing(true)}@@ -666,6 +666,8 @@ function DocxViewerContent({}) {const fileInputRef = React.useRef<HTMLInputElement>(null)const viewportRef = React.useRef<HTMLDivElement | null>(null)+ const [viewportElement, setViewportElement] =+ React.useState<HTMLDivElement | null>(null)const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()const [uploadedDocxFile, setUploadedDocxFile] =React.useState<UploadedDocxFile | null>(null)@@ -740,6 +742,24 @@ function DocxViewerContent({const handlePageCountChange = React.useCallback((nextPageCount: number) => {setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))}, [])+ const setViewportRef = React.useCallback(+ (element: HTMLDivElement | null) => {+ viewportRef.current = element+ setViewportElement(element)+ },+ []+ )+ const pageVirtualization = React.useMemo(+ () => ({+ // Sidebar thumbnails can only paint from mounted page DOM,+ // so every page must mount while the sidebar is open;+ // otherwise let the viewer virtualize off-screen pages.+ enabled: !sidebarOpen,+ scrollElement: viewportElement,+ zoomScale: zoomScale / 100,+ }),+ [sidebarOpen, viewportElement, zoomScale]+ )const handleDownload = React.useCallback(async () => {if (isPreparingDownload) returnif (!uploadedDocxFile && !url) return@@ -985,7 +1005,7 @@ function DocxViewerContent({variant="ghost"size="sm"className={cn(- "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",+ "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none transition-none hover:bg-sidebar-accent",thumbnail.pageNumber === activePage &&"bg-sidebar-accent text-foreground",thumbnail.pageNumber !== activePage &&@@ -1021,7 +1041,7 @@ function DocxViewerContent({className={cn("min-h-0 flex-1", rounded && "rounded-b-lg")}style={{ backgroundColor: viewerBackgroundColor }}viewportClassName="p-4"- viewportRef={viewportRef}+ viewportRef={setViewportRef}>{!url && !uploadedDocxFile ? (<div className="grid h-full min-h-96 place-items-center p-6 text-center">@@ -1067,10 +1087,7 @@ function DocxViewerContent({loadingState={loadingState}pageBackgroundColor={effectiveIsDark ? "#0a0a0a" : undefined}pageGapBackgroundColor={viewerBackgroundColor}- // Sidebar thumbnails can only paint from mounted page DOM,- // so every page must mount while the sidebar is open;- // otherwise let the viewer virtualize off-screen pages.- pageVirtualization={{ enabled: !sidebarOpen }}+ pageVirtualization={pageVirtualization}deferInitialPaginationPaint={false}onPageCountChange={handlePageCountChange}/>diff --git a/apps/v4/components/ui/pdf-viewer.tsx b/apps/v4/components/ui/pdf-viewer.tsxindex ffe2dc6..ef81ed0 100644--- a/apps/v4/components/ui/pdf-viewer.tsx+++ b/apps/v4/components/ui/pdf-viewer.tsx@@ -1,7 +1,67 @@"use client"import * as React from "react"+import { createPluginRegistration, refreshPages } from "@embedpdf/core"+import { EmbedPDF, useRegistry } from "@embedpdf/core/react"+import type {+ PdfDocumentObject,+ PdfEngine,+ Rect,+ Rotation,+} from "@embedpdf/models"import {+ DocumentManagerPluginPackage,+ useActiveDocument,+ useDocumentManagerCapability,+} from "@embedpdf/plugin-document-manager/react"+import {+ GlobalPointerProvider,+ InteractionManagerPluginPackage,+ PagePointerProvider,+} from "@embedpdf/plugin-interaction-manager/react"+import { RenderLayer, RenderPluginPackage } from "@embedpdf/plugin-render/react"+import { Rotate, RotatePluginPackage } from "@embedpdf/plugin-rotate/react"+import {+ ScrollPluginPackage,+ ScrollStrategy,+ useScroll,+ useScrollPlugin,+ type PageLayout,+ type ScrollerLayout,+ type VirtualItem,+} from "@embedpdf/plugin-scroll/react"+import {+ SearchLayer,+ SearchPluginPackage,+ useSearch,+} from "@embedpdf/plugin-search/react"+import {+ CopyToClipboard,+ SelectionPluginPackage,+ useSelectionCapability,+ useSelectionPlugin,+} from "@embedpdf/plugin-selection/react"+import {+ ThumbImg,+ ThumbnailPluginPackage,+ useThumbnailCapability,+ useThumbnailPlugin,+ type ThumbMeta,+ type WindowState,+} from "@embedpdf/plugin-thumbnail/react"+import { TilingLayer, TilingPluginPackage } from "@embedpdf/plugin-tiling/react"+import {+ useIsViewportGated,+ useViewportCapability,+ useViewportElement,+ useViewportRef,+ ViewportElementContext,+ ViewportPluginPackage,+} from "@embedpdf/plugin-viewport/react"+import { useZoom, ZoomPluginPackage } from "@embedpdf/plugin-zoom/react"+import {+ ArrowDown01Icon,+ ArrowUp01Icon,Download01Icon,MinusSignCircleIcon,PlusSignCircleIcon,@@ -11,11 +71,6 @@ import {Upload01Icon,} from "@hugeicons/core-free-icons"import { HugeiconsIcon } from "@hugeicons/react"-import { useVirtualizer } from "@tanstack/react-virtual"-import type { PDFDocumentProxy } from "pdfjs-dist"-import type * as ReactPdf from "react-pdf"--import "react-pdf/dist/Page/TextLayer.css"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"@@ -25,7 +80,6 @@ import {useElementWidth,useInlineThumbnailSidebar,} from "@/components/ui/document-viewer-sidebar"-import { FileThumbnail } from "@/components/ui/file-thumbnail"import { Input } from "@/components/ui/input"import {Popover,@@ -48,15 +102,7 @@ import {TooltipProvider,TooltipTrigger,} from "@/components/ui/tooltip"--type ReactPdfModule = typeof ReactPdf-type PageRotationDeltas = Map<number, number>--type PDFPageMetrics = {- width: number- height: number- rotation: number-}+import { loadSharedPdfEngine } from "@/components/pdf-thumbnail-utils"export type PDFViewerPageOverlayProps = {pageNumber: number@@ -76,36 +122,15 @@ export type PDFViewerHandle = {getViewportElement: () => HTMLDivElement | null}-export type PDFViewerScrollDirection = "forward" | "backward" | "none"--export type PDFViewerVisiblePagesRange = {- activePage: number- endPage: number- isFastScrolling: boolean- numPages: number- pageRenderBuffer: number- scrollDirection: PDFViewerScrollDirection- startPage: number-}--export type PDFViewerRenderRange = {- endPage: number- startPage: number-}-export type PDFViewerProps = {file?: stringclassName?: string- documentOptions?: ReactPdf.DocumentProps["options"]defaultThumbnailSidebarOpen?: booleandefaultZoom?: number+ /** Retained for API compatibility; page sizes come from the document. */pageWidth?: number+ /** Retained for API compatibility; page sizes come from the document. */pageHeight?: number- pageNumbers?: number[]- pageRenderBuffer?: number- setRenderRange?: (- visiblePagesRange: PDFViewerVisiblePagesRange- ) => PDFViewerRenderRangedownloadFileName?: stringshowDownload?: booleanshowToolbar?: boolean@@ -135,29 +160,37 @@ export type PDFViewerProps = {) => void}-const DEFAULT_PAGE_WIDTH = 612-const DEFAULT_PAGE_HEIGHT = 792const DEFAULT_ZOOM = 1-const ZOOM_OPTIONS = [0.5, 0.75, 1, 1.25, 1.5, 2]-const MAX_DEVICE_PIXEL_RATIO = 2-const DEFAULT_PAGE_RENDER_BUFFER = 4-const FAST_SCROLL_VELOCITY_PX_PER_MS = 1-const SCROLL_IDLE_TIMEOUT_MS = 180-const PAGE_VIRTUALIZER_PADDING = 24-const PAGE_VIRTUALIZER_GAP = 24-const THUMBNAIL_VIRTUALIZER_PADDING = 16-const THUMBNAIL_ITEM_CHROME_HEIGHT = 48-const THUMBNAIL_ITEM_GAP = 12-const THUMBNAIL_WIDTH = 92-type SearchHighlight = {- id: string- left: number- top: number- width: number- height: number+const ZOOM_OPTIONS = [0.1, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2]+const PAGE_GAP = 24+const THUMBNAIL_PAGE_WIDTH = 92+const THUMBNAIL_IMAGE_PADDING = 8+const THUMBNAIL_WIDTH = THUMBNAIL_PAGE_WIDTH + THUMBNAIL_IMAGE_PADDING * 2+const THUMBNAIL_LABEL_HEIGHT = 24+const THUMBNAIL_GAP = 12+const THUMBNAIL_PANE_PADDING_Y = 16+const THUMBNAIL_SIDEBAR_WIDTH_CLASS = "w-40"+const THUMBNAIL_SIDEBAR_CLOSED_CLASS = "-ml-40"+const PAGE_BASE_RENDER_MAX_SCALE = 1+const PAGE_BASE_RENDER_DPR = 1+const TEXT_SELECTION_BACKGROUND = "rgba(59, 130, 246, 0.14)"++type PageRotationDeltas = Map<number, Rotation>+type ThumbnailSelectionMode = "replace" | "toggle" | "range"++function getPageIndexRange(from: number, to: number): Set<number> {+ const start = Math.min(from, to)+ const end = Math.max(from, to)+ const range = new Set<number>()++ for (let pageIndex = start; pageIndex <= end; pageIndex += 1) {+ range.add(pageIndex)+ }++ return range}-function areNumberSetsEqual(left: Set<number>, right: Set<number>) {+function arePageIndexSetsEqual(left: Set<number>, right: Set<number>) {if (left.size !== right.size) return falsefor (const value of left) {@@ -167,51 +200,40 @@ function areNumberSetsEqual(left: Set<number>, right: Set<number>) {return true}-function getPdfWorkerUrl(pdfjsVersion: string) {- return `//unpkg.com/pdfjs-dist@${pdfjsVersion}/legacy/build/pdf.worker.min.mjs`-}--function getPdfAssetBaseUrl(pdfjsVersion: string) {- return `https://unpkg.com/pdfjs-dist@${pdfjsVersion}`+function normalizeRotation(rotation: number): Rotation {+ return (((rotation % 4) + 4) % 4) as Rotation}-const defaultPdfDocumentOptionsByVersion = new Map<- string,- ReactPdf.DocumentProps["options"]->()+function useSharedPdfEngine() {+ const [engine, setEngine] = React.useState<PdfEngine | null>(null)+ const [error, setError] = React.useState<Error | null>(null)-function getDefaultPdfDocumentOptions(- pdfjsVersion: string-): ReactPdf.DocumentProps["options"] {- const cachedOptions = defaultPdfDocumentOptionsByVersion.get(pdfjsVersion)-- if (cachedOptions) return cachedOptions-- const assetBaseUrl = getPdfAssetBaseUrl(pdfjsVersion)-- const options = {- cMapPacked: true,- cMapUrl: `${assetBaseUrl}/cmaps/`,- standardFontDataUrl: `${assetBaseUrl}/standard_fonts/`,- }+ React.useEffect(() => {+ let cancelled = false- defaultPdfDocumentOptionsByVersion.set(pdfjsVersion, options)+ loadSharedPdfEngine().then(+ (loadedEngine) => {+ if (!cancelled) setEngine(loadedEngine)+ },+ (loadError: Error) => {+ if (!cancelled) setError(loadError)+ }+ )- return options-}+ return () => {+ cancelled = true+ }+ }, [])-function normalizeRotation(rotation: number) {- return (((Math.round(rotation / 90) * 90) % 360) + 360) % 360+ return { engine, error }}-function isQuarterTurn(rotation: number) {- return Math.abs(normalizeRotation(rotation) / 90) % 2 === 1+function rotationToDegrees(rotation: Rotation) {+ return (rotation as number) * 90}-function getPageDimensions(metrics: PDFPageMetrics, rotation: number) {- return isQuarterTurn(rotation)- ? { width: metrics.height, height: metrics.width }- : { width: metrics.width, height: metrics.height }+function normalizeDegrees(rotation: number) {+ return ((rotation % 360) + 360) % 360}function ensurePdfExtension(fileName: string) {@@ -248,20 +270,6 @@ function downloadBlob(blob: Blob, fileName: string) {window.setTimeout(() => URL.revokeObjectURL(url), 0)}-async function getPdfPageMetrics(- pdf: PDFDocumentProxy,- pageNumber: number-): Promise<PDFPageMetrics> {- const page = await pdf.getPage(pageNumber)- const viewport = page.getViewport({ scale: 1, rotation: 0 })-- return {- width: viewport.width,- height: viewport.height,- rotation: normalizeRotation(page.rotate),- }-}-async function downloadPdfWithPageRotations({file,fileName,@@ -277,31 +285,153 @@ async function downloadPdfWithPageRotations({throw new Error(`Failed to download PDF (${response.status})`)}+ if (pageRotationDeltas.size === 0) {+ downloadBlob(await response.blob(), fileName)+ return+ }+const [{ PDFDocument, degrees }, pdfBytes] = await Promise.all([import("pdf-lib"),response.arrayBuffer(),])const pdfDocument = await PDFDocument.load(pdfBytes)- pdfDocument.getPages().forEach((page, index) => {- const pageNumber = index + 1- const rotationDelta = pageRotationDeltas.get(pageNumber) ?? 0+ pdfDocument.getPages().forEach((page, pageIndex) => {+ const rotationDelta = pageRotationDeltas.get(pageIndex)if (!rotationDelta) returnpage.setRotation(- degrees(normalizeRotation(page.getRotation().angle + rotationDelta))+ degrees(+ normalizeDegrees(+ page.getRotation().angle + rotationToDegrees(rotationDelta)+ )+ ))})const nextPdfBytes = await pdfDocument.save()const nextPdfBuffer = new ArrayBuffer(nextPdfBytes.byteLength)new Uint8Array(nextPdfBuffer).set(nextPdfBytes)- const hasPageRotationChanges = pageRotationDeltas.size > 0downloadBlob(new Blob([nextPdfBuffer], { type: "application/pdf" }),- hasPageRotationChanges ? getRotatedPdfDownloadFileName(fileName) : fileName+ getRotatedPdfDownloadFileName(fileName)+ )+}++function getThumbnailMetaForPage({+ page,+ pageIndex,+ rotation,+ width,+ imagePadding,+ labelHeight,+ top,+}: {+ page: PdfDocumentObject["pages"][number]+ pageIndex: number+ rotation: Rotation+ width: number+ imagePadding: number+ labelHeight: number+ top: number+}): ThumbMeta {+ const innerWidth = Math.max(1, width - imagePadding * 2)+ const pageWidth = rotation % 2 === 1 ? page.size.height : page.size.width+ const pageHeight = rotation % 2 === 1 ? page.size.width : page.size.height+ const imageHeight = Math.round(innerWidth * (pageHeight / pageWidth))+ const wrapperHeight = imagePadding + imageHeight + imagePadding + labelHeight++ return {+ pageIndex,+ width: innerWidth,+ height: imageHeight,+ wrapperHeight,+ top,+ labelHeight,+ padding: imagePadding,+ }+}++function buildThumbnailLayout({+ basePageRotations,+ pageRotationDeltas,+ pdfDocument,+ width,+ gap,+ imagePadding,+ labelHeight,+ paddingY,+}: {+ basePageRotations: Rotation[]+ pageRotationDeltas: PageRotationDeltas+ pdfDocument: PdfDocumentObject | null+ width: number+ gap: number+ imagePadding: number+ labelHeight: number+ paddingY: number+}) {+ if (!pdfDocument) return null++ let top = paddingY+ const items = pdfDocument.pages.map((page, pageIndex) => {+ const basePageRotation =+ basePageRotations[pageIndex] ?? normalizeRotation(page.rotation)+ const pageRotation = normalizeRotation(+ basePageRotation + (pageRotationDeltas.get(pageIndex) ?? 0)+ )+ const meta = getThumbnailMetaForPage({+ page,+ pageIndex,+ rotation: pageRotation,+ width,+ imagePadding,+ labelHeight,+ top,+ })++ top += meta.wrapperHeight + gap+ return meta+ })++ return {+ items,+ totalHeight: items.length ? top - gap + paddingY : paddingY * 2,+ }+}++function getVisibleThumbnailItems({+ buffer,+ clientHeight,+ items,+ scrollTop,+}: {+ buffer: number+ clientHeight: number+ items: ThumbMeta[]+ scrollTop: number+}) {+ if (items.length === 0) return []+ if (clientHeight <= 0)+ return items.slice(0, Math.min(items.length, buffer * 2))++ const viewportBottom = scrollTop + clientHeight+ let start = items.findIndex(+ (item) => item.top + item.wrapperHeight >= scrollTop+ )++ if (start === -1) start = items.length - 1++ let end = start+ while (end < items.length && items[end].top <= viewportBottom) {+ end += 1+ }++ return items.slice(+ Math.max(0, start - buffer),+ Math.min(items.length, end + buffer))}@@ -315,7 +445,10 @@ function PDFViewerLoadingSkeleton({return (<div className="absolute inset-0 z-20 flex bg-muted/30">{sidebarOpen ? (- <DocumentViewerSidebarSkeleton inline={sidebarInline} />+ <DocumentViewerSidebarSkeleton+ className={THUMBNAIL_SIDEBAR_WIDTH_CLASS}+ inline={sidebarInline}+ />) : null}<div className="grid min-w-0 flex-1 place-items-center"><Spinner className="size-4" />@@ -324,6 +457,65 @@ function PDFViewerLoadingSkeleton({)}+// Rendered while the engine or document is not ready: same frame as the+// full viewer, with only the upload control usable.+function PDFViewerFallbackShell({+ className,+ showToolbar,+ showUpload,+ sidebarOpen,+ state,+ onUploadFile,+}: {+ className?: string+ showToolbar: boolean+ showUpload: boolean+ sidebarOpen: boolean+ state: "loading" | "error" | "empty"+ onUploadFile?: (file: File) => void+}) {+ return (+ <div+ data-slot="pdf-viewer"+ className={cn(+ "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",+ className+ )}+ >+ {showToolbar ? (+ <div className="flex min-h-12 flex-wrap items-center justify-end gap-2 border-b bg-background px-3 py-2">+ {showUpload && onUploadFile ? (+ <PDFViewerUploadControl onUploadFile={onUploadFile} />+ ) : null}+ </div>+ ) : null}+ <div className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30">+ {state === "loading" ? (+ <PDFViewerLoadingSkeleton sidebarInline sidebarOpen={sidebarOpen} />+ ) : null}+ {state === "error" ? (+ <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-sm text-muted-foreground">+ Unable to load the PDF preview.+ </div>+ ) : null}+ {state === "empty" ? (+ <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-center text-sm text-muted-foreground">+ <div className="max-w-sm space-y-3">+ <div className="font-medium text-foreground">+ Upload a PDF to preview+ </div>+ <div>+ Pass a PDF URL with the <code>file</code> prop or use the upload+ control.+ </div>+ </div>+ </div>+ ) : null}+ </div>+ </div>+ )+}+function ToolbarTooltip({label,children,@@ -341,40 +533,40 @@ function ToolbarTooltip({)}-function SearchInput({- value,- onValueChange,- onApply,- onClear,+function PDFViewerUploadControl({+ onUploadFile,}: {- value: string- onValueChange: (value: string) => void- onApply: () => void- onClear: () => void+ onUploadFile: (file: File) => void}) {+ const inputRef = React.useRef<HTMLInputElement>(null)+return (- <div className="space-y-3">- <Input- placeholder="Search text"- value={value}- onChange={(event: React.ChangeEvent<HTMLInputElement>) =>- onValueChange(event.target.value)- }- onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {- if (event.key === "Enter") {- onApply()+ <>+ <input+ ref={inputRef}+ type="file"+ accept="application/pdf,.pdf"+ className="sr-only"+ tabIndex={-1}+ onChange={(event) => {+ const nextFile = event.target.files?.[0]++ if (nextFile) {+ onUploadFile(nextFile)+ event.currentTarget.value = ""}}}/>- <div className="flex justify-end gap-2">- <Button type="button" variant="outline" size="sm" onClick={onClear}>- Clear- </Button>- <Button type="button" size="sm" onClick={onApply}>- Search- </Button>- </div>- </div>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Upload PDF"+ onClick={() => inputRef.current?.click()}+ >+ <HugeiconsIcon icon={Upload01Icon} className="size-4" />+ </Button>+ </>)}@@ -390,20 +582,21 @@ function PDFViewerPageNumberControl({onPageChange: (pageNumber: number) => void}) {const inputRef = React.useRef<HTMLInputElement>(null)+ const displayPage = numPages ? activePage : 1const [isEditing, setIsEditing] = React.useState(false)- const [draftPage, setDraftPage] = React.useState(() => String(activePage))+ const [draftPage, setDraftPage] = React.useState(() => String(displayPage))React.useEffect(() => {if (!isEditing) {- setDraftPage(String(activePage))+ setDraftPage(String(displayPage))}- }, [activePage, isEditing])+ }, [displayPage, isEditing])React.useEffect(() => {if (!isEditing) returninputRef.current?.focus()- inputRef.current?.select()+ inputRef.current?.setSelectionRange(draftPage.length, draftPage.length)}, [isEditing])const applyPageDraft = React.useCallback(@@ -416,9 +609,9 @@ function PDFViewerPageNumberControl({if (!Number.isInteger(parsedPage)) return- onPageChange(parsedPage)+ onPageChange(Math.min(Math.max(parsedPage, 1), Math.max(numPages, 1)))},- [onPageChange]+ [numPages, onPageChange])return (@@ -450,1696 +643,2001 @@ function PDFViewerPageNumberControl({<Buttontype="button"variant="ghost"- size="xs"- className="mx-0.5 h-auto min-w-7 rounded-sm px-1.5 py-0 text-sm leading-normal font-normal text-primary sm:text-sm"- aria-label={`Current page ${activePage}. Edit page number`}- disabled={controlsDisabled}- onClick={() => setIsEditing(true)}+ size="sm"+ className="font-normal"+ aria-label={`Current page ${displayPage}. Edit page number`}+ disabled={controlsDisabled || !numPages}+ onClick={() => {+ setDraftPage(String(displayPage))+ setIsEditing(true)+ }}>- {activePage}+ {displayPage}</Button>)}- <span>of {numPages || "-"}</span>+ <span>of {numPages || "–"}</span></div>)}-function PDFSidebarThumbnail({- pageMetrics,- pageNumber,- reactPdf,- rotation,- thumbnailAspectRatio,+function PDFViewerSearchControl({+ documentId,+ controlsDisabled,}: {- pageMetrics: PDFPageMetrics- pageNumber: number- reactPdf: ReactPdfModule- rotation: number- thumbnailAspectRatio: number+ documentId: string+ controlsDisabled: boolean}) {- const effectiveRotation = normalizeRotation(pageMetrics.rotation + rotation)-- return (- <FileThumbnail- file={{- name: `Page ${pageNumber}.pdf`,- type: "application/pdf",- }}- previewAspectRatio={thumbnailAspectRatio}- previewClassName="rounded-md bg-white"- previewContent={- <reactPdf.Thumbnail- pageNumber={pageNumber}- width={THUMBNAIL_WIDTH}- rotate={effectiveRotation}- className="flex size-full items-center justify-center [&_.react-pdf__Thumbnail__page]:!m-0 [&_.react-pdf__Thumbnail__page]:!h-auto [&_.react-pdf__Thumbnail__page]:!w-full [&_.react-pdf__Thumbnail__page]:overflow-hidden [&_canvas]:!h-auto [&_canvas]:!w-full"- />- }- className="w-[92px] rounded-md border-0 shadow-xs ring-0"- />+ const { state, provides } = useSearch(documentId)+ const { provides: scroll } = useScroll(documentId)+ const [searchDraft, setSearchDraft] = React.useState("")++ const scrollToResult = React.useCallback(+ (index: number) => {+ const result = state.results[index]++ if (!result || !scroll) return++ const firstRect = result.rects[0]++ scroll.scrollToPage({+ pageNumber: result.pageIndex + 1,+ ...(firstRect+ ? {+ pageCoordinates: {+ x: firstRect.origin.x,+ y: firstRect.origin.y,+ },+ alignY: 30,+ }+ : {}),+ behavior: "auto",+ })+ },+ [scroll, state.results])-}-function clampPageNumber(pageNumber: number, renderedPageNumbers: number[]) {- if (!renderedPageNumbers.length) return pageNumber+ const applySearch = React.useCallback(() => {+ const query = searchDraft.trim()- const minPage = Math.min(...renderedPageNumbers)- const maxPage = Math.max(...renderedPageNumbers)+ if (!provides) return- return Math.min(Math.max(pageNumber, minPage), maxPage)-}+ if (!query) {+ provides.stopSearch()+ return+ }-function normalizeRenderRange(- range: PDFViewerRenderRange,- renderedPageNumbers: number[]-) {- const startPage = clampPageNumber(- Math.min(range.startPage, range.endPage),- renderedPageNumbers- )- const endPage = clampPageNumber(- Math.max(range.startPage, range.endPage),- renderedPageNumbers+ provides.startSearch()+ provides.searchAllPages(query).wait(+ (result) => {+ const firstResult = result.results[0]++ if (firstResult && scroll) {+ provides.goToResult(0)+ const firstRect = firstResult.rects[0]++ scroll.scrollToPage({+ pageNumber: firstResult.pageIndex + 1,+ ...(firstRect+ ? {+ pageCoordinates: {+ x: firstRect.origin.x,+ y: firstRect.origin.y,+ },+ alignY: 30,+ }+ : {}),+ behavior: "auto",+ })+ }+ },+ () => undefined+ )+ }, [provides, scroll, searchDraft])++ const clearSearch = React.useCallback(() => {+ setSearchDraft("")+ provides?.stopSearch()+ }, [provides])++ const navigate = React.useCallback(+ (direction: 1 | -1) => {+ if (!provides || state.total === 0) return++ const index =+ direction === 1 ? provides.nextResult() : provides.previousResult()++ scrollToResult(index)+ },+ [provides, scrollToResult, state.total])- return { startPage, endPage }+ return (+ <Popover>+ <ToolbarTooltip label="Search text">+ <PopoverTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Search text"+ disabled={controlsDisabled}+ >+ <HugeiconsIcon icon={Search01Icon} className="size-4" />+ </Button>+ </PopoverTrigger>+ </ToolbarTooltip>+ <PopoverContent align="end" className="w-72">+ <div className="space-y-3">+ <Input+ placeholder="Search text"+ value={searchDraft}+ onChange={(event) => setSearchDraft(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ applySearch()+ }+ }}+ />+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-1">+ <ToolbarTooltip label="Previous match">+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Previous match"+ disabled={state.total === 0}+ onClick={() => navigate(-1)}+ >+ <HugeiconsIcon icon={ArrowUp01Icon} className="size-4" />+ </Button>+ </ToolbarTooltip>+ <ToolbarTooltip label="Next match">+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Next match"+ disabled={state.total === 0}+ onClick={() => navigate(1)}+ >+ <HugeiconsIcon icon={ArrowDown01Icon} className="size-4" />+ </Button>+ </ToolbarTooltip>+ {state.active && state.query ? (+ <span className="text-xs text-muted-foreground tabular-nums">+ {state.total === 0+ ? "No matches"+ : `${state.activeResultIndex + 1} of ${state.total}`}+ </span>+ ) : null}+ </div>+ <div className="flex gap-2">+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={clearSearch}+ >+ Clear+ </Button>+ <Button type="button" size="sm" onClick={applySearch}>+ Search+ </Button>+ </div>+ </div>+ </div>+ </PopoverContent>+ </Popover>+ )}-function getPageRenderPriority({+function PDFViewerThumbnails({+ basePageRotations,+ documentId,activePage,- pageNumber,- scrollDirection,+ pageCount,+ pageRotationDeltas,+ pdfDocument,+ selectedPageIndexes,+ onSelectPage,}: {+ basePageRotations: Rotation[]+ documentId: stringactivePage: number- pageNumber: number- scrollDirection: PDFViewerScrollDirection+ pageCount: number+ pageRotationDeltas: PageRotationDeltas+ pdfDocument: PdfDocumentObject | null+ selectedPageIndexes: Set<number>+ onSelectPage: (pageNumber: number, mode: ThumbnailSelectionMode) => void}) {- const distance = Math.abs(pageNumber - activePage)+ const thumbnailListboxId = React.useId()+ const activeDescendantId =+ activePage > 0 ? `${thumbnailListboxId}-page-${activePage}` : undefined++ const handleKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ if (pageCount < 1) return++ const currentPage = activePage > 0 ? activePage : 1+ let nextPage: number | null = null++ if (event.key === "ArrowDown") {+ nextPage = Math.min(pageCount, currentPage + 1)+ } else if (event.key === "ArrowUp") {+ nextPage = Math.max(1, currentPage - 1)+ } else if (event.key === "Home") {+ nextPage = 1+ } else if (event.key === "End") {+ nextPage = pageCount+ } else if (event.key === " ") {+ event.preventDefault()+ onSelectPage(currentPage, "toggle")+ return+ }- if (pageNumber === activePage) return -1000+ if (nextPage === null) return- if (scrollDirection === "forward") {- return pageNumber > activePage ? distance : distance + 1000- }+ event.preventDefault()+ onSelectPage(nextPage, event.shiftKey ? "range" : "replace")+ },+ [activePage, onSelectPage, pageCount]+ )- if (scrollDirection === "backward") {- return pageNumber < activePage ? distance : distance + 1000- }+ return (+ <PDFViewerThumbnailScrollArea+ activeDescendantId={activeDescendantId}+ basePageRotations={basePageRotations}+ documentId={documentId}+ onKeyDown={handleKeyDown}+ pageRotationDeltas={pageRotationDeltas}+ pdfDocument={pdfDocument}+ >+ {(meta: ThumbMeta) => {+ const pageNumber = meta.pageIndex + 1+ const isActive = pageNumber === activePage+ const isSelected = selectedPageIndexes.has(meta.pageIndex)+ const imagePadding = meta.padding ?? 0+ const pageRotationDelta = pageRotationDeltas.get(meta.pageIndex) ?? 0+ const thumbnailImageStyle: React.CSSProperties =+ pageRotationDelta % 2 === 1+ ? {+ height: meta.width,+ transform: `rotate(${rotationToDegrees(pageRotationDelta)}deg)`,+ width: meta.height,+ }+ : {+ height: meta.height,+ transform:+ pageRotationDelta === 0+ ? undefined+ : `rotate(${rotationToDegrees(pageRotationDelta)}deg)`,+ width: meta.width,+ }- return distance+ return (+ <div+ key={meta.pageIndex}+ data-pdf-viewer-thumbnail={pageNumber}+ className="absolute right-0 left-0 flex justify-center"+ style={{ top: meta.top, height: meta.wrapperHeight }}+ >+ <div+ id={`${thumbnailListboxId}-page-${pageNumber}`}+ role="option"+ data-pdf-viewer-thumbnail-option={pageNumber}+ aria-current={isActive ? "page" : undefined}+ aria-label={`Page ${pageNumber}`}+ aria-posinset={pageNumber}+ aria-selected={isSelected}+ aria-setsize={pageCount}+ data-selected={isSelected ? "" : undefined}+ className={cn(+ "flex h-full w-full cursor-default flex-col items-center justify-between rounded-md px-2 py-0 text-xs transition-none select-none hover:bg-sidebar-accent",+ isActive || isSelected+ ? "bg-sidebar-accent text-foreground"+ : "text-muted-foreground"+ )}+ onClick={(event) => {+ const mode = event.shiftKey+ ? "range"+ : event.metaKey || event.ctrlKey+ ? "toggle"+ : "replace"++ onSelectPage(pageNumber, mode)+ }}+ >+ <span+ className="mt-0 flex items-center justify-center overflow-hidden rounded-md bg-transparent"+ style={{+ width: meta.width + imagePadding * 2,+ height: meta.height + imagePadding * 2,+ padding: imagePadding,+ }}+ >+ <ThumbImg+ documentId={documentId}+ meta={meta}+ className="block rounded-sm object-contain"+ style={thumbnailImageStyle}+ />+ </span>+ <span+ className="flex items-center justify-center tabular-nums"+ style={{ height: meta.labelHeight }}+ >+ <span className="flex min-w-5 items-center justify-center px-1.5 text-center leading-5">+ {pageNumber}+ </span>+ </span>+ </div>+ </div>+ )+ }}+ </PDFViewerThumbnailScrollArea>+ )}-function PDFViewerPage({- devicePixelRatioLimit,- effectiveRotation,- reactPdf,- pageNumber,- pageStyle,- renderedPageWidth,- zoom,- shouldRenderPage,- searchQuery,- pageClassName,- renderPageOverlay,- onPageSettled,- onPagePointerDown,- onPagePointerMove,- onPagePointerUp,- onPagePointerCancel,+function PDFViewerThumbnailScrollArea({+ activeDescendantId,+ basePageRotations,+ children,+ documentId,+ onKeyDown,+ pageRotationDeltas,+ pdfDocument,}: {- devicePixelRatioLimit: number- effectiveRotation: number- reactPdf: ReactPdfModule- pageNumber: number- pageStyle: React.CSSProperties & { width: number; height: number }- renderedPageWidth: number- zoom: number- shouldRenderPage: boolean- searchQuery: string- pageClassName?: (pageNumber: number) => string | undefined- renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode- onPageSettled: (pageNumber: number, devicePixelRatioLimit: number) => void- onPagePointerDown?: (- event: React.PointerEvent<HTMLDivElement>,- pageNumber: number- ) => void- onPagePointerMove?: (- event: React.PointerEvent<HTMLDivElement>,- pageNumber: number- ) => void- onPagePointerUp?: (- event: React.PointerEvent<HTMLDivElement>,- pageNumber: number- ) => void- onPagePointerCancel?: (- event: React.PointerEvent<HTMLDivElement>,- pageNumber: number- ) => void+ activeDescendantId?: string+ basePageRotations: Rotation[]+ children: (meta: ThumbMeta) => React.ReactNode+ documentId: string+ onKeyDown: React.KeyboardEventHandler<HTMLDivElement>+ pageRotationDeltas: PageRotationDeltas+ pdfDocument: PdfDocumentObject | null}) {- const pageRef = React.useRef<HTMLDivElement>(null)- const [searchHighlights, setSearchHighlights] = React.useState<- SearchHighlight[]- >([])- const hasSearchQuery = Boolean(searchQuery.trim())- const clearSearchHighlights = React.useCallback(() => {- setSearchHighlights((currentHighlights) =>- currentHighlights.length ? [] : currentHighlights- )- }, [])+ const { plugin: thumbnailPlugin } = useThumbnailPlugin()+ const viewportRef = React.useRef<HTMLDivElement | null>(null)+ const [windowData, setWindowData] = React.useState<{+ docId: string | null+ window: WindowState | null+ }>({ docId: null, window: null })+ const [viewportMetrics, setViewportMetrics] = React.useState({+ clientHeight: 0,+ scrollTop: 0,+ })- const updateSearchHighlights = React.useCallback(() => {- const pageElement = pageRef.current- const query = searchQuery.trim().toLowerCase()+ const windowState = windowData.docId === documentId ? windowData.window : null+ const paddingY = thumbnailPlugin?.cfg.paddingY ?? 0+ const thumbnailLayout = React.useMemo(+ () =>+ buildThumbnailLayout({+ basePageRotations,+ pageRotationDeltas,+ pdfDocument,+ width: thumbnailPlugin?.cfg.width ?? THUMBNAIL_WIDTH,+ gap: thumbnailPlugin?.cfg.gap ?? THUMBNAIL_GAP,+ imagePadding: thumbnailPlugin?.cfg.imagePadding ?? 0,+ labelHeight: thumbnailPlugin?.cfg.labelHeight ?? THUMBNAIL_LABEL_HEIGHT,+ paddingY,+ }),+ [+ basePageRotations,+ pageRotationDeltas,+ pdfDocument,+ paddingY,+ thumbnailPlugin,+ ]+ )+ const effectiveWindowState = React.useMemo(() => {+ if (!thumbnailLayout) return windowState++ const items = getVisibleThumbnailItems({+ buffer: thumbnailPlugin?.cfg.buffer ?? 3,+ clientHeight: viewportMetrics.clientHeight,+ items: thumbnailLayout.items,+ scrollTop: viewportMetrics.scrollTop,+ })- if (!pageElement || !query) {- clearSearchHighlights()- return+ return {+ start: items[0]?.pageIndex ?? -1,+ end: items.at(-1)?.pageIndex ?? -1,+ items,+ totalHeight: thumbnailLayout.totalHeight,}+ }, [thumbnailLayout, thumbnailPlugin, viewportMetrics, windowState])- const textLayer = pageElement.querySelector<HTMLElement>(- ".react-pdf__Page__textContent"- )+ React.useEffect(() => {+ if (!thumbnailPlugin) return- if (!textLayer) {- clearSearchHighlights()- return+ const scope = thumbnailPlugin.provides().forDocument(documentId)+ const initialWindow = scope.getWindow()++ if (initialWindow) {+ setWindowData({ docId: documentId, window: initialWindow })}- const pageRect = pageElement.getBoundingClientRect()- const nextHighlights: SearchHighlight[] = []+ const unsubscribe = scope.onWindow((nextWindow) => {+ setWindowData({ docId: documentId, window: nextWindow })+ })- textLayer.querySelectorAll<HTMLElement>("span").forEach((span, index) => {- const textNode = Array.from(span.childNodes).find(- (node): node is Text => node.nodeType === Node.TEXT_NODE- )- const text = textNode?.textContent ?? ""- const normalizedText = text.toLowerCase()- let matchIndex = normalizedText.indexOf(query)-- while (textNode && matchIndex !== -1) {- const range = document.createRange()- range.setStart(textNode, matchIndex)- range.setEnd(textNode, matchIndex + query.length)-- Array.from(range.getClientRects()).forEach((rect, rectIndex) => {- if (rect.width <= 0 || rect.height <= 0) return-- nextHighlights.push({- id: `${pageNumber}-${index}-${matchIndex}-${rectIndex}`,- left: rect.left - pageRect.left,- top: rect.top - pageRect.top,- width: rect.width,- height: rect.height,- })- })+ return () => {+ unsubscribe()+ setWindowData({ docId: null, window: null })+ }+ }, [documentId, thumbnailPlugin])- range.detach()- matchIndex = normalizedText.indexOf(query, matchIndex + query.length)- }+ React.useEffect(() => {+ const viewport = viewportRef.current+ if (!viewport || !thumbnailPlugin) return++ const scope = thumbnailPlugin.provides().forDocument(documentId)+ const updateWindow = () => {+ setViewportMetrics({+ clientHeight: viewport.clientHeight,+ scrollTop: viewport.scrollTop,+ })+ scope.updateWindow(viewport.scrollTop, viewport.clientHeight)+ }++ viewport.addEventListener("scroll", updateWindow)+ updateWindow()++ return () => viewport.removeEventListener("scroll", updateWindow)+ }, [documentId, thumbnailPlugin])++ React.useEffect(() => {+ const viewport = viewportRef.current+ if (!viewport || !thumbnailPlugin) return++ const scope = thumbnailPlugin.provides().forDocument(documentId)+ const resizeObserver = new ResizeObserver(() => {+ setViewportMetrics({+ clientHeight: viewport.clientHeight,+ scrollTop: viewport.scrollTop,+ })+ scope.updateWindow(viewport.scrollTop, viewport.clientHeight)})- setSearchHighlights(nextHighlights)- }, [clearSearchHighlights, pageNumber, searchQuery])+ resizeObserver.observe(viewport)++ return () => resizeObserver.disconnect()+ }, [documentId, thumbnailPlugin])React.useEffect(() => {- if (!shouldRenderPage || !hasSearchQuery) {- clearSearchHighlights()- return- }+ const viewport = viewportRef.current+ if (!viewport || !thumbnailPlugin) return- const frame = window.requestAnimationFrame(updateSearchHighlights)- return () => window.cancelAnimationFrame(frame)- }, [- clearSearchHighlights,- hasSearchQuery,- shouldRenderPage,- updateSearchHighlights,- ])+ const scope = thumbnailPlugin.provides().forDocument(documentId)+ setViewportMetrics({+ clientHeight: viewport.clientHeight,+ scrollTop: viewport.scrollTop,+ })+ scope.updateWindow(viewport.scrollTop, viewport.clientHeight)+ }, [documentId, thumbnailPlugin, windowState, thumbnailLayout])++ React.useEffect(() => {+ const viewport = viewportRef.current+ if (!viewport || !thumbnailPlugin || !windowState) return++ const scope = thumbnailPlugin.provides().forDocument(documentId)++ return scope.onScrollTo(({ top, behavior }) => {+ viewport.scrollTo({ top, behavior })+ })+ }, [documentId, thumbnailPlugin, Boolean(windowState)])return (- <div- ref={pageRef}- data-pdf-viewer-page={pageNumber}- className={cn("relative", pageClassName?.(pageNumber))}- style={pageStyle}- onPointerDown={(event) => onPagePointerDown?.(event, pageNumber)}- onPointerMove={(event) => onPagePointerMove?.(event, pageNumber)}- onPointerUp={(event) => onPagePointerUp?.(event, pageNumber)}- onPointerCancel={(event) => onPagePointerCancel?.(event, pageNumber)}+ <ScrollArea+ className="h-full w-full"+ orientation="vertical"+ scrollFade+ viewportClassName="px-4"+ viewportProps={{+ "aria-activedescendant": activeDescendantId,+ "aria-label": "PDF pages",+ "aria-multiselectable": true,+ onKeyDown,+ onMouseDown: (event) => {+ event.currentTarget.focus({ preventScroll: true })+ },+ role: "listbox",+ style: {+ paddingBottom: paddingY,+ paddingTop: paddingY,+ },+ tabIndex: 0,+ }}+ viewportRef={viewportRef}>- {shouldRenderPage ? (- <>- <reactPdf.Page- pageNumber={pageNumber}- width={renderedPageWidth}- rotate={effectiveRotation}- className="overflow-hidden border bg-background shadow-xs"- renderAnnotationLayer={false}- renderTextLayer={hasSearchQuery}- devicePixelRatio={- typeof window === "undefined"- ? 1- : Math.min(devicePixelRatioLimit, window.devicePixelRatio || 1)- }- loading={- <div className="grid place-items-center" style={pageStyle}>- <Spinner className="size-4" />- </div>- }- onRenderSuccess={() =>- onPageSettled(pageNumber, devicePixelRatioLimit)- }- onRenderTextLayerSuccess={updateSearchHighlights}- onRenderError={() =>- onPageSettled(pageNumber, devicePixelRatioLimit)- }- />- {searchHighlights.length ? (- <div className="pointer-events-none absolute inset-0 z-10">- {searchHighlights.map((highlight) => (- <div- key={highlight.id}- className="absolute rounded-[2px] bg-yellow-300/45 mix-blend-multiply ring-1 ring-yellow-500/20 dark:bg-yellow-300/35"- style={{- left: highlight.left,- top: highlight.top,- width: highlight.width,- height: highlight.height,- }}- />- ))}- </div>- ) : null}- </>- ) : (- <div className="size-full border bg-white shadow-xs" />- )}- {renderPageOverlay?.({- pageNumber,- pageWidth: pageStyle.width,- pageHeight: pageStyle.height,- scale: zoom,- rotation: effectiveRotation,- })}- </div>+ <div+ className="relative"+ style={{ height: effectiveWindowState?.totalHeight ?? 0 }}+ >+ {effectiveWindowState?.items.map((meta) => children(meta))}+ </div>+ </ScrollArea>)}-export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(- function PDFViewer(- {- file,- className,- documentOptions,- defaultThumbnailSidebarOpen = false,- defaultZoom = DEFAULT_ZOOM,- pageWidth = DEFAULT_PAGE_WIDTH,- pageHeight = DEFAULT_PAGE_HEIGHT,- pageNumbers,- pageRenderBuffer = DEFAULT_PAGE_RENDER_BUFFER,- setRenderRange,- downloadFileName,- showDownload = true,- showRotateControls = true,- showToolbar = true,- showUpload = true,- toolbarActions,- pageClassName,- renderPageOverlay,- onActivePageChange,- onDocumentLoadSuccess,- onPdfUpload,- onPagePointerDown,- onPagePointerMove,- onPagePointerUp,- onPagePointerCancel,- },- ref- ) {- const [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null)- const [pdfDocument, setPdfDocument] =- React.useState<PDFDocumentProxy | null>(null)- const [pdfFile, setPdfFile] = React.useState(file ?? "")- const [uploadedPdfUrl, setUploadedPdfUrl] = React.useState<string | null>(- null- )- const [numPages, setNumPages] = React.useState(0)- const [activePage, setActivePage] = React.useState(1)- const [zoom, setZoom] = React.useState(defaultZoom)- const [pageRotationDeltas, setPageRotationDeltas] =- React.useState<PageRotationDeltas>(() => new Map())- const [pageMetrics, setPageMetrics] = React.useState<- Map<number, PDFPageMetrics>- >(() => new Map())- const [sidebarOpen, setSidebarOpen] = React.useState(- defaultThumbnailSidebarOpen- )- const [searchDraft, setSearchDraft] = React.useState("")- const [searchQuery, setSearchQuery] = React.useState("")- const [isDocumentLoading, setIsDocumentLoading] = React.useState(true)- const [isFirstPageRendering, setIsFirstPageRendering] = React.useState(true)- const [settledPageNumbers, setSettledPageNumbers] = React.useState<- Set<number>- >(() => new Set())- const [lowResolutionPageNumbers, setLowResolutionPageNumbers] =- React.useState<Set<number>>(() => new Set())- const [visiblePageNumbers, setVisiblePageNumbers] = React.useState<- Set<number>- >(() => new Set([1]))- const [scrollState, setScrollState] = React.useState<{- direction: PDFViewerScrollDirection- isFastScrolling: boolean- }>({ direction: "none", isFastScrolling: false })- const [loadError, setLoadError] = React.useState(false)- const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)- const viewportRef = React.useRef<HTMLDivElement>(null)- const thumbnailViewportRef = React.useRef<HTMLDivElement>(null)- const wasThumbnailSidebarVisibleRef = React.useRef(false)- const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()- const thumbnailClickScrollYRef = React.useRef<number | null>(null)- const pendingPageMetricsRef = React.useRef<Set<number>>(new Set())- const pageMetricsGenerationRef = React.useRef(0)- const scrollTrackerRef = React.useRef({- scrollTop: 0,- timestamp: 0,- })-- React.useEffect(() => {- setPdfFile(file ?? "")- setLoadError(false)- setIsDocumentLoading(Boolean(file))- setIsFirstPageRendering(Boolean(file))- setSettledPageNumbers(new Set())- setPdfDocument(null)- pendingPageMetricsRef.current.clear()- pageMetricsGenerationRef.current += 1- setNumPages(0)- setActivePage(1)- setPageMetrics(new Map())- setPageRotationDeltas(new Map())- setLowResolutionPageNumbers(new Set())- setVisiblePageNumbers(new Set([1]))- setScrollState({ direction: "none", isFastScrolling: false })- }, [file])-- React.useEffect(() => {- let mounted = true+function PDFViewerScrollAreaViewport({+ children,+ className,+ documentId,+}: {+ children: React.ReactNode+ className?: string+ documentId: string+}) {+ const viewportRef = useViewportRef(documentId)+ const { provides: viewport } = useViewportCapability()+ const isGated = useIsViewportGated(documentId)+ const [viewportGap, setViewportGap] = React.useState(0)- void import("react-pdf")- .then((module) => {- module.pdfjs.GlobalWorkerOptions.workerSrc = getPdfWorkerUrl(- module.pdfjs.version- )+ React.useEffect(() => {+ if (!viewport) return- if (mounted) {- setReactPdf(module)- }- })- .catch(() => {- if (mounted) {- setLoadError(true)- setIsDocumentLoading(false)- setIsFirstPageRendering(false)- }- })+ setViewportGap(viewport.getViewportGap())+ }, [viewport])- return () => {- mounted = false- }- }, [])+ return (+ <ViewportElementContext.Provider value={viewportRef}>+ <ScrollArea+ className={className}+ orientation="both"+ viewportClassName="relative select-none selection:bg-transparent selection:text-inherit"+ viewportProps={{+ style: {+ padding: viewportGap,+ },+ }}+ viewportRef={viewportRef}+ >+ {isGated ? null : children}+ </ScrollArea>+ </ViewportElementContext.Provider>+ )+}- React.useEffect(() => {- return () => {- if (uploadedPdfUrl) {- URL.revokeObjectURL(uploadedPdfUrl)- }- }- }, [uploadedPdfUrl])+// Captures the scrollable viewport element so the imperative handle can expose+// it.+function PDFViewerViewportBridge({+ viewportElementRef,+}: {+ viewportElementRef: React.MutableRefObject<HTMLDivElement | null>+}) {+ const elementRef = useViewportElement()- const renderedPageNumbers = React.useMemo(() => {- if (pageNumbers?.length) return pageNumbers+ React.useEffect(() => {+ viewportElementRef.current = elementRef?.current ?? null+ })- return Array.from({ length: numPages || 1 }, (_, index) => index + 1)- }, [numPages, pageNumbers])+ return null+}- const firstRenderedPage = renderedPageNumbers[0] ?? 1- const defaultPageMetrics = React.useMemo<PDFPageMetrics>(- () => ({ width: pageWidth, height: pageHeight, rotation: 0 }),- [pageHeight, pageWidth]- )- const getPageMetrics = React.useCallback(- (pageNumber: number) => pageMetrics.get(pageNumber) ?? defaultPageMetrics,- [defaultPageMetrics, pageMetrics]- )- const getEstimatedPageSize = React.useCallback(- (index: number) => {- const pageNumber = renderedPageNumbers[index] ?? firstRenderedPage- const metrics = getPageMetrics(pageNumber)- const rotationDelta = pageRotationDeltas.get(pageNumber) ?? 0- const effectiveRotation = normalizeRotation(- metrics.rotation + rotationDelta- )- const dimensions = getPageDimensions(metrics, effectiveRotation)+function PDFViewerTextSelectionLayer({+ documentId,+ pageIndex,+ scale,+}: {+ documentId: string+ pageIndex: number+ scale: number+}) {+ const { plugin: selectionPlugin } = useSelectionPlugin()+ const [rects, setRects] = React.useState<Rect[]>([])- return dimensions.height * zoom + PAGE_VIRTUALIZER_GAP- },- [- firstRenderedPage,- getPageMetrics,- pageRotationDeltas,- renderedPageNumbers,- zoom,- ]- )- const getEstimatedPageWidth = React.useCallback(- (pageNumber: number) => {- const metrics = getPageMetrics(pageNumber)- const rotationDelta = pageRotationDeltas.get(pageNumber) ?? 0- const effectiveRotation = normalizeRotation(- metrics.rotation + rotationDelta- )- const dimensions = getPageDimensions(metrics, effectiveRotation)+ React.useEffect(() => {+ if (!selectionPlugin) return- return dimensions.width * zoom+ return selectionPlugin.registerSelectionOnPage({+ documentId,+ pageIndex,+ onRectsChange: ({ rects: nextRects }) => {+ setRects(nextRects)},- [getPageMetrics, pageRotationDeltas, zoom]- )- const pageVirtualizer = useVirtualizer({- count: renderedPageNumbers.length,- estimateSize: getEstimatedPageSize,- getItemKey: (index) => renderedPageNumbers[index] ?? index,- getScrollElement: () => viewportRef.current,- overscan: scrollState.isFastScrolling ? 14 : 8,- paddingEnd: PAGE_VIRTUALIZER_PADDING,- paddingStart: PAGE_VIRTUALIZER_PADDING,- scrollPaddingStart: PAGE_VIRTUALIZER_PADDING,})- const virtualPageItems = pageVirtualizer.getVirtualItems()- const virtualPageNumbers = React.useMemo(- () =>- virtualPageItems.flatMap((virtualPage) => {- const pageNumber = renderedPageNumbers[virtualPage.index]-- return pageNumber ? [pageNumber] : []- }),- [renderedPageNumbers, virtualPageItems]- )- const virtualPageNumbersKey = virtualPageNumbers.join(",")- const virtualPageNumberSet = React.useMemo(- () =>- new Set(- virtualPageNumbersKey- ? virtualPageNumbersKey- .split(",")- .map((pageNumber) => Number(pageNumber))- : []- ),- [virtualPageNumbersKey]- )- const maxEstimatedPageWidth = React.useMemo(() => {- if (!renderedPageNumbers.length) return pageWidth * zoom-- return renderedPageNumbers.reduce(- (maxWidth, pageNumber) =>- Math.max(maxWidth, getEstimatedPageWidth(pageNumber)),- 0- )- }, [getEstimatedPageWidth, pageWidth, renderedPageNumbers, zoom])- const activePageIndex = React.useMemo(- () => renderedPageNumbers.indexOf(activePage),- [activePage, renderedPageNumbers]- )- const loadPageMetrics = React.useCallback(- async (pageNumbersToLoad: number[]) => {- const pdf = pdfDocument-- if (!pdf) return-- const generation = pageMetricsGenerationRef.current- const uniquePageNumbers = Array.from(new Set(pageNumbersToLoad)).filter(- (pageNumber) =>- pageNumber >= 1 &&- pageNumber <= pdf.numPages &&- !pageMetrics.has(pageNumber) &&- !pendingPageMetricsRef.current.has(pageNumber)- )-- if (!uniquePageNumbers.length) return-- uniquePageNumbers.forEach((pageNumber) => {- pendingPageMetricsRef.current.add(pageNumber)- })-- const pageMetricEntries = await Promise.all(- uniquePageNumbers.map(async (pageNumber) => {- try {- return [- pageNumber,- await getPdfPageMetrics(pdf, pageNumber),- ] as const- } catch {- return null- }- })- )-- uniquePageNumbers.forEach((pageNumber) => {- pendingPageMetricsRef.current.delete(pageNumber)- })-- if (generation !== pageMetricsGenerationRef.current) return+ }, [documentId, pageIndex, selectionPlugin])- const resolvedPageMetricEntries = pageMetricEntries.filter(- (entry): entry is readonly [number, PDFPageMetrics] => Boolean(entry)- )-- if (!resolvedPageMetricEntries.length) return+ if (!rects.length) return null- setPageMetrics((currentMetrics) => {- const nextMetrics = new Map(currentMetrics)- let changed = false+ return (+ <>+ {rects.map((rect, index) => (+ <div+ key={`${index}-${rect.origin.x}-${rect.origin.y}`}+ className="pointer-events-none absolute"+ style={{+ background: TEXT_SELECTION_BACKGROUND,+ height: rect.size.height * scale,+ left: rect.origin.x * scale,+ top: rect.origin.y * scale,+ width: rect.size.width * scale,+ }}+ />+ ))}+ </>+ )+}- resolvedPageMetricEntries.forEach(([pageNumber, metrics]) => {- if (nextMetrics.has(pageNumber)) return- nextMetrics.set(pageNumber, metrics)- changed = true- })+function PDFViewerSelectionReleaseGuard({+ documentId,+}: {+ documentId: string+}) {+ const { plugin: selectionPlugin } = useSelectionPlugin()+ const { provides: selection } = useSelectionCapability()+ const lastSelectionModeIdRef = React.useRef<string | null>(null)- return changed ? nextMetrics : currentMetrics- })- },- [pageMetrics, pdfDocument]- )- const resolvedDownloadFileName = React.useMemo(- () => getPdfDownloadFileName(downloadFileName, pdfFile),- [downloadFileName, pdfFile]- )- const pdfjsVersion = reactPdf?.pdfjs.version- const defaultDocumentOptions = React.useMemo(- () =>- pdfjsVersion ? getDefaultPdfDocumentOptions(pdfjsVersion) : undefined,- [pdfjsVersion]- )- const resolvedDocumentOptions = documentOptions ?? defaultDocumentOptions- const hasPdfFile = Boolean(pdfFile)- const controlsDisabled = !hasPdfFile || !reactPdf || !numPages- const downloadDisabled = controlsDisabled || isPreparingDownload- const isLoading =- hasPdfFile && (!reactPdf || isDocumentLoading || isFirstPageRendering)- const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)- const thumbnailSidebarVisible = Boolean(- sidebarOpen && !isLoading && !loadError- )- const normalizedPageRenderBuffer = Math.max(0, Math.floor(pageRenderBuffer))- const getEstimatedThumbnailItemSize = React.useCallback(- (index: number) => {- const pageNumber = renderedPageNumbers[index] ?? firstRenderedPage- const metrics = getPageMetrics(pageNumber)- const rotationDelta = pageRotationDeltas.get(pageNumber) ?? 0- const effectiveRotation = normalizeRotation(- metrics.rotation + rotationDelta- )- const dimensions = getPageDimensions(metrics, effectiveRotation)- const thumbnailAspectRatio = dimensions.width / dimensions.height+ React.useEffect(() => {+ if (!selection) return- return (- THUMBNAIL_WIDTH / thumbnailAspectRatio +- THUMBNAIL_ITEM_CHROME_HEIGHT +- THUMBNAIL_ITEM_GAP- )- },- [- firstRenderedPage,- getPageMetrics,- pageRotationDeltas,- renderedPageNumbers,- ]- )- const thumbnailVirtualizer = useVirtualizer({- count: thumbnailSidebarVisible ? renderedPageNumbers.length : 0,- estimateSize: getEstimatedThumbnailItemSize,- getItemKey: (index) => renderedPageNumbers[index] ?? index,- getScrollElement: () => thumbnailViewportRef.current,- overscan: 10,- paddingEnd: THUMBNAIL_VIRTUALIZER_PADDING,- paddingStart: THUMBNAIL_VIRTUALIZER_PADDING,- scrollPaddingStart: THUMBNAIL_VIRTUALIZER_PADDING,+ return selection.forDocument(documentId).onBeginSelection(({ modeId }) => {+ lastSelectionModeIdRef.current = modeId})+ }, [documentId, selection])- const renderRange = React.useMemo(() => {- if (!renderedPageNumbers.length) {- return { startPage: 1, endPage: 1 }- }+ React.useEffect(() => {+ if (!selection) return- const slowTrailingBuffer =- scrollState.direction === "none"- ? 0- : Math.min(2, normalizedPageRenderBuffer)- const fastAheadBuffer = Math.max(normalizedPageRenderBuffer + 6, 8)- const fastBehindBuffer = Math.min(1, normalizedPageRenderBuffer)- const beforeBuffer = scrollState.isFastScrolling- ? scrollState.direction === "backward"- ? fastAheadBuffer- : fastBehindBuffer- : normalizedPageRenderBuffer +- (scrollState.direction === "backward" ? slowTrailingBuffer : 0)- const afterBuffer = scrollState.isFastScrolling- ? scrollState.direction === "forward"- ? fastAheadBuffer- : fastBehindBuffer- : normalizedPageRenderBuffer +- (scrollState.direction === "forward" ? slowTrailingBuffer : 0)- const defaultRange = normalizeRenderRange(- {- startPage: activePage - beforeBuffer,- endPage: activePage + afterBuffer,- },- renderedPageNumbers- )- const customRange = setRenderRange?.({- ...defaultRange,- activePage,- isFastScrolling: scrollState.isFastScrolling,- numPages,- pageRenderBuffer: normalizedPageRenderBuffer,- scrollDirection: scrollState.direction,- })+ let cleanupFrame = 0+ const finalizeIfStillSelecting = () => {+ window.cancelAnimationFrame(cleanupFrame)+ cleanupFrame = window.requestAnimationFrame(() => {+ const selectionState = selection.getState(documentId)- return normalizeRenderRange(- customRange ?? defaultRange,- renderedPageNumbers- )- }, [- activePage,- normalizedPageRenderBuffer,- numPages,- renderedPageNumbers,- scrollState.direction,- scrollState.isFastScrolling,- setRenderRange,- ])+ if (!selectionState.selecting) return- React.useEffect(() => {- if (lowResolutionPageNumbers.size === 0) {- return- }+ if (selectionState.selection && selectionPlugin) {+ const pluginWithEndSelection = selectionPlugin as unknown as {+ endSelection?: (documentId: string, modeId: string) => void+ }- let hasStalePageNumber = false+ pluginWithEndSelection.endSelection?.(+ documentId,+ lastSelectionModeIdRef.current ?? "pointerMode"+ )+ return+ }- lowResolutionPageNumbers.forEach((pageNumber) => {- if (!virtualPageNumberSet.has(pageNumber)) {- hasStalePageNumber = true+ if (!selectionState.selection) {+ selection.clear(documentId)}})+ }- if (!hasStalePageNumber) {- return- }-- setLowResolutionPageNumbers((currentPageNumbers) => {- let changed = false- const nextPageNumbers = new Set(currentPageNumbers)+ window.addEventListener("pointerup", finalizeIfStillSelecting)+ window.addEventListener("pointercancel", finalizeIfStillSelecting)+ window.addEventListener("blur", finalizeIfStillSelecting)- currentPageNumbers.forEach((pageNumber) => {- if (!virtualPageNumberSet.has(pageNumber)) {- nextPageNumbers.delete(pageNumber)- changed = true- }- })+ return () => {+ window.cancelAnimationFrame(cleanupFrame)+ window.removeEventListener("pointerup", finalizeIfStillSelecting)+ window.removeEventListener("pointercancel", finalizeIfStillSelecting)+ window.removeEventListener("blur", finalizeIfStillSelecting)+ }+ }, [documentId, selection, selectionPlugin])- return changed ? nextPageNumbers : currentPageNumbers- })- }, [lowResolutionPageNumbers, virtualPageNumberSet])+ return null+}- const queuedPageNumbers = React.useMemo(() => {- if (renderedPageNumbers.length <= 3) {- return new Set(renderedPageNumbers)- }+function isEditableCopyTarget(target: EventTarget | null) {+ if (!(target instanceof HTMLElement)) return false- const maxUnsettledPages = scrollState.isFastScrolling ? 4 : 8- const visibleUnsettledCandidates = virtualPageNumbers.filter(- (pageNumber) =>- visiblePageNumbers.has(pageNumber) &&- !settledPageNumbers.has(pageNumber)- )- const unsettledCandidates = virtualPageNumbers- .filter(- (pageNumber) =>- pageNumber >= renderRange.startPage &&- pageNumber <= renderRange.endPage &&- !visiblePageNumbers.has(pageNumber) &&- !settledPageNumbers.has(pageNumber)- )- .sort(- (leftPage, rightPage) =>- getPageRenderPriority({- activePage,- pageNumber: leftPage,- scrollDirection: scrollState.direction,- }) -- getPageRenderPriority({- activePage,- pageNumber: rightPage,- scrollDirection: scrollState.direction,- })- )+ if (target.isContentEditable) return true- return new Set(- [...visibleUnsettledCandidates, ...unsettledCandidates].slice(- 0,- maxUnsettledPages- )- )- }, [- activePage,- renderRange.endPage,- renderRange.startPage,- renderedPageNumbers,- scrollState.direction,- scrollState.isFastScrolling,- settledPageNumbers,- visiblePageNumbers,- virtualPageNumbers,- ])+ return Boolean(target.closest("input, textarea, [contenteditable='true']"))+}- const pageNumbersForMetrics = React.useMemo(() => {- const nextPageNumbers = new Set<number>([- firstRenderedPage,- activePage,- ...visiblePageNumbers,- ...virtualPageNumbers,- ])-- renderedPageNumbers.forEach((pageNumber) => {- if (- pageNumber >= renderRange.startPage &&- pageNumber <= renderRange.endPage- ) {- nextPageNumbers.add(pageNumber)- }- })+function PDFViewerSelectionCopyShortcut({+ documentId,+}: {+ documentId: string+}) {+ const { provides: selection } = useSelectionCapability()- return Array.from(nextPageNumbers)- }, [- activePage,- firstRenderedPage,- renderRange.endPage,- renderRange.startPage,- renderedPageNumbers,- visiblePageNumbers,- virtualPageNumbers,- ])+ React.useEffect(() => {+ if (!selection) return- React.useEffect(() => {- void loadPageMetrics(pageNumbersForMetrics)- }, [loadPageMetrics, pageNumbersForMetrics])-- const updateActivePageFromViewport = React.useCallback(() => {- const viewport = viewportRef.current- if (!viewport || !renderedPageNumbers.length) return-- const viewportRect = viewport.getBoundingClientRect()- const viewportCenter = viewportRect.top + viewportRect.height / 2- const nextVisiblePageNumbers = new Set<number>()- let closestPage = renderedPageNumbers[0] ?? 1- let closestDistance = Number.POSITIVE_INFINITY-- viewport- .querySelectorAll<HTMLElement>("[data-pdf-viewer-page]")- .forEach((pageElement) => {- const pageNumber = Number(pageElement.dataset.pdfViewerPage)-- if (!pageNumber) return-- const pageRect = pageElement.getBoundingClientRect()- const pageCenter = pageRect.top + pageRect.height / 2- const distance = Math.abs(pageCenter - viewportCenter)-- if (- pageRect.bottom > viewportRect.top &&- pageRect.top < viewportRect.bottom- ) {- nextVisiblePageNumbers.add(pageNumber)- }+ const copySelectedPdfText = (event: Event) => {+ if (isEditableCopyTarget(event.target)) return+ if (!selection.getState(documentId).selection) return- if (distance < closestDistance) {- closestDistance = distance- closestPage = pageNumber- }- })+ event.preventDefault()+ selection.copyToClipboard(documentId)+ }- if (!nextVisiblePageNumbers.size) {- nextVisiblePageNumbers.add(closestPage)- }+ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.key.toLowerCase() !== "c") return+ if (!event.metaKey && !event.ctrlKey) return- setActivePage((currentPage) => {- if (currentPage === closestPage) return currentPage- onActivePageChange?.(closestPage)- return closestPage- })+ copySelectedPdfText(event)+ }- setVisiblePageNumbers((currentPageNumbers) =>- areNumberSetsEqual(currentPageNumbers, nextVisiblePageNumbers)- ? currentPageNumbers- : nextVisiblePageNumbers- )- }, [onActivePageChange, renderedPageNumbers])+ document.addEventListener("copy", copySelectedPdfText)+ document.addEventListener("keydown", handleKeyDown)- React.useEffect(() => {- const frameId = window.requestAnimationFrame(updateActivePageFromViewport)+ return () => {+ document.removeEventListener("copy", copySelectedPdfText)+ document.removeEventListener("keydown", handleKeyDown)+ }+ }, [documentId, selection])- return () => window.cancelAnimationFrame(frameId)- }, [updateActivePageFromViewport, virtualPageNumbersKey])+ return null+}- React.useEffect(() => {- const viewport = viewportRef.current- if (!viewport || !numPages) return-- let frameId = 0- let idleTimeoutId = 0- const handleScroll = () => {- const currentScrollTop = viewport.scrollTop- const currentTimestamp = performance.now()- const previous = scrollTrackerRef.current- const delta = currentScrollTop - previous.scrollTop- const elapsed = Math.max(1, currentTimestamp - previous.timestamp)- const speed = Math.abs(delta) / elapsed- const direction: PDFViewerScrollDirection =- delta > 0 ? "forward" : delta < 0 ? "backward" : "none"- const isFastScrolling = speed >= FAST_SCROLL_VELOCITY_PX_PER_MS-- scrollTrackerRef.current = {- scrollTop: currentScrollTop,- timestamp: currentTimestamp,- }+function isQuarterTurn(rotation: Rotation) {+ return rotation % 2 === 1+}- if (direction !== "none") {- setScrollState((currentState) =>- currentState.direction === direction &&- currentState.isFastScrolling === isFastScrolling- ? currentState- : { direction, isFastScrolling }- )- }+function getRotatedDimensions({+ height,+ rotation,+ width,+}: {+ height: number+ rotation: Rotation+ width: number+}) {+ return isQuarterTurn(rotation)+ ? { height: width, width: height }+ : { height, width }+}- window.clearTimeout(idleTimeoutId)- idleTimeoutId = window.setTimeout(() => {- setScrollState((currentState) =>- currentState.direction === "none" && !currentState.isFastScrolling- ? currentState- : { direction: "none", isFastScrolling: false }- )- }, SCROLL_IDLE_TIMEOUT_MS)+function getRotatedPageDimensions(page: PageLayout, rotation: Rotation) {+ return getRotatedDimensions({+ height: page.height,+ rotation,+ width: page.width,+ })+}- window.cancelAnimationFrame(frameId)- frameId = window.requestAnimationFrame(updateActivePageFromViewport)+function applyPageRotationDeltasToScrollerLayout({+ basePageRotations,+ layout,+ pageRotationDeltas,+}: {+ basePageRotations: Rotation[]+ layout: ScrollerLayout+ pageRotationDeltas: PageRotationDeltas+}): ScrollerLayout {+ if (pageRotationDeltas.size === 0) return layout++ let maxWidth = 0+ let maxHeight = 0+ let offset = 0+ const pageGap = layout.pageGap+ let startSpacingAdjustment = 0+ const items: VirtualItem[] = layout.items.map((item, itemIndex) => {+ let pageOffset = 0+ let itemWidth = 0+ let itemHeight = 0+ const pageLayouts = item.pageLayouts.map((page) => {+ const basePageRotation =+ basePageRotations[page.pageIndex] ?? normalizeRotation(0)+ const pageRotation = normalizeRotation(+ basePageRotation + (pageRotationDeltas.get(page.pageIndex) ?? 0)+ )+ const rotatedSize = getRotatedPageDimensions(page, pageRotation)+ const oldScrollAxisSize =+ layout.strategy === ScrollStrategy.Horizontal+ ? page.rotatedWidth+ : page.rotatedHeight+ const newScrollAxisSize =+ layout.strategy === ScrollStrategy.Horizontal+ ? rotatedSize.width+ : rotatedSize.height++ if (+ layout.startSpacing === 0 &&+ itemIndex === 0 &&+ pageOffset === 0 &&+ newScrollAxisSize < oldScrollAxisSize+ ) {+ startSpacingAdjustment = Math.max(+ startSpacingAdjustment,+ (oldScrollAxisSize - newScrollAxisSize) / 2+ )}- scrollTrackerRef.current = {- scrollTop: viewport.scrollTop,- timestamp: performance.now(),+ const nextPageLayout = {+ ...page,+ rotatedHeight: rotatedSize.height,+ rotatedWidth: rotatedSize.width,+ x: layout.strategy === ScrollStrategy.Horizontal ? 0 : pageOffset,+ y: layout.strategy === ScrollStrategy.Horizontal ? pageOffset : 0,}- frameId = window.requestAnimationFrame(updateActivePageFromViewport)- viewport.addEventListener("scroll", handleScroll, { passive: true })- return () => {- window.cancelAnimationFrame(frameId)- window.clearTimeout(idleTimeoutId)- viewport.removeEventListener("scroll", handleScroll)+ pageOffset +=+ (layout.strategy === ScrollStrategy.Horizontal+ ? rotatedSize.height+ : rotatedSize.width) + pageGap+ itemWidth =+ layout.strategy === ScrollStrategy.Horizontal+ ? Math.max(itemWidth, rotatedSize.width)+ : itemWidth + rotatedSize.width+ itemHeight =+ layout.strategy === ScrollStrategy.Horizontal+ ? itemHeight + rotatedSize.height+ : Math.max(itemHeight, rotatedSize.height)++ return nextPageLayout+ })++ if (pageLayouts.length > 1) {+ if (layout.strategy === ScrollStrategy.Horizontal) {+ itemHeight -= pageGap+ } else {+ itemWidth -= pageGap}- }, [numPages, updateActivePageFromViewport])-- React.useImperativeHandle(- ref,- () => ({- scrollToPage: (pageNumber, options) => {- const pageIndex = renderedPageNumbers.indexOf(pageNumber)- if (pageIndex === -1) return-- pageVirtualizer.scrollToIndex(pageIndex, {- align: "start",- behavior: options?.behavior ?? "auto",- })- },- scrollToPageArea: (pageNumber, area, options) => {- const viewport = viewportRef.current- const pageIndex = renderedPageNumbers.indexOf(pageNumber)- const pageOffset = pageVirtualizer.getOffsetForIndex(- pageIndex,- "start"- )?.[0]-- if (!viewport || pageIndex === -1 || pageOffset === undefined) return-- const metrics = getPageMetrics(pageNumber)- const rotationDelta = pageRotationDeltas.get(pageNumber) ?? 0- const effectiveRotation = normalizeRotation(- metrics.rotation + rotationDelta- )- const dimensions = getPageDimensions(metrics, effectiveRotation)- const targetTop =- pageOffset + (area.top / 100) * dimensions.height * zoom - 96-- viewport.scrollTo({- top: Math.max(0, targetTop),- behavior: "smooth",- ...options,- })- },- getViewportElement: () => viewportRef.current,- }),- [- getPageMetrics,- pageRotationDeltas,- pageVirtualizer,- renderedPageNumbers,- zoom,- ]- )+ }- const restoreWindowScroll = React.useCallback((scrollY: number) => {- window.scrollTo({ top: scrollY })- window.requestAnimationFrame(() => {- window.scrollTo({ top: scrollY })- window.requestAnimationFrame(() => {- window.scrollTo({ top: scrollY })- })- })- ;[0, 50, 150, 300].forEach((delay) => {- window.setTimeout(() => {- window.scrollTo({ top: scrollY })- }, delay)- })- }, [])+ const nextItem = {+ ...item,+ height: itemHeight,+ offset,+ pageLayouts,+ width: itemWidth,+ x: layout.strategy === ScrollStrategy.Horizontal ? offset : item.x,+ y: layout.strategy === ScrollStrategy.Horizontal ? item.y : offset,+ }- const scrollToPage = React.useCallback(- (pageNumber: number) => {- const windowScrollY = thumbnailClickScrollYRef.current ?? window.scrollY- setActivePage(pageNumber)- onActivePageChange?.(pageNumber)+ if (layout.strategy === ScrollStrategy.Horizontal) {+ offset += itemWidth + pageGap+ maxHeight = Math.max(maxHeight, itemHeight)+ } else {+ offset += itemHeight + pageGap+ maxWidth = Math.max(maxWidth, itemWidth)+ }- const pageIndex = renderedPageNumbers.indexOf(pageNumber)+ return nextItem+ })- if (pageIndex === -1) {- restoreWindowScroll(windowScrollY)- return- }+ if (items.length > 0) {+ offset -= pageGap+ }- pageVirtualizer.scrollToIndex(pageIndex, {- align: "start",- behavior: "auto",- })- restoreWindowScroll(windowScrollY)- window.setTimeout(() => {- if (thumbnailClickScrollYRef.current === windowScrollY) {- thumbnailClickScrollYRef.current = null- }- }, 350)- },- [- onActivePageChange,- pageVirtualizer,- renderedPageNumbers,- restoreWindowScroll,- ]- )+ return {+ ...layout,+ endSpacing: layout.endSpacing,+ items,+ startSpacing: layout.startSpacing + startSpacingAdjustment,+ totalHeight:+ layout.strategy === ScrollStrategy.Horizontal+ ? maxHeight+ : layout.startSpacing ++ startSpacingAdjustment ++ offset ++ layout.endSpacing,+ totalWidth:+ layout.strategy === ScrollStrategy.Horizontal+ ? layout.startSpacing ++ startSpacingAdjustment ++ offset ++ layout.endSpacing+ : maxWidth,+ }+}- const handlePageNumberChange = React.useCallback(- (pageNumber: number) => {- if (!renderedPageNumbers.includes(pageNumber)) return+function PDFViewerScroller({+ documentId,+ pageRotationDeltas,+ basePageRotations,+ renderPage,+}: {+ documentId: string+ pageRotationDeltas: PageRotationDeltas+ basePageRotations: Rotation[]+ renderPage: (props: PageLayout) => React.ReactNode+}) {+ const { plugin: scrollPlugin } = useScrollPlugin()+ const [layoutData, setLayoutData] = React.useState<{+ docId: string | null+ layout: ScrollerLayout | null+ }>({ docId: null, layout: null })- scrollToPage(pageNumber)- },- [renderedPageNumbers, scrollToPage]- )+ React.useEffect(() => {+ if (!scrollPlugin || !documentId) return- const preserveThumbnailClickScroll = React.useCallback(- (event: React.PointerEvent | React.MouseEvent) => {- event.preventDefault()+ const unsubscribe = scrollPlugin.onScrollerData(documentId, (layout) => {+ setLayoutData({ docId: documentId, layout })+ })- if (thumbnailClickScrollYRef.current === null) {- thumbnailClickScrollYRef.current = window.scrollY- }- },- []- )+ return () => {+ unsubscribe()+ setLayoutData({ docId: null, layout: null })+ scrollPlugin.clearLayoutReady(documentId)+ }+ }, [documentId, scrollPlugin])- const scrollActiveThumbnailIntoView = React.useCallback(() => {- if (activePageIndex === -1) return+ const scrollerLayout = React.useMemo(() => {+ if (layoutData.docId !== documentId || !layoutData.layout) return null- thumbnailVirtualizer.scrollToIndex(activePageIndex, {- align: "center",- behavior: "auto",- })- }, [activePageIndex, thumbnailVirtualizer])+ return applyPageRotationDeltasToScrollerLayout({+ basePageRotations,+ layout: layoutData.layout,+ pageRotationDeltas,+ })+ }, [basePageRotations, documentId, layoutData, pageRotationDeltas])- React.useEffect(() => {- const wasThumbnailSidebarVisible = wasThumbnailSidebarVisibleRef.current- wasThumbnailSidebarVisibleRef.current = thumbnailSidebarVisible+ React.useLayoutEffect(() => {+ if (!scrollPlugin || !documentId || !scrollerLayout) return+ scrollPlugin.setLayoutReady(documentId)+ }, [documentId, scrollPlugin, scrollerLayout])- if (!thumbnailSidebarVisible || wasThumbnailSidebarVisible) return+ if (!scrollerLayout) return null- const frameId = window.requestAnimationFrame(- scrollActiveThumbnailIntoView- )-- return () => window.cancelAnimationFrame(frameId)- }, [scrollActiveThumbnailIntoView, thumbnailSidebarVisible])-- const handleLoadStart = React.useCallback(() => {- setIsDocumentLoading(true)- setIsFirstPageRendering(true)- setLoadError(false)- setPdfDocument(null)- pendingPageMetricsRef.current.clear()- pageMetricsGenerationRef.current += 1- setNumPages(0)- setActivePage(1)- setPageMetrics(new Map())- setPageRotationDeltas(new Map())- setSettledPageNumbers(new Set())- setLowResolutionPageNumbers(new Set())- setVisiblePageNumbers(new Set([1]))- setScrollState({ direction: "none", isFastScrolling: false })- onActivePageChange?.(1)- setSearchQuery("")- setSearchDraft("")- viewportRef.current?.scrollTo({ top: 0, left: 0 })- }, [onActivePageChange])-- const handleLoadSuccess = React.useCallback(- async (pdf: PDFDocumentProxy) => {- const nextNumPages = pdf.numPages- const nextGeneration = pageMetricsGenerationRef.current + 1-- pageMetricsGenerationRef.current = nextGeneration- pendingPageMetricsRef.current.clear()- setPdfDocument(pdf)- setNumPages(nextNumPages)- setIsFirstPageRendering(true)- setSettledPageNumbers(new Set())- setLowResolutionPageNumbers(new Set())- setVisiblePageNumbers(new Set([1]))- setLoadError(false)- setActivePage(1)- onActivePageChange?.(1)- onDocumentLoadSuccess?.(nextNumPages)- setSearchQuery("")- setSearchDraft("")- viewportRef.current?.scrollTo({ top: 0, left: 0 })-- try {- const initialPageNumber = pageNumbers?.[0] ?? 1- const initialMetrics = await getPdfPageMetrics(pdf, initialPageNumber)-- if (nextGeneration === pageMetricsGenerationRef.current) {- setPageMetrics(new Map([[initialPageNumber, initialMetrics]]))- }- } catch {- setPageMetrics(new Map())- } finally {- setIsDocumentLoading(false)+ return (+ <div+ style={{+ width: `${scrollerLayout.totalWidth}px`,+ height: `${scrollerLayout.totalHeight}px`,+ position: "relative",+ boxSizing: "border-box",+ margin: "0 auto",+ ...(scrollerLayout.strategy === ScrollStrategy.Horizontal && {+ display: "flex",+ flexDirection: "row",+ }),+ }}+ >+ <div+ style={+ scrollerLayout.strategy === ScrollStrategy.Horizontal+ ? {+ width: scrollerLayout.startSpacing,+ height: "100%",+ flexShrink: 0,+ }+ : {+ height: scrollerLayout.startSpacing,+ width: "100%",+ }}- },- [onActivePageChange, onDocumentLoadSuccess, pageNumbers]- )+ />+ <div+ style={{+ gap: scrollerLayout.pageGap,+ display: "flex",+ alignItems: "center",+ position: "relative",+ boxSizing: "border-box",+ ...(scrollerLayout.strategy === ScrollStrategy.Horizontal+ ? {+ flexDirection: "row",+ minHeight: "100%",+ }+ : {+ flexDirection: "column",+ minWidth: "fit-content",+ }),+ }}+ >+ {scrollerLayout.items.map((item) => (+ <div+ key={item.pageNumbers[0]}+ style={{+ display: "flex",+ justifyContent: "center",+ gap: scrollerLayout.pageGap,+ }}+ >+ {item.pageLayouts.map((layout) => (+ <div+ key={layout.pageNumber}+ style={{+ width: `${layout.rotatedWidth}px`,+ height: `${layout.rotatedHeight}px`,+ position: "relative",+ zIndex: layout.elevated ? 1 : undefined,+ }}+ >+ {renderPage(layout)}+ </div>+ ))}+ </div>+ ))}+ </div>+ <div+ style={+ scrollerLayout.strategy === ScrollStrategy.Horizontal+ ? {+ width: scrollerLayout.endSpacing,+ height: "100%",+ flexShrink: 0,+ }+ : {+ height: scrollerLayout.endSpacing,+ width: "100%",+ }+ }+ />+ </div>+ )+}- const handleLoadError = React.useCallback(() => {- setIsDocumentLoading(false)- setIsFirstPageRendering(false)- setLoadError(true)- setPdfDocument(null)- pendingPageMetricsRef.current.clear()- pageMetricsGenerationRef.current += 1- setNumPages(0)- setPageMetrics(new Map())- setPageRotationDeltas(new Map())- setSettledPageNumbers(new Set())- setLowResolutionPageNumbers(new Set())- setVisiblePageNumbers(new Set([1]))- }, [])+type PDFViewerInnerProps = {+ viewerRef: React.ForwardedRef<PDFViewerHandle>+ pdfFile: string+ documentId: string+ document: PdfDocumentObject | null+ defaultZoom: number+ className?: string+ defaultThumbnailSidebarOpen: boolean+ downloadFileName?: string+ showDownload: boolean+ showToolbar: boolean+ showRotateControls: boolean+ showUpload: boolean+ toolbarActions?: React.ReactNode+ pageClassName?: (pageNumber: number) => string | undefined+ renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode+ onActivePageChange?: (pageNumber: number) => void+ onPdfUpload?: (file: File) => void+ onPagePointerDown?: PDFViewerProps["onPagePointerDown"]+ onPagePointerMove?: PDFViewerProps["onPagePointerMove"]+ onPagePointerUp?: PDFViewerProps["onPagePointerUp"]+ onPagePointerCancel?: PDFViewerProps["onPagePointerCancel"]+ onUploadFile: (file: File) => void+}- const handlePageSettled = React.useCallback(- (pageNumber: number, devicePixelRatioLimit: number) => {- setSettledPageNumbers((currentPageNumbers) => {- if (currentPageNumbers.has(pageNumber)) return currentPageNumbers+function PDFViewerInner({+ viewerRef,+ pdfFile,+ documentId,+ document: pdfDocument,+ defaultZoom,+ className,+ defaultThumbnailSidebarOpen,+ downloadFileName,+ showDownload,+ showToolbar,+ showRotateControls,+ showUpload,+ toolbarActions,+ pageClassName,+ renderPageOverlay,+ onActivePageChange,+ onPdfUpload,+ onPagePointerDown,+ onPagePointerMove,+ onPagePointerUp,+ onPagePointerCancel,+ onUploadFile,+}: PDFViewerInnerProps) {+ const { registry } = useRegistry()+ const { state: scrollState, provides: scroll } = useScroll(documentId)+ const { state: zoomState, provides: zoom } = useZoom(documentId)+ const { provides: thumbnails } = useThumbnailCapability()+ const { plugin: thumbnailPlugin } = useThumbnailPlugin()+ const [sidebarOpen, setSidebarOpen] = React.useState(+ defaultThumbnailSidebarOpen+ )+ const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)+ const [pageRotationDeltas, setPageRotationDeltas] =+ React.useState<PageRotationDeltas>(() => new Map())+ const [selectedPageIndexes, setSelectedPageIndexes] = React.useState<+ Set<number>+ >(() => new Set())+ const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()+ const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)+ const viewportElementRef = React.useRef<HTMLDivElement | null>(null)+ const pageRotationDeltasRef = React.useRef(pageRotationDeltas)+ const selectedPageIndexesRef = React.useRef(selectedPageIndexes)+ const selectionAnchorPageIndexRef = React.useRef<number | null>(null)+ const suppressActivePageSelectionSyncRef = React.useRef<number | null>(null)+ const initializedSelectionDocumentRef = React.useRef<string | null>(null)+ const basePageRotationsRef = React.useRef<Rotation[]>([])+ const basePageRotationsDocumentRef = React.useRef<string | null>(null)++ const activePage = scrollState.currentPage+ const numPages = pdfDocument?.pageCount ?? 0+ const isLoading = !pdfDocument+ const controlsDisabled = !numPages+ const downloadDisabled = controlsDisabled || isPreparingDownload+ const thumbnailSidebarVisible = sidebarOpen && !isLoading+ const currentZoomLevel = zoomState.currentZoomLevel+ const alignedThumbnailSidebarDocumentRef = React.useRef<string | null>(null)- const nextPageNumbers = new Set(currentPageNumbers)- nextPageNumbers.add(pageNumber)- return nextPageNumbers- })- setLowResolutionPageNumbers((currentPageNumbers) => {- const isLowResolutionRender =- devicePixelRatioLimit < MAX_DEVICE_PIXEL_RATIO- const alreadyLowResolution = currentPageNumbers.has(pageNumber)+ React.useEffect(() => {+ pageRotationDeltasRef.current = pageRotationDeltas+ }, [pageRotationDeltas])- if (isLowResolutionRender && alreadyLowResolution) {- return currentPageNumbers- }+ React.useEffect(() => {+ selectedPageIndexesRef.current = selectedPageIndexes+ }, [selectedPageIndexes])- if (!isLowResolutionRender && !alreadyLowResolution) {- return currentPageNumbers- }+ React.useEffect(() => {+ const emptyDeltas = new Map<number, Rotation>()+ pageRotationDeltasRef.current = emptyDeltas+ setPageRotationDeltas(emptyDeltas)+ const emptySelection = new Set<number>()+ selectedPageIndexesRef.current = emptySelection+ setSelectedPageIndexes(emptySelection)+ selectionAnchorPageIndexRef.current = null+ suppressActivePageSelectionSyncRef.current = null+ initializedSelectionDocumentRef.current = null+ basePageRotationsRef.current = []+ basePageRotationsDocumentRef.current = null+ }, [documentId])- const nextPageNumbers = new Set(currentPageNumbers)+ React.useEffect(() => {+ if (!pdfDocument || basePageRotationsDocumentRef.current === documentId) {+ return+ }- if (isLowResolutionRender) {- nextPageNumbers.add(pageNumber)- } else {- nextPageNumbers.delete(pageNumber)- }+ basePageRotationsRef.current = pdfDocument.pages.map((page) =>+ normalizeRotation(page.rotation)+ )+ basePageRotationsDocumentRef.current = documentId+ }, [documentId, pdfDocument])- return nextPageNumbers- })+ React.useEffect(() => {+ if (activePage > 0) onActivePageChange?.(activePage)+ }, [activePage, onActivePageChange])- if (pageNumber === firstRenderedPage) {- setIsFirstPageRendering(false)- }- },- [firstRenderedPage]+ React.useEffect(() => {+ if (activePage < 1 || numPages < 1) return++ const activePageIndex = activePage - 1+ const suppressedPageIndex = suppressActivePageSelectionSyncRef.current++ suppressActivePageSelectionSyncRef.current = null++ if (suppressedPageIndex === activePageIndex) return++ const nextSelection = new Set([activePageIndex])++ selectionAnchorPageIndexRef.current = activePageIndex+ selectedPageIndexesRef.current = nextSelection+ setSelectedPageIndexes((previousSelection) =>+ arePageIndexSetsEqual(previousSelection, nextSelection)+ ? previousSelection+ : nextSelection)+ }, [activePage, numPages])- React.useEffect(() => {- setSettledPageNumbers(new Set())- setLowResolutionPageNumbers(new Set())- setVisiblePageNumbers(new Set([1]))- setIsFirstPageRendering(Boolean(pdfFile))- }, [pdfFile])-- const rotateActivePage = React.useCallback(- (rotationDelta: number) => {- setPageRotationDeltas((currentRotations) => {- const currentRotation = currentRotations.get(activePage) ?? 0- const nextRotation = normalizeRotation(- currentRotation + rotationDelta- )- const nextRotations = new Map(currentRotations)+ React.useEffect(() => {+ if (+ numPages < 1 ||+ initializedSelectionDocumentRef.current === documentId+ ) {+ return+ }++ const initialPageIndex = Math.max(0, (activePage > 0 ? activePage : 1) - 1)+ const initialSelection = new Set([initialPageIndex])++ initializedSelectionDocumentRef.current = documentId+ selectionAnchorPageIndexRef.current = initialPageIndex+ selectedPageIndexesRef.current = initialSelection+ setSelectedPageIndexes(initialSelection)+ }, [activePage, documentId, numPages])++ React.useEffect(() => {+ if (!thumbnailSidebarVisible) {+ alignedThumbnailSidebarDocumentRef.current = null+ return+ }++ if (+ activePage < 1 ||+ !thumbnails ||+ alignedThumbnailSidebarDocumentRef.current === documentId+ ) {+ return+ }++ alignedThumbnailSidebarDocumentRef.current = documentId+ const frame = window.requestAnimationFrame(() => {+ thumbnails.forDocument(documentId).scrollToThumb(activePage - 1)+ })++ return () => window.cancelAnimationFrame(frame)+ }, [activePage, documentId, thumbnailSidebarVisible, thumbnails])++ // The zoom plugin only releases its viewport gate for mode-based zoom+ // levels (automatic/fit); with a numeric default the gate would never+ // lift, so apply the initial zoom explicitly once the document loads.+ const initialZoomDocumentRef = React.useRef<string | null>(null)+ React.useEffect(() => {+ if (!pdfDocument || !zoom) return+ if (initialZoomDocumentRef.current === documentId) return++ initialZoomDocumentRef.current = documentId+ zoom.requestZoom(defaultZoom)+ }, [defaultZoom, documentId, pdfDocument, zoom])++ const scrollToPage = React.useCallback(+ (pageNumber: number, options?: ScrollIntoViewOptions) => {+ scroll?.scrollToPage({+ pageNumber,+ behavior: options?.behavior === "smooth" ? "smooth" : "auto",+ })+ },+ [scroll]+ )++ const selectThumbnailPage = React.useCallback(+ (pageNumber: number, mode: ThumbnailSelectionMode) => {+ const pageIndex = pageNumber - 1++ if (pageIndex < 0 || pageIndex >= numPages) return++ suppressActivePageSelectionSyncRef.current = pageIndex++ setSelectedPageIndexes((previousSelection) => {+ let nextSelection: Set<number>- if (nextRotation) {- nextRotations.set(activePage, nextRotation)+ if (mode === "range") {+ const anchorPageIndex =+ selectionAnchorPageIndexRef.current ??+ (activePage > 0 ? activePage - 1 : pageIndex)++ nextSelection = getPageIndexRange(anchorPageIndex, pageIndex)+ } else if (mode === "toggle") {+ nextSelection = new Set(previousSelection)++ if (nextSelection.has(pageIndex)) {+ nextSelection.delete(pageIndex)} else {- nextRotations.delete(activePage)+ nextSelection.add(pageIndex)}- return nextRotations+ selectionAnchorPageIndexRef.current = pageIndex+ } else {+ nextSelection = new Set([pageIndex])+ selectionAnchorPageIndexRef.current = pageIndex+ }++ selectedPageIndexesRef.current = nextSelection+ return nextSelection+ })++ scrollToPage(pageNumber)+ },+ [activePage, numPages, scrollToPage]+ )++ React.useImperativeHandle(+ viewerRef,+ () => ({+ scrollToPage,+ scrollToPageArea: (pageNumber, area, options) => {+ const pageSize = pdfDocument?.pages[pageNumber - 1]?.size++ scroll?.scrollToPage({+ pageNumber,+ ...(pageSize+ ? {+ pageCoordinates: {+ x: ((area.left ?? 0) / 100) * pageSize.width,+ y: (area.top / 100) * pageSize.height,+ },+ alignY: 25,+ }+ : {}),+ behavior: options?.behavior === "smooth" ? "smooth" : "auto",})},- [activePage]- )+ getViewportElement: () => viewportElementRef.current,+ }),+ [pdfDocument, scroll, scrollToPage]+ )- const handleDownload = React.useCallback(async () => {- if (!pdfFile || isPreparingDownload) return+ const handleDownload = React.useCallback(async () => {+ if (!pdfFile || isPreparingDownload) return- setIsPreparingDownload(true)+ setIsPreparingDownload(true)- try {- await downloadPdfWithPageRotations({- file: pdfFile,- fileName: resolvedDownloadFileName,- pageRotationDeltas,+ try {+ await downloadPdfWithPageRotations({+ file: pdfFile,+ fileName: getPdfDownloadFileName(downloadFileName, pdfFile),+ pageRotationDeltas,+ })+ } catch (error) {+ console.error(error)+ } finally {+ setIsPreparingDownload(false)+ }+ }, [downloadFileName, isPreparingDownload, pageRotationDeltas, pdfFile])++ const rotateSelectedPages = React.useCallback(+ (direction: -1 | 1) => {+ if (!pdfDocument || !registry || activePage < 1) return++ const documentState = registry.getStore().getState().core.documents[+ documentId+ ]+ const currentDocument = documentState?.document ?? pdfDocument+ const selectedTargetPageIndexes = Array.from(+ selectedPageIndexesRef.current+ ).filter((pageIndex) => currentDocument.pages[pageIndex])+ const fallbackPageIndex = activePage - 1+ const targetPageIndexes = (+ selectedTargetPageIndexes.length+ ? selectedTargetPageIndexes+ : [fallbackPageIndex]+ )+ .filter((pageIndex) => currentDocument.pages[pageIndex])+ .sort((a, b) => a - b)++ if (targetPageIndexes.length === 0) return++ const previousDeltas = pageRotationDeltasRef.current+ const nextDeltas = new Map(previousDeltas)+ const referencePageIndex =+ activePage > 0 && currentDocument.pages[activePage - 1]+ ? activePage - 1+ : targetPageIndexes[0]+ let scrollDelta = 0++ for (const pageIndex of targetPageIndexes) {+ const currentPage = currentDocument.pages[pageIndex]+ if (!currentPage) continue++ const previousDelta = previousDeltas.get(pageIndex) ?? 0+ const nextDelta = normalizeRotation(previousDelta + direction)+ const basePageRotation =+ basePageRotationsRef.current[pageIndex] ??+ normalizeRotation(currentPage.rotation)+ const previousPageRotation = normalizeRotation(+ basePageRotation + previousDelta+ )+ const nextPageRotation = normalizeRotation(basePageRotation + nextDelta)+ const previousRotatedSize = getRotatedDimensions({+ height: currentPage.size.height * currentZoomLevel,+ rotation: previousPageRotation,+ width: currentPage.size.width * currentZoomLevel,+ })+ const nextRotatedSize = getRotatedDimensions({+ height: currentPage.size.height * currentZoomLevel,+ rotation: nextPageRotation,+ width: currentPage.size.width * currentZoomLevel,})- } catch (error) {- console.error(error)- } finally {- setIsPreparingDownload(false)+ const heightDelta = nextRotatedSize.height - previousRotatedSize.height++ if (pageIndex < referencePageIndex) {+ scrollDelta += heightDelta+ } else if (pageIndex === referencePageIndex) {+ scrollDelta += heightDelta / 2+ }++ if (nextDelta) {+ nextDeltas.set(pageIndex, nextDelta)+ } else {+ nextDeltas.delete(pageIndex)+ }}- }, [- isPreparingDownload,- pageRotationDeltas,- pdfFile,- resolvedDownloadFileName,- ])- const handleUpload = React.useCallback(- (file: File) => {- const nextUrl = URL.createObjectURL(file)+ pageRotationDeltasRef.current = nextDeltas+ setPageRotationDeltas(nextDeltas)- setUploadedPdfUrl((previousUrl) => {- if (previousUrl) URL.revokeObjectURL(previousUrl)- return nextUrl+ const store = registry.getStore()++ store.dispatchToCore(refreshPages(documentId, targetPageIndexes))+ const viewport = viewportElementRef.current++ if (viewport && scrollDelta !== 0) {+ window.requestAnimationFrame(() => {+ viewport.scrollTop += scrollDelta})- setPdfFile(nextUrl)- onPdfUpload?.(file)- },- [onPdfUpload]- )+ }+ ;(+ thumbnailPlugin as {+ calculateWindowState?: (documentId: string) => void+ } | null+ )?.calculateWindowState?.(documentId)+ },+ [+ activePage,+ currentZoomLevel,+ documentId,+ pdfDocument,+ registry,+ thumbnailPlugin,+ ]+ )- return (- <div- data-slot="pdf-viewer"- className={cn(- "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",- className- )}- >- {showToolbar ? (- <div className="flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2">- <div className="flex min-w-0 flex-wrap items-center gap-2">- <TooltipProvider>- <ToolbarTooltip label="Toggle thumbnails">- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label="Toggle thumbnails"- disabled={controlsDisabled}- onClick={() => setSidebarOpen((open) => !open)}- >- <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />- </Button>- </ToolbarTooltip>- </TooltipProvider>- <PDFViewerPageNumberControl- activePage={activePage}- controlsDisabled={controlsDisabled}- numPages={numPages}- onPageChange={handlePageNumberChange}- />- </div>+ const handleUpload = React.useCallback(+ (file: File) => {+ onUploadFile(file)+ onPdfUpload?.(file)+ },+ [onPdfUpload, onUploadFile]+ )++ const renderPage = React.useCallback(+ (page: PageLayout) => {+ const pageNumber = page.pageNumber+ const basePageRotation =+ basePageRotationsRef.current[page.pageIndex] ??+ pdfDocument?.pages[page.pageIndex]?.rotation ??+ normalizeRotation(0)+ const pageRotation = normalizeRotation(+ basePageRotation + (pageRotationDeltas.get(page.pageIndex) ?? 0)+ )++ return (+ <Rotate+ documentId={documentId}+ pageIndex={page.pageIndex}+ rotation={pageRotation}+ >+ <PagePointerProvider+ documentId={documentId}+ pageIndex={page.pageIndex}+ rotation={pageRotation}+ key={`${page.pageIndex}-${pageRotation}`}+ data-pdf-viewer-page={pageNumber}+ className={cn(+ "relative border border-transparent bg-transparent shadow-xs select-none selection:bg-transparent selection:text-inherit",+ pageClassName?.(pageNumber)+ )}+ style={{ backgroundColor: "transparent" }}+ onPointerDown={(event: React.PointerEvent<HTMLDivElement>) =>+ onPagePointerDown?.(event, pageNumber)+ }+ onPointerMove={(event: React.PointerEvent<HTMLDivElement>) =>+ onPagePointerMove?.(event, pageNumber)+ }+ onPointerUp={(event: React.PointerEvent<HTMLDivElement>) =>+ onPagePointerUp?.(event, pageNumber)+ }+ onPointerCancel={(event: React.PointerEvent<HTMLDivElement>) =>+ onPagePointerCancel?.(event, pageNumber)+ }+ >+ <div+ aria-hidden="true"+ className="pointer-events-none absolute inset-0 bg-white"+ />+ <RenderLayer+ documentId={documentId}+ pageIndex={page.pageIndex}+ scale={Math.min(currentZoomLevel, PAGE_BASE_RENDER_MAX_SCALE)}+ dpr={PAGE_BASE_RENDER_DPR}+ className="pointer-events-none absolute inset-0 h-full w-full object-fill opacity-100 blur-[0.35px] transition-none"+ />+ <TilingLayer+ documentId={documentId}+ pageIndex={page.pageIndex}+ key={`tiles-${page.pageIndex}-${pageRotation}`}+ className="pointer-events-none opacity-100 transition-none [&_img]:opacity-100 [&_img]:transition-none"+ />+ <SearchLayer+ documentId={documentId}+ pageIndex={page.pageIndex}+ className="pointer-events-none"+ highlightColor="rgba(253, 224, 71, 0.45)"+ activeHighlightColor="rgba(249, 115, 22, 0.55)"+ />+ <PDFViewerTextSelectionLayer+ documentId={documentId}+ pageIndex={page.pageIndex}+ scale={currentZoomLevel}+ />+ {renderPageOverlay?.({+ pageNumber,+ pageWidth: page.width,+ pageHeight: page.height,+ scale: currentZoomLevel,+ rotation: rotationToDegrees(pageRotation),+ })}+ </PagePointerProvider>+ </Rotate>+ )+ },+ [+ currentZoomLevel,+ onPagePointerCancel,+ onPagePointerDown,+ onPagePointerMove,+ onPagePointerUp,+ pageClassName,+ pageRotationDeltas,+ renderPageOverlay,+ documentId,+ pdfDocument,+ ]+ )++ return (+ <div+ data-slot="pdf-viewer"+ className={cn(+ "flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",+ "select-none selection:bg-transparent selection:text-inherit",+ className+ )}+ >+ {showToolbar ? (+ <div className="flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2">+ <div className="flex min-w-0 flex-wrap items-center gap-2"><TooltipProvider>- <div className="flex min-w-0 flex-wrap items-center justify-end gap-1">- {showRotateControls ? (- <>- <div className="flex flex-none items-center gap-1">- <ToolbarTooltip label="Rotate page counterclockwise">- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label="Rotate page counterclockwise"- disabled={controlsDisabled}- onClick={() => rotateActivePage(-90)}- >- <HugeiconsIcon- icon={RotateClockwiseIcon}- className="size-4 -scale-x-100"- />- </Button>- </ToolbarTooltip>- <ToolbarTooltip label="Rotate page clockwise">- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label="Rotate page clockwise"- disabled={controlsDisabled}- onClick={() => rotateActivePage(90)}- >- <HugeiconsIcon- icon={RotateClockwiseIcon}- className="size-4"- />- </Button>- </ToolbarTooltip>- </div>- <Separator- orientation="vertical"- className="mx-1 h-4 self-center"- />- </>- ) : null}- <div className="flex flex-none items-center gap-1">- <ToolbarTooltip label="Zoom out">- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label="Zoom out"- disabled={controlsDisabled || zoom <= ZOOM_OPTIONS[0]}- onClick={() => {- const currentIndex = ZOOM_OPTIONS.indexOf(zoom)- setZoom(- ZOOM_OPTIONS[Math.max(0, currentIndex - 1)] ?? zoom- )- }}- >- <HugeiconsIcon- icon={MinusSignCircleIcon}- className="size-4"- />- </Button>- </ToolbarTooltip>- <Select- value={String(zoom)}- onValueChange={(value) => setZoom(Number(value))}- disabled={controlsDisabled}- modal={false}- >- <SelectTrigger size="sm" className="w-[84px] min-w-[84px]">- <SelectValue placeholder="Zoom">- {Math.round(zoom * 100)}%- </SelectValue>- </SelectTrigger>- <SelectContent alignItemWithTrigger={false}>- {ZOOM_OPTIONS.map((option) => (- <SelectItem key={option} value={String(option)}>- {Math.round(option * 100)}%- </SelectItem>- ))}- </SelectContent>- </Select>- <ToolbarTooltip label="Zoom in">- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label="Zoom in"- disabled={- controlsDisabled ||- zoom >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]- }- onClick={() => {- const currentIndex = ZOOM_OPTIONS.indexOf(zoom)- setZoom(- ZOOM_OPTIONS[- Math.min(ZOOM_OPTIONS.length - 1, currentIndex + 1)- ] ?? zoom- )- }}- >- <HugeiconsIcon- icon={PlusSignCircleIcon}- className="size-4"- />- </Button>- </ToolbarTooltip>- </div>- <Separator- orientation="vertical"- className="mx-1 h-4 self-center"- />- <Popover>- <ToolbarTooltip label="Search text">- <PopoverTrigger asChild>+ <ToolbarTooltip label="Toggle thumbnails">+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Toggle thumbnails"+ disabled={controlsDisabled}+ onClick={() => setSidebarOpen((open) => !open)}+ >+ <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />+ </Button>+ </ToolbarTooltip>+ </TooltipProvider>+ <PDFViewerPageNumberControl+ activePage={activePage}+ controlsDisabled={controlsDisabled}+ numPages={numPages}+ onPageChange={scrollToPage}+ />+ </div>+ <TooltipProvider>+ <div className="flex min-w-0 flex-wrap items-center justify-end gap-1">+ {showRotateControls ? (+ <>+ <div className="flex flex-none items-center gap-1">+ <ToolbarTooltip label="Rotate counterclockwise"><Buttontype="button"variant="ghost"size="icon-sm"- aria-label="Search text"+ aria-label="Rotate counterclockwise"disabled={controlsDisabled}+ onClick={() => rotateSelectedPages(-1)}>- <HugeiconsIcon icon={Search01Icon} className="size-4" />+ <HugeiconsIcon+ icon={RotateClockwiseIcon}+ className="size-4"+ /></Button>- </PopoverTrigger>- </ToolbarTooltip>- <PopoverContent align="end" className="w-64">- <SearchInput- value={searchDraft}- onValueChange={setSearchDraft}- onApply={() => setSearchQuery(searchDraft)}- onClear={() => {- setSearchDraft("")- setSearchQuery("")- }}- />- </PopoverContent>- </Popover>- {showDownload ? (- <>- <Separator- orientation="vertical"- className="mx-1 h-4 self-center"- />- <ToolbarTooltip label="Download PDF">+ </ToolbarTooltip>+ <ToolbarTooltip label="Rotate clockwise"><Buttontype="button"variant="ghost"size="icon-sm"- aria-label="Download PDF"- disabled={downloadDisabled}- onClick={handleDownload}+ aria-label="Rotate clockwise"+ disabled={controlsDisabled}+ onClick={() => rotateSelectedPages(1)}>- {isPreparingDownload ? (- <Spinner className="size-4" />- ) : (- <HugeiconsIcon- icon={Download01Icon}- className="size-4"- />- )}+ <HugeiconsIcon+ icon={RotateClockwiseIcon}+ className="size-4 -scale-x-100"+ /></Button></ToolbarTooltip>- </>- ) : null}- {showUpload ? (- <>- <Separator- orientation="vertical"- className="mx-1 h-4 self-center"+ </div>+ <Separator+ orientation="vertical"+ className="mx-1 h-4 self-center"+ />+ </>+ ) : null}+ <div className="flex flex-none items-center gap-1">+ <ToolbarTooltip label="Zoom out">+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Zoom out"+ disabled={+ controlsDisabled || currentZoomLevel <= ZOOM_OPTIONS[0]+ }+ onClick={() => {+ const nextZoom = [...ZOOM_OPTIONS]+ .reverse()+ .find((option) => option < currentZoomLevel)++ zoom?.requestZoom(nextZoom ?? ZOOM_OPTIONS[0])+ }}+ >+ <HugeiconsIcon+ icon={MinusSignCircleIcon}+ className="size-4"/>- <ToolbarTooltip label="Upload PDF">- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label="Upload PDF"- render={- <label>- <input- type="file"- accept="application/pdf,.pdf"- className="sr-only"- onChange={(event) => {- const nextFile = event.target.files?.[0]-- if (nextFile) {- handleUpload(nextFile)- event.currentTarget.value = ""- }- }}- />- <HugeiconsIcon- icon={Upload01Icon}- className="size-4"- />- </label>- }- />- </ToolbarTooltip>- </>- ) : null}- {toolbarActions ? (- <>- <Separator- orientation="vertical"- className="mx-1 h-4 self-center"+ </Button>+ </ToolbarTooltip>+ <Select+ value={String(currentZoomLevel)}+ onValueChange={(value) => zoom?.requestZoom(Number(value))}+ disabled={controlsDisabled}+ modal={false}+ >+ <SelectTrigger size="sm" className="w-[84px] min-w-[84px]">+ <SelectValue placeholder="Zoom">+ {Math.round(currentZoomLevel * 100)}%+ </SelectValue>+ </SelectTrigger>+ <SelectContent alignItemWithTrigger={false}>+ {ZOOM_OPTIONS.map((option) => (+ <SelectItem key={option} value={String(option)}>+ {Math.round(option * 100)}%+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <ToolbarTooltip label="Zoom in">+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Zoom in"+ disabled={+ controlsDisabled ||+ currentZoomLevel >= ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]+ }+ onClick={() => {+ const nextZoom = ZOOM_OPTIONS.find(+ (option) => option > currentZoomLevel+ )++ zoom?.requestZoom(+ nextZoom ?? ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]+ )+ }}+ >+ <HugeiconsIcon+ icon={PlusSignCircleIcon}+ className="size-4"/>- {toolbarActions}- </>- ) : null}+ </Button>+ </ToolbarTooltip></div>- </TooltipProvider>- </div>+ <Separator+ orientation="vertical"+ className="mx-1 h-4 self-center"+ />+ <PDFViewerSearchControl+ key={documentId}+ documentId={documentId}+ controlsDisabled={controlsDisabled}+ />+ {showDownload ? (+ <>+ <Separator+ orientation="vertical"+ className="mx-1 h-4 self-center"+ />+ <ToolbarTooltip label="Download PDF">+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Download PDF"+ disabled={downloadDisabled}+ onClick={handleDownload}+ >+ {isPreparingDownload ? (+ <Spinner className="size-4" />+ ) : (+ <HugeiconsIcon+ icon={Download01Icon}+ className="size-4"+ />+ )}+ </Button>+ </ToolbarTooltip>+ </>+ ) : null}+ {showUpload ? (+ <>+ <Separator+ orientation="vertical"+ className="mx-1 h-4 self-center"+ />+ <ToolbarTooltip label="Upload PDF">+ <PDFViewerUploadControl onUploadFile={handleUpload} />+ </ToolbarTooltip>+ </>+ ) : null}+ {toolbarActions ? (+ <>+ <Separator+ orientation="vertical"+ className="mx-1 h-4 self-center"+ />+ {toolbarActions}+ </>+ ) : null}+ </div>+ </TooltipProvider>+ </div>+ ) : null}+ <div+ ref={viewerShellRef}+ className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"+ >+ {isLoading ? (+ <PDFViewerLoadingSkeleton+ sidebarInline={sidebarInline}+ sidebarOpen={sidebarOpen}+ />) : null}+ <div className="flex h-full max-h-full min-h-0 w-full flex-1 overflow-hidden">+ <DocumentViewerThumbnailSidebar+ closedInlineClassName={THUMBNAIL_SIDEBAR_CLOSED_CLASS}+ inline={sidebarInline}+ open={thumbnailSidebarVisible}+ widthClassName={THUMBNAIL_SIDEBAR_WIDTH_CLASS}+ >+ {thumbnailSidebarVisible ? (+ <PDFViewerThumbnails+ basePageRotations={basePageRotationsRef.current}+ documentId={documentId}+ activePage={activePage}+ pageCount={numPages}+ pageRotationDeltas={pageRotationDeltas}+ pdfDocument={pdfDocument}+ selectedPageIndexes={selectedPageIndexes}+ onSelectPage={selectThumbnailPage}+ />+ ) : null}+ </DocumentViewerThumbnailSidebar>+ <PDFViewerScrollAreaViewport+ documentId={documentId}+ className="relative h-full max-h-full min-h-0 min-w-0 flex-1"+ >+ <PDFViewerViewportBridge viewportElementRef={viewportElementRef} />+ <PDFViewerSelectionCopyShortcut documentId={documentId} />+ <PDFViewerSelectionReleaseGuard documentId={documentId} />+ <GlobalPointerProvider documentId={documentId}>+ <PDFViewerScroller+ basePageRotations={basePageRotationsRef.current}+ documentId={documentId}+ pageRotationDeltas={pageRotationDeltas}+ renderPage={renderPage}+ />+ </GlobalPointerProvider>+ <CopyToClipboard />+ </PDFViewerScrollAreaViewport>+ </div>+ </div>+ </div>+ )+}++function PDFViewerDocumentLoader({+ pdfFile,+ onDocumentLoadSuccess,+ ...innerProps+}: {+ pdfFile: string+ onDocumentLoadSuccess?: (numPages: number) => void+} & Omit<PDFViewerInnerProps, "pdfFile" | "documentId" | "document">) {+ const { provides: documentManager } = useDocumentManagerCapability()+ const { activeDocumentId, activeDocument } = useActiveDocument()+ const [loadError, setLoadError] = React.useState(false)+ const openedFileRef = React.useRef<string | null>(null)+ const onDocumentLoadSuccessRef = React.useRef(onDocumentLoadSuccess)++ React.useEffect(() => {+ onDocumentLoadSuccessRef.current = onDocumentLoadSuccess+ })++ React.useEffect(() => {+ if (!documentManager || !pdfFile) return+ if (openedFileRef.current === pdfFile) return++ openedFileRef.current = pdfFile+ setLoadError(false)++ const previousDocumentIds = documentManager+ .getOpenDocuments()+ .map((openDocument) => openDocument.id)+ const handleOpenError = () => {+ if (openedFileRef.current === pdfFile) setLoadError(true)+ }++ documentManager+ .openDocumentUrl({+ url: pdfFile,+ mode: pdfFile.startsWith("blob:") ? "full-fetch" : "auto",+ })+ .wait((response) => {+ response.task.wait((openedDocument) => {+ onDocumentLoadSuccessRef.current?.(openedDocument.pageCount)+ previousDocumentIds.forEach((documentIdToClose) => {+ documentManager.closeDocument(documentIdToClose).wait(+ () => undefined,+ () => undefined+ )+ })+ }, handleOpenError)+ }, handleOpenError)+ }, [documentManager, pdfFile])++ const document =+ activeDocument?.status === "loaded" ? activeDocument.document : null+ const documentFailed = loadError || activeDocument?.status === "error"++ if (!activeDocumentId || documentFailed || !pdfFile) {+ return (+ <PDFViewerFallbackShell+ className={innerProps.className}+ showToolbar={innerProps.showToolbar}+ showUpload={innerProps.showUpload}+ sidebarOpen={innerProps.defaultThumbnailSidebarOpen}+ state={!pdfFile ? "empty" : documentFailed ? "error" : "loading"}+ onUploadFile={(file) => {+ innerProps.onUploadFile(file)+ innerProps.onPdfUpload?.(file)+ }}+ />+ )+ }++ return (+ <PDFViewerInner+ {...innerProps}+ pdfFile={pdfFile}+ documentId={activeDocumentId}+ document={document}+ />+ )+}++export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(+ function PDFViewer(+ {+ file,+ className,+ defaultThumbnailSidebarOpen = false,+ defaultZoom = DEFAULT_ZOOM,+ pageWidth: _pageWidth,+ pageHeight: _pageHeight,+ downloadFileName,+ showDownload = true,+ showRotateControls = true,+ showToolbar = true,+ showUpload = true,+ toolbarActions,+ pageClassName,+ renderPageOverlay,+ onActivePageChange,+ onDocumentLoadSuccess,+ onPdfUpload,+ onPagePointerDown,+ onPagePointerMove,+ onPagePointerUp,+ onPagePointerCancel,+ },+ ref+ ) {+ const { engine, error: engineError } = useSharedPdfEngine()+ const [pdfFile, setPdfFile] = React.useState(file ?? "")+ const [uploadedPdfUrl, setUploadedPdfUrl] = React.useState<string | null>(+ null+ )++ React.useEffect(() => {+ setPdfFile(file ?? "")+ }, [file])++ React.useEffect(+ () => () => {+ if (uploadedPdfUrl) URL.revokeObjectURL(uploadedPdfUrl)+ },+ [uploadedPdfUrl]+ )++ const handleUploadFile = React.useCallback((nextFile: File) => {+ const nextUrl = URL.createObjectURL(nextFile)++ setUploadedPdfUrl((previousUrl) => {+ if (previousUrl) URL.revokeObjectURL(previousUrl)+ return nextUrl+ })+ setPdfFile(nextUrl)+ }, [])++ // Plugin registrations are created once per viewer instance.+ const [plugins] = React.useState(() => [+ createPluginRegistration(DocumentManagerPluginPackage),+ createPluginRegistration(ViewportPluginPackage, {+ viewportGap: PAGE_GAP,+ }),+ createPluginRegistration(ScrollPluginPackage, {+ defaultPageGap: PAGE_GAP,+ defaultBufferSize: 2,+ }),+ createPluginRegistration(RenderPluginPackage),+ createPluginRegistration(TilingPluginPackage, {+ tileSize: 768,+ overlapPx: 2.5,+ extraRings: 0,+ }),+ createPluginRegistration(InteractionManagerPluginPackage),+ createPluginRegistration(SelectionPluginPackage, {+ marquee: { enabled: false },+ }),+ createPluginRegistration(SearchPluginPackage, {+ showAllResults: true,+ }),+ createPluginRegistration(ThumbnailPluginPackage, {+ width: THUMBNAIL_WIDTH,+ gap: THUMBNAIL_GAP,+ imagePadding: THUMBNAIL_IMAGE_PADDING,+ labelHeight: THUMBNAIL_LABEL_HEIGHT,+ paddingY: THUMBNAIL_PANE_PADDING_Y,+ buffer: 3,+ autoScroll: true,+ scrollBehavior: "auto",+ }),+ createPluginRegistration(ZoomPluginPackage, {+ defaultZoomLevel: defaultZoom,+ minZoom: ZOOM_OPTIONS[0],+ maxZoom: ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1],+ }),+ createPluginRegistration(RotatePluginPackage),+ ])++ if (engineError) {+ return (<div- ref={viewerShellRef}- className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"+ data-slot="pdf-viewer"+ className={cn(+ "grid h-full w-full place-items-center bg-background p-6 text-sm text-muted-foreground",+ className+ )}>- {!hasPdfFile ? (- <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-center text-sm text-muted-foreground">- <div className="max-w-sm space-y-3">- <div className="font-medium text-foreground">- Upload a PDF to preview- </div>- <div>- Pass a PDF URL with the <code>file</code> prop or use the- upload control.- </div>- </div>- </div>+ Unable to load the PDF engine.+ </div>+ )+ }++ if (!engine) {+ return (+ <div+ data-slot="pdf-viewer"+ className={cn(+ "relative flex h-full max-h-full min-h-0 w-full flex-col overflow-hidden bg-background",+ className+ )}+ >+ {showToolbar ? (+ <div className="min-h-12 border-b bg-background" />) : null}- {isLoading && !loadError ? (+ <div className="relative min-h-0 flex-1"><PDFViewerLoadingSkeleton- sidebarInline={sidebarInline}- sidebarOpen={sidebarOpen}+ sidebarInline+ sidebarOpen={defaultThumbnailSidebarOpen}/>- ) : null}- {loadError ? (- <div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-sm text-muted-foreground">- Unable to load the PDF preview.- </div>- ) : null}- {reactPdf && hasPdfFile ? (- <reactPdf.Document- file={pdfFile}- options={resolvedDocumentOptions}- className={cn(- "flex h-full min-h-0 w-full flex-1",- (isLoading || loadError) && "invisible"- )}- loading={null}- error={null}- onLoadStart={handleLoadStart}- onLoadSuccess={handleLoadSuccess}- onLoadError={handleLoadError}- onItemClick={({ pageNumber }) => scrollToPage(pageNumber)}- >- <div className="flex h-full max-h-full min-h-0 w-full flex-1 overflow-hidden">- <DocumentViewerThumbnailSidebar- inline={sidebarInline}- open={thumbnailSidebarVisible}- >- {thumbnailSidebarVisible ? (- <ScrollArea- className="h-full"- scrollFade- viewportRef={thumbnailViewportRef}- >- <div- className="relative"- style={{ height: thumbnailVirtualizer.getTotalSize() }}- >- {thumbnailVirtualizer- .getVirtualItems()- .map((virtualThumbnail) => {- const pageNumber =- renderedPageNumbers[virtualThumbnail.index]-- if (!pageNumber) return null-- const metrics = getPageMetrics(pageNumber)- const rotationDelta =- pageRotationDeltas.get(pageNumber) ?? 0- const effectiveRotation = normalizeRotation(- metrics.rotation + rotationDelta- )- const thumbnailDimensions = getPageDimensions(- metrics,- effectiveRotation- )- const thumbnailAspectRatio =- thumbnailDimensions.width /- thumbnailDimensions.height-- return (- <div- key={virtualThumbnail.key}- className="absolute top-0 right-4 left-4 flex justify-center [contain:layout_paint]"- style={{- transform: `translateY(${virtualThumbnail.start}px)`,- }}- >- <Button- data-pdf-viewer-thumbnail={pageNumber}- type="button"- variant="ghost"- size="sm"- className={cn(- "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",- pageNumber === activePage- ? "bg-sidebar-accent text-foreground"- : "text-muted-foreground"- )}- onFocus={(event) =>- event.currentTarget.blur()- }- onMouseDown={preserveThumbnailClickScroll}- onPointerDown={preserveThumbnailClickScroll}- onClick={() => scrollToPage(pageNumber)}- >- <PDFSidebarThumbnail- pageMetrics={metrics}- pageNumber={pageNumber}- reactPdf={reactPdf}- rotation={rotationDelta}- thumbnailAspectRatio={thumbnailAspectRatio}- />- {pageNumber}- </Button>- </div>- )- })}- </div>- </ScrollArea>- ) : null}- </DocumentViewerThumbnailSidebar>- <ScrollArea- className="h-full max-h-full min-h-0 min-w-0 flex-1"- viewportClassName={cn(- isFirstPageRendering && !loadError && "invisible"- )}- viewportRef={viewportRef}- >- <div- className="relative min-h-full min-w-full"- style={{- height: pageVirtualizer.getTotalSize(),- width:- maxEstimatedPageWidth + PAGE_VIRTUALIZER_PADDING * 2,- }}- >- {virtualPageItems.map((virtualPage) => {- const pageNumber = renderedPageNumbers[virtualPage.index]-- if (!pageNumber) return null-- const metrics = getPageMetrics(pageNumber)- const rotationDelta =- pageRotationDeltas.get(pageNumber) ?? 0- const effectiveRotation = normalizeRotation(- metrics.rotation + rotationDelta- )- const dimensions = getPageDimensions(- metrics,- effectiveRotation- )- const shouldRenderPage =- settledPageNumbers.has(pageNumber) ||- queuedPageNumbers.has(pageNumber)- const devicePixelRatioLimit =- (scrollState.isFastScrolling &&- !settledPageNumbers.has(pageNumber)) ||- lowResolutionPageNumbers.has(pageNumber)- ? 1- : MAX_DEVICE_PIXEL_RATIO- const pageStyle = {- width: dimensions.width * zoom,- height: dimensions.height * zoom,- }- const pageSearchQuery =- searchQuery.trim() &&- Math.abs(pageNumber - activePage) <= 1- ? searchQuery- : ""-- return (- <div- key={virtualPage.key}- className="absolute top-0 left-1/2 [contain:layout_paint]"- style={{- height: pageStyle.height,- transform: `translateX(-50%) translateY(${virtualPage.start}px)`,- width: pageStyle.width,- }}- >- <PDFViewerPage- devicePixelRatioLimit={devicePixelRatioLimit}- effectiveRotation={effectiveRotation}- reactPdf={reactPdf}- pageNumber={pageNumber}- pageStyle={pageStyle}- renderedPageWidth={pageStyle.width}- zoom={zoom}- shouldRenderPage={shouldRenderPage}- searchQuery={pageSearchQuery}- pageClassName={pageClassName}- renderPageOverlay={renderPageOverlay}- onPageSettled={handlePageSettled}- onPagePointerDown={onPagePointerDown}- onPagePointerMove={onPagePointerMove}- onPagePointerUp={onPagePointerUp}- onPagePointerCancel={onPagePointerCancel}- />- </div>- )- })}- </div>- </ScrollArea>- </div>- </reactPdf.Document>- ) : null}+ </div></div>- </div>+ )+ }++ return (+ <EmbedPDF engine={engine} plugins={plugins}>+ <PDFViewerDocumentLoader+ viewerRef={ref}+ pdfFile={pdfFile}+ defaultZoom={defaultZoom}+ className={className}+ defaultThumbnailSidebarOpen={defaultThumbnailSidebarOpen}+ downloadFileName={downloadFileName}+ showDownload={showDownload}+ showToolbar={showToolbar}+ showRotateControls={showRotateControls}+ showUpload={showUpload}+ toolbarActions={toolbarActions}+ pageClassName={pageClassName}+ renderPageOverlay={renderPageOverlay}+ onActivePageChange={onActivePageChange}+ onDocumentLoadSuccess={onDocumentLoadSuccess}+ onPdfUpload={onPdfUpload}+ onPagePointerDown={onPagePointerDown}+ onPagePointerMove={onPagePointerMove}+ onPagePointerUp={onPagePointerUp}+ onPagePointerCancel={onPagePointerCancel}+ onUploadFile={handleUploadFile}+ />+ </EmbedPDF>)})diff --git a/apps/v4/content/docs/components/docx-editor.mdx b/apps/v4/content/docs/components/docx-editor.mdxindex 34fbb94..ad022b3 100644--- a/apps/v4/content/docs/components/docx-editor.mdx+++ b/apps/v4/content/docs/components/docx-editor.mdx@@ -32,7 +32,7 @@ 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.7.0-alpha.3 @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.7.0-alpha.6 @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6```<Step>diff --git a/apps/v4/content/docs/components/docx-viewer.mdx b/apps/v4/content/docs/components/docx-viewer.mdxindex bb85bd6..2288277 100644--- a/apps/v4/content/docs/components/docx-viewer.mdx+++ b/apps/v4/content/docs/components/docx-viewer.mdx@@ -32,7 +32,7 @@ npx shadcn@latest add @extend/docx-viewer<Step>Install the following dependencies:</Step>```bash-npm install @extend-ai/react-docx@^0.7.0-alpha.3 @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6+npm install @extend-ai/react-docx@^0.7.0-alpha.6 @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6```<Step>Copy and paste the following code into your project.</Step>diff --git a/apps/v4/content/docs/components/file-system.mdx b/apps/v4/content/docs/components/file-system.mdxindex ce7d76c..2e852ba 100644--- a/apps/v4/content/docs/components/file-system.mdx+++ b/apps/v4/content/docs/components/file-system.mdx@@ -91,7 +91,7 @@ A `ListObjectsV2` response maps directly onto the manifest:## Thumbnails-Like [File Thumbnail](/docs/components/file-thumbnail), the component never parses documents and has no renderer dependencies. Generate preview images with whichever stack you already use — `react-pdf`, `@extend-ai/react-docx`, `@extend-ai/react-xlsx`, or a server-side pipeline — then pass the result through `previewImageUrl`. Files without a preview fall back to a generic document tile, or to the node returned by `renderFilePreview`.+Like [File Thumbnail](/docs/components/file-thumbnail), the component never parses documents and has no renderer dependencies. Generate preview images with whichever stack you already use — EmbedPDF, `@extend-ai/react-docx`, `@extend-ai/react-xlsx`, or a server-side pipeline — then pass the result through `previewImageUrl`. Files without a preview fall back to a generic document tile, or to the node returned by `renderFilePreview`.One caveat for DOCX: `@extend-ai/react-docx` versions before 0.7.0 rasterize pages in a way that taints the canvas, blocking `toDataURL` export in the browser. On 0.7.0+ the demo generates DOCX thumbnails client-side like the PDFs; on older versions, render DOCX previews live via `renderFilePreview` or generate thumbnail images server-side.@@ -141,9 +141,9 @@ The gallery view embeds the full viewers — PDF, DOCX, and XLSX files render in### Multi-Page Thumbnails-Pass `previewImageUrls` (an array of page thumbnails — page counts come from whichever renderer generates them, e.g. `react-pdf`, `@extend-ai/react-docx`, or `@extend-ai/react-xlsx`). Large thumbnails in the column preview show hover pager buttons to step through pages. `previewAspectRatio` on a file controls its thumbnail shape — e.g. natural ratios for images, landscape for spreadsheets.+Pass `previewImageUrls` (an array of page thumbnails — page counts come from whichever renderer generates them, e.g. EmbedPDF, `@extend-ai/react-docx`, or `@extend-ai/react-xlsx`). Large thumbnails in the column preview show hover pager buttons to step through pages. `previewAspectRatio` on a file controls its thumbnail shape — e.g. natural ratios for images, landscape for spreadsheets.-For long documents, provide only the first page(s) eagerly plus `previewPageCount`, and implement `loadPreviewImageUrl(file, pageIndex)` — the pager renders the remaining pages on demand (the demo renders PDF pages lazily through a cached `pdfjs` document).+For long documents, provide only the first page(s) eagerly plus `previewPageCount`, and implement `loadPreviewImageUrl(file, pageIndex)` — the pager renders the remaining pages on demand (the demo renders PDF pages lazily through the shared PDFium thumbnail utility).## API Referencediff --git a/apps/v4/content/docs/components/pdf-viewer.mdx b/apps/v4/content/docs/components/pdf-viewer.mdxindex a110e2e..9838653 100644--- a/apps/v4/content/docs/components/pdf-viewer.mdx+++ b/apps/v4/content/docs/components/pdf-viewer.mdx@@ -9,6 +9,10 @@ The React PDF Viewer is the core page-based document surface for document-heavy<PdfViewerDemo />+## About++PDF rendering is powered by [EmbedPDF](https://www.embedpdf.com/).+## Installation<CodeTabs>@@ -32,7 +36,7 @@ npx shadcn@latest add @extend/pdf-viewer<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 pdf-lib@^1.17.1 [email protected] react-pdf@^10.4.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 @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6 pdf-lib@^1.17.1```<Step>Copy and paste the following code into your project.</Step>@@ -47,33 +51,12 @@ npm install @hugeicons/core-free-icons@^4.2.0 @hugeicons/react@^1.1.6 @tanstack/</CodeTabs>-<Callout variant="info" title="Self-host PDF.js assets">-The viewer uses version-matched PDF.js CMaps and standard fonts from unpkg by-default so PDFs with CID fonts can render without extra setup. To avoid external-asset requests, copy `pdfjs-dist/cmaps` and `pdfjs-dist/standard_fonts` into-your public assets and pass `documentOptions`.--<DocsMdxCodeBlock- language="tsx"- copyButtonClassName="top-0.5"- code={`<PDFViewer- file="/path/to/document.pdf"- documentOptions={{- cMapPacked: true,- cMapUrl: "/pdfjs/cmaps/",- standardFontDataUrl: "/pdfjs/standard_fonts/",- }}-/>`}-/>--</Callout>-## Useful behaviors-- Zoom, fit width, fit page, rotate, and print/download actions.-- Virtualized page rendering for long PDFs.-- Optional OCR block overlays, e-signature fields, search highlights, and annotation layer.-- Text layer support for selection, copy, search, and accessibility.+- Zoom, rotate, and download actions.+- PDFium-backed page rendering for long PDFs.+- Optional OCR block overlays, e-signature fields, search highlights, and page overlays.+- Text selection, copy, search, and thumbnail navigation.## API Reference@@ -85,14 +68,12 @@ The PDFViewer component renders a scrollable PDF surface with toolbar controls,| ----------------------------- | ------------------------------------------------------------------------- | ------- | -------- || `file` | `string` | `-` | No || `className` | `string` | `-` | No |-| `documentOptions` | `ReactPdf.DocumentProps["options"]` | CDN | No || `defaultThumbnailSidebarOpen` | `boolean` | `false` | No |-| `defaultZoom` | `number` | `0.75` | No |-| `pageWidth` | `number` | `612` | No |-| `pageHeight` | `number` | `792` | No |-| `pageNumbers` | `number[]` | `-` | No |-| `pageRenderBuffer` | `number` | `4` | No |-| `setRenderRange` | `(visiblePagesRange: PDFViewerVisiblePagesRange) => PDFViewerRenderRange` | `-` | No |+| `defaultZoom` | `number` | `1` | No |+| `pageWidth` | `number` | `-` | No |+| `pageHeight` | `number` | `-` | No |+| `showDownload` | `boolean` | `true` | No |+| `showToolbar` | `boolean` | `true` | No || `showRotateControls` | `boolean` | `true` | No || `showUpload` | `boolean` | `true` | No || `toolbarActions` | `React.ReactNode` | `-` | No |diff --git a/apps/v4/next.config.mjs b/apps/v4/next.config.mjsindex 0a99d1a..ba1d93e 100644--- a/apps/v4/next.config.mjs+++ b/apps/v4/next.config.mjs@@ -43,11 +43,6 @@ const nextConfig = {turbopackFileSystemCacheForDev: true,},webpack: (config) => {- config.resolve.alias = {- ...config.resolve.alias,- "pdfjs-dist$": "pdfjs-dist/build/pdf.min.mjs",- }-config.experiments = {...config.experiments,asyncWebAssembly: true,diff --git a/apps/v4/package.json b/apps/v4/package.jsonindex 392799c..8dd0293 100644--- a/apps/v4/package.json+++ b/apps/v4/package.json@@ -22,7 +22,21 @@"@dnd-kit/core": "^6.3.1","@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2",- "@extend-ai/react-docx": "0.7.0-alpha.3",+ "@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",+ "@extend-ai/react-docx": "0.7.0-alpha.6","@extend-ai/react-xlsx": "0.10.2","@glideapps/glide-data-grid": "6.0.4-alpha24","@hugeicons/core-free-icons": "^4.2.0",@@ -48,11 +62,9 @@"nuqs": "^2.8.9","papaparse": "^5.5.3","pdf-lib": "^1.17.1",- "pdfjs-dist": "5.4.296","react": "19.2.3","react-dom": "19.2.3","react-markdown": "^10.1.0",- "react-pdf": "^10.4.1","react-resizable-panels": "^4.11.2","react-responsive-carousel": "^3.2.23","rehype-pretty-code": "^0.14.1",diff --git a/apps/v4/registry.json b/apps/v4/registry.jsonindex c9619c5..6cd8e83 100644--- a/apps/v4/registry.json+++ b/apps/v4/registry.json@@ -603,20 +603,31 @@"title": "PDF Viewer","description": "A PDF viewer with page virtualization, thumbnails, search, zoom, rotation, upload, and page overlay hooks.","dependencies": [+ "@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",- "@tanstack/react-virtual@^3.13.26",- "pdf-lib@^1.17.1",- "[email protected]",- "react-pdf@^10.4.1"+ "pdf-lib@^1.17.1"],"registryDependencies": ["button","@extend/document-viewer-sidebar",- "@extend/file-thumbnail","input","popover","scroll-area",+ "select","separator","spinner","tooltip",@@ -628,6 +639,11 @@"path": "components/ui/pdf-viewer.tsx","type": "registry:ui","target": "@ui/pdf-viewer.tsx"+ },+ {+ "path": "components/pdf-thumbnail-utils.ts",+ "type": "registry:component",+ "target": "@components/pdf-thumbnail-utils.ts"}]},@@ -637,7 +653,7 @@"title": "DOCX Viewer","description": "A DOCX viewer with upload, zoom, theme controls, and read-only rendering.","dependencies": [- "@extend-ai/react-docx@^0.7.0-alpha.3",+ "@extend-ai/react-docx@^0.7.0-alpha.6","@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],@@ -668,7 +684,7 @@"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.7.0-alpha.3",+ "@extend-ai/react-docx@^0.7.0-alpha.6","@hugeicons/core-free-icons@^4.2.0","@hugeicons/react@^1.1.6"],diff --git a/apps/v4/registry/new-york-v4/ui/bounding-box-citations.tsx b/apps/v4/registry/new-york-v4/ui/bounding-box-citations.tsxindex 1dd1ae8..db05cae 100644--- a/apps/v4/registry/new-york-v4/ui/bounding-box-citations.tsx+++ b/apps/v4/registry/new-york-v4/ui/bounding-box-citations.tsx@@ -1917,7 +1917,7 @@ function HumanReviewFieldCardBase({</div><spanclassName={cn(- "size-2 shrink-0 rounded-full bg-amber-400 transition-opacity",+ "size-2 shrink-0 rounded-full bg-amber-400",!modified && "opacity-0")}/>diff --git a/apps/v4/registry/new-york-v4/ui/layout-blocks.tsx b/apps/v4/registry/new-york-v4/ui/layout-blocks.tsxindex 4d7be90..4f250af 100644--- a/apps/v4/registry/new-york-v4/ui/layout-blocks.tsx+++ b/apps/v4/registry/new-york-v4/ui/layout-blocks.tsx@@ -8187,7 +8187,7 @@ const OcrBlockButton = React.memo(function OcrBlockButton({onMouseEnter={() => onFocusBlock(block)}onFocus={() => onFocusBlock(block)}className={cn(- "w-full rounded-lg border bg-background p-3 text-left transition-colors hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",+ "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",isActive && style.ring)}>diff --git a/pdf-viewer-selection-check.png b/pdf-viewer-selection-check.pngnew file mode 100644index 0000000..8eb11e1Binary files /dev/null and b/pdf-viewer-selection-check.png differdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2b9d264..692dfb0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -30,9 +30,51 @@ importers:'@dnd-kit/utilities':specifier: ^3.2.2version: 3.2.2([email protected])+ '@embedpdf/core':+ specifier: ^2.14.4+ version: 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/engines':+ specifier: ^2.14.4+ version: 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models':+ specifier: ^2.14.4+ version: 2.14.4+ '@embedpdf/plugin-document-manager':+ specifier: ^2.14.4+ version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-interaction-manager':+ specifier: ^2.14.4+ version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-render':+ specifier: ^2.14.4+ version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-rotate':+ specifier: ^2.14.4+ version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-scroll':+ specifier: ^2.14.4+ version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-search':+ specifier: ^2.14.4+ version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-selection':+ specifier: ^2.14.4+ version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-thumbnail':+ specifier: ^2.14.4+ version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-tiling':+ specifier: ^2.14.4+ version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-viewport':+ specifier: ^2.14.4+ version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-zoom':+ specifier: ^2.14.4+ version: 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@extend-ai/react-docx':- specifier: 0.7.0-alpha.3+ specifier: 0.7.0-alpha.6'@extend-ai/react-xlsx':specifier: 0.10.2@@ -62,7 +104,7 @@ importers:'@vercel/analytics':specifier: ^2.0.1- version: 2.0.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 2.0.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))border-beam:specifier: ^1.0.1@@ -108,9 +150,6 @@ importers:pdf-lib:specifier: ^1.17.1version: 1.17.1- pdfjs-dist:- specifier: 5.4.296- version: 5.4.296react:specifier: 19.2.3version: 19.2.3@@ -120,9 +159,6 @@ importers:react-markdown:specifier: ^10.1.0version: 10.1.0(@types/[email protected])([email protected])- react-pdf:- specifier: ^10.4.1- version: 10.4.1(@types/[email protected])([email protected]([email protected]))([email protected])react-resizable-panels:specifier: ^4.11.2@@ -162,7 +198,7 @@ importers:devDependencies:'@ianvs/prettier-plugin-sort-imports':specifier: ^4.4.1- version: 4.6.1([email protected])+ version: 4.6.1(@vue/[email protected])([email protected])'@tailwindcss/postcss':specifier: ^4.2.4version: 4.2.4@@ -192,7 +228,7 @@ importers:version: 3.6.2prettier-plugin-tailwindcss:specifier: ^0.7.2+ version: 0.7.2(@ianvs/[email protected](@vue/[email protected])([email protected]))([email protected])tailwindcss:specifier: ^4version: 4.1.18@@ -482,6 +518,178 @@ packages:peerDependencies:'@noble/ciphers': ^1.0.0+ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-trrFhKePk1JnAS8Vd+NWrS1fU2SIj3sifwawho/MeWKTkferLLuBay96ccA4S/Q5D7glKNH//M58VRgns09P3A==}+ peerDependencies:+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-1kWYvrxjpKr5QUt16r93pLQOLoWEuzD447OViwZyRECsZ8ePoTnErlNlxHiTkeAWBgwr4DD7Xd+2VkTdMAacNA==}+ peerDependencies:+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-SnGvQb+LwPZQO2WjjvlmXrJZolJUfLYbLZQSaYUw1vrQyMyJKT4LewvJGG+hZ+Yz2fz7OMIQ+4Gc98mGODZtOg==}++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-5HVAKGL7VqPeTxxADDrSqAFBxfmAXdP8fIqrPwJIKkqdK2643bOer8CqnnpO3/nPoFhkzxhttWMB9BGiqSW62w==}++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-BY2tv/mcICUUKf+M/bizf3RU65PMqKClJ/e5o9mgMibxyML0OQvEDwYMRPODQkKgJKXCO3ScHmVvcmXp6kt+fA==}++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-bh88HXSvOBS581kgmihWY7Ijp9hBsvlmXogFG5LSNx9UBAobRcakZiFMGieRBc06hUSkpo7WhjaFM/z/SfQ8dQ==}++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-LLYysdr8O6sRNzhmW3PbF3AeA8xnqvOi4XLFfIfNlW5uEZ+qsJdcfd78Q78sFJMhlaOAYFMziMMsnOzmx463rA==}++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-ETXl7XCwaQLSSvMO3EUDwMNqtL64kX2LlFxarTRi/NsIGGOIxUurGfKtrkmtnKHrWy1jAJSt6oxK2uJhvdvQIw==}++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-rGZJbVD6DYS5BbXdpEMnWkpVF0Knar+bsiyb2o3+YRx7O8eyFubEBQUSUInirQk69HA6fc3GhYCg7TyC/oD76Q==}++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-RlxazYdS1ObWe3Rt78pVUXSqQEMeOb1oHFA0CT3aolwtVooZyop9XO3WTDWpEaGvGrHXvuSv7WQgcCLZ2zKyaQ==}++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-0tDPQEH1WtfXcASNVp5U3dqfzZboNvcE4rDok/P4JCN+DCTaJDG2E9lYHGMo9FtuS2IdHgrzkmPRpOo5WV9MKQ==}++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-1qUKu/RAN9LV+Ih7geig0X/2i4jIn8P1D0I0nQUwSMM9hJmitcyDJ/9SK/eOSsdEs4SulIqt+a2W2IMZOY2Vew==}+ peerDependencies:+ '@embedpdf/core': 2.14.4+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-y4MeHBy5s/SR5ma4rezYADIUujViAZSQe8A/CKehve4eU6Z9YF2AflL/M6KG24gCsUyW4D04AxAn3bvsXLR3nw==}+ peerDependencies:+ '@embedpdf/core': 2.14.4+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-KNY3EGYf9SRqtDBOEO9mR3Hyv9mN8TaC3ztERj0BX8zra7mkjkQnhGQlMxif1dGOoTD9XIcPqJvaw8o7PWDJDw==}+ peerDependencies:+ '@embedpdf/core': 2.14.4+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-+bBBHfoSMBMjHubDgPkCCu3o2NZn5vv8l/2gmzH6D8k90UVLB2AOei9VTmfy5xqoit+eoY6iSl7w3qyijNfB0A==}+ peerDependencies:+ '@embedpdf/core': 2.14.4+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-0JgPwnQqB9THKJt/mOubgFkiTcCkOI6kFCZz8zlwl88DAJcUbdhJoTwCJZ2STYSfECTLB4ZFjb5fZ9AXyfkf0g==}+ peerDependencies:+ '@embedpdf/core': 2.14.4+ '@embedpdf/plugin-viewport': 2.14.4+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-ErRlg0MKLxZ0c4OKk5RjPOV8f8yCaqFi6zqUxBI49/3yN6wDINKvm8dxt5Q2QGUa740n/XylT5BTbjH6lAjCzQ==}+ peerDependencies:+ '@embedpdf/core': 2.14.4+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-8w6ZUdwRcBhNCQjlS8mFvsMXI/wr1Q7DljwlFmKaEQyM9vXm2rI9WGN0z9ffjKHlsYn0yg98pqyPLtTevH1P7Q==}+ peerDependencies:+ '@embedpdf/core': 2.14.4+ '@embedpdf/plugin-interaction-manager': 2.14.4+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-80D+R2uXoTsmQXFpGGhtapv3I45WNzTSIkcD3VvLywjS2MHwgCNY51RQsn5bc3HINZW9d/SX1F39qiv4HzPp6A==}+ peerDependencies:+ '@embedpdf/core': 2.14.4+ '@embedpdf/plugin-render': 2.14.4+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-++1bzvU0Xqi6a1XeUOLAHU7D/FVUNobC/behSSn3WZnY/wIpYG3dXs5NbhNzeomIGXYHC4jCXbKGBPe5TNdoSw==}+ peerDependencies:+ '@embedpdf/core': 2.14.4+ '@embedpdf/plugin-render': 2.14.4+ '@embedpdf/plugin-scroll': 2.14.4+ '@embedpdf/plugin-viewport': 2.14.4+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-ZhbDITPZ/h1Vd9cUbCPShSbH5RXd/biCw9w6fneTItruMauYIcTNUS2eWLJC0Yovhw7nu0TjRVYuTQ71jzs0dg==}+ peerDependencies:+ '@embedpdf/core': 2.14.4+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-a5kUjbG9sKMyO8qqDTrtL30VJ3dSEyNHHvszhfbvKtv4hppz/fSKS78vieu3lw48K11BoioImzCAF6Y3R0LMiw==}+ peerDependencies:+ '@embedpdf/core': 2.14.4+ '@embedpdf/plugin-scroll': 2.14.4+ '@embedpdf/plugin-viewport': 2.14.4+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'++ '@embedpdf/[email protected]':+ resolution: {integrity: sha512-W7BZSNAQeUPQhi6l96Q4oFtg8Vgbt622LQL5ql0oZjyJNJRbYqCJIiJpR+5ZvK6S/x2MadZnYSzBJ/ekL6394A==}+ peerDependencies:+ preact: ^10.26.4+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ svelte: '>=5 <6'+ vue: '>=3.2.0'+'@emnapi/[email protected]':resolution: {integrity: sha512-XsLw1dEOpkSX/WucdqUhPWP7hDxSvZiY+fsUC14h+FtQ2Ifni4znbBt8punRX+Uj2JG/uDb8nEHVKvrVlvdZ5Q==}@@ -847,8 +1055,8 @@ packages:resolution: {integrity: sha512-ZAoA40rNMPwSm+AeHpCq8STiNAwzWLJuP8Xv4CHIc9wv/PSuExjMrmjfYNj682vW0OOiZ1HKxzvjQr9XZIisQA==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}- '@extend-ai/[email protected]':- resolution: {integrity: sha512-JjTHCi09/SkBPBlphAY8G6wjkJoyG/zoMKxMQlj7jRyAXrK6LH1S/aH2mjN8n1aSDQ9zYS0pFVG8uN+AiugM5A==}+ '@extend-ai/[email protected]':+ resolution: {integrity: sha512-CxAd1oFR06U9CrIe2VOYBTKPL+IScmgzrZqpsOQd9xgqGoyekl84xSnGlcPqKs6I9jr51wv7amOs7LiDLFdn0A==}peerDependencies:react: '>=18'react-dom: '>=18'@@ -1159,76 +1367,6 @@ packages:resolution: {integrity: sha512-VVPPgHyQ6ShqnrmDWuxjmUIsO9gWyOZFmuOfLd9LfBGQJwZfy0gvv9pbHSJuoFNIYC7ZDX9aoFwowjcdSC4E8w==}engines: {node: '>=18'}- '@napi-rs/[email protected]':- resolution: {integrity: sha512-hjhCKhntPv9+t4ckHymdx0phYNcVW+GKQR6Lzw2zE+pOVjOplSmtx9nNNknTjbEDLcuLZqA1y8ufKg1XfgftzQ==}- engines: {node: '>= 10'}- cpu: [arm64]- os: [android]-- '@napi-rs/[email protected]':- resolution: {integrity: sha512-2PcswRaC7Ly645DGt88///zuFDhJxJYdKAs1uU3mfk1atYkXufgcgLfBpk6Tm12nCQBaNt1wpybuPZ4qOhTo8A==}- engines: {node: '>= 10'}- cpu: [arm64]- os: [darwin]-- '@napi-rs/[email protected]':- resolution: {integrity: sha512-ePNZtj7pNIva/siZMg+HmbeozkIjqUIYdoymH8HaA3qK7LfzFN4WMBM8G6HQ9ZC+H3+Dnn5pqtiXpgLykaPOhw==}- engines: {node: '>= 10'}- cpu: [x64]- os: [darwin]-- '@napi-rs/[email protected]':- resolution: {integrity: sha512-d5cDB48oWFGU8/XPhUOFAlySgb/VAu7D+s8fi55K1Pcfg8aPplHWqMgibhVLU8ky7Pyg/fuiVLz4Nf3JrSTuUA==}- engines: {node: '>= 10'}- cpu: [arm]- os: [linux]-- '@napi-rs/[email protected]':- resolution: {integrity: sha512-rDxgxRu69RvDlX/bh9o22DxLsGr8EqsNgotL9+RwQE1S0b0cqeatqsw6aW45mukm0B42DIAaAacKaYQ8cqS1nw==}- engines: {node: '>= 10'}- cpu: [arm64]- os: [linux]-- '@napi-rs/[email protected]':- resolution: {integrity: sha512-K3mDW66N+xT2/V439u1alFANiBUjdEx2gLiNYnCmUsva5jZMxWTjafBYwTzYK+EMFMHrUoabuU+T1BIP5CgbYQ==}- engines: {node: '>= 10'}- cpu: [arm64]- os: [linux]-- '@napi-rs/[email protected]':- resolution: {integrity: sha512-mooqUBTIsccZpnoQC4NgrC1v6C1vof39etLNMnBwCY+p0gajWJvAHLGQ6g/gGyS5YrpDW+GefSN4+Cvcr08UWw==}- engines: {node: '>= 10'}- cpu: [riscv64]- os: [linux]-- '@napi-rs/[email protected]':- resolution: {integrity: sha512-1eCvkDCazm7FFhsT7DfGOdSaHgZVK3bt/dSBl5EWHOWmnz+I7j8tPseJqqD81NF+MH21jKUK4wQSDjN0mdhnTg==}- engines: {node: '>= 10'}- cpu: [x64]- os: [linux]-- '@napi-rs/[email protected]':- resolution: {integrity: sha512-20arT6lnI19S68qNlii73TSEDbECNgzMz2EpldC1V3mZFuRkeujXkcebRk0LRJe9SEUAooYiLokfMViY8IX7yA==}- engines: {node: '>= 10'}- cpu: [x64]- os: [linux]-- '@napi-rs/[email protected]':- resolution: {integrity: sha512-DZFFT1wIAg37LJw37yhMRFfjATd3vTQzjZ1Yki8u2vhO6Hi5VE6BVaGQ1aaDu7xb4iMErz+9EOwjpS7xcxFeBw==}- engines: {node: '>= 10'}- cpu: [arm64]- os: [win32]-- '@napi-rs/[email protected]':- resolution: {integrity: sha512-MyT1j3mHC2+Lu4pBi9mKyMJhtP6U7k7EldY7sj/uS5gJA65gTXt8MefJQXLJo5d/vZbuWmfxzkEUNc/urV3pHA==}- engines: {node: '>= 10'}- cpu: [x64]- os: [win32]-- '@napi-rs/[email protected]':- resolution: {integrity: sha512-xglYA6q3XO5P3BNJYxVZ1IV7DLVjp1Py6nwag88YntrS+3vKHyYcMqXVS4ZztJmwz2uGvz1FWhI/4LgbR5uQDA==}- engines: {node: '>= 10'}-'@napi-rs/[email protected]':resolution: {integrity: sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ==}@@ -1747,6 +1885,11 @@ packages:'@standard-schema/[email protected]':resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}+ '@sveltejs/[email protected]':+ resolution: {integrity: sha512-4WfKk68eTih+MiJD4fSbxN7E8kVBmTMPWHUPYjvl2N0rMs53YLTT8/YjKU5Dtnz5LqDjl7LEw4U7lXR2W3J5WA==}+ peerDependencies:+ acorn: ^8.9.0+'@swc/[email protected]':resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==}@@ -1908,6 +2051,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-xMAgYwceFhRA2zY+XbEA7mxYbA093wdiW8Vu6gZPGWy9cmOyU9XesH1tNcEWsKFd5Vzrqx5T3D38PWx1FIIXkA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}+'@types/[email protected]':resolution: {integrity: sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==}@@ -2104,6 +2250,35 @@ packages:vue-router:optional: true+ '@vue/[email protected]':+ resolution: {integrity: sha512-s99aGxWYig9ErHbct27KXEGhrBYlRI6c4MwAgXErOAbX9xiW37/uMa+XUDO69zLz83dng8UUZ70CTOJrLrYrEQ==}++ '@vue/[email protected]':+ resolution: {integrity: sha512-JTqp25l8aFfJYF7/KmsXZjAxJz7T+SjmTJLoXVjHtc2BrSgSiW2n9Aem/cWq1OPe68A8JL06B3eVdhlP0H4TVw==}++ '@vue/[email protected]':+ resolution: {integrity: sha512-DuA2GiZawSEW442iw/9+Fkol8hTgb4Ke5KkhmSry65QA7YuyMbIdy8p0XZRMvNwJdgRz307W8g1CSzdvS4nuNg==}++ '@vue/[email protected]':+ resolution: {integrity: sha512-7s+W5Gc42FGxZMcuwl8H5B29T8BJPMdBT7KHFE+BbAuZ/iTEdTtv7z2XiMjiaUUw4w3ZcCEdHs36RuYJ2VA7bA==}++ '@vue/[email protected]':+ resolution: {integrity: sha512-pG6LV/NDNRbKizcUjFFLAfjaL8mcv4DmR9avNcUw2gDHBzZneuS2TWCmp633ynzxz9YYKNeEPK2I8Wraqy2HUQ==}++ '@vue/[email protected]':+ resolution: {integrity: sha512-iyW8WVfF1CpCXxncZY5Ei6rSd6oZr5DgEom//fUjRBRl56AXPD+s9ATvukRt77ZFTuYlnVA1bxY+dJB94tWVYw==}++ '@vue/[email protected]':+ resolution: {integrity: sha512-apX2wt9sdfDshS+a2xueFZLVpt0GkRJZSoPmrW/SA4yzXTznhfcMVW59gr7h4YQeY0vJhdJkk2rsIDwgfFgC5A==}++ '@vue/[email protected]':+ resolution: {integrity: sha512-vue8vbf2QlV4quHqzwmJy6dWfmRhP1J8l4wtZg60CL6VoKqcPY2oe7may3+1d9qfpedjK5PRLFqd5k3Isj9mUw==}+ peerDependencies:+ vue: 3.5.38++ '@vue/[email protected]':+ resolution: {integrity: sha512-FTW0AFZNaK5/mOqvGBwVfUlNLU38TiQn4+DQgIFUnrBBJQ1crMJ82yeGQLV5jyKFsO8yRukpbuP7x+nRbH6aug==}+'@wyw-in-js/[email protected]':resolution: {integrity: sha512-5YAZMUmF+S2HaqheKfew6ybbYBMnF10PjIgI7ieyuFxCohyqJNF4xdo6oHftv2z5Z4vCQ0OZHtDOQyDImBYwmg==}engines: {node: '>=16.0.0'}@@ -2167,6 +2342,10 @@ packages:resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==}engines: {node: '>=10'}+ resolution: {integrity: sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==}+ engines: {node: '>= 0.4'}+resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==}engines: {node: '>= 0.4'}@@ -2583,6 +2762,9 @@ packages:resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==}+ resolution: {integrity: sha512-4CXDYRBGqN+57wVJkuXBYmpAVUSg3L6JAQa/DFqm238G73E1wuyc/JhGQJzN7vUf/CMphYau2zXbfWzDR5aTEw==}+resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}@@ -2640,6 +2822,10 @@ packages:resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==}engines: {node: '>=0.12'}+ resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}+ engines: {node: '>=0.12'}+resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}engines: {node: '>=6'}@@ -2810,6 +2996,9 @@ packages:jiti:optional: true+ resolution: {integrity: sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==}+resolution: {integrity: sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}@@ -2823,6 +3012,14 @@ packages:resolution: {integrity: sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==}engines: {node: '>=0.10'}+ resolution: {integrity: sha512-gPdx+I+BjYEinNMQaBXFjbaJVyoPMU4ZODg5mE+M4DqVG9VusAVHHjcBX+zqyITlI0DIARwDMMzZwAWj36dRoQ==}+ peerDependencies:+ '@typescript-eslint/types': ^8.2.0+ peerDependenciesMeta:+ '@typescript-eslint/types':+ optional: true+resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==}engines: {node: '>=4.0'}@@ -2852,6 +3049,9 @@ packages:resolution: {integrity: sha512-m5KgiH85xAhhW8Wta0vShLcUvOsh3LLPI2YVwcbio1l7E09NTLL1EyMZFM1OyWowoH0skScNbhOPl4kcBgzTww==}+ resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==}+resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}@@ -3417,6 +3617,9 @@ packages:resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==}+ resolution: {integrity: sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==}+resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==}engines: {node: '>= 0.4'}@@ -3657,6 +3860,9 @@ packages:resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}+ resolution: {integrity: sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==}+resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==}engines: {node: '>=10'}@@ -3696,12 +3902,6 @@ packages:resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}- resolution: {integrity: sha512-3SEQqTpV9oqVsIWqAcmDuaNeo7yBO3tqPtqGRcKkEo0lrzD3wqbKG9mkxO65KoOgXqj+zH2phJ2LiAsdzlogSw==}-- resolution: {integrity: sha512-G/hncXrl4Qt7mauJEXSg3AcdYzmpkIITTNl5I+rH9sog5Yw0kK6vseJjCaPfOXqOqQuPUP89Rkhfz5kPS8ijtw==}-resolution: {integrity: sha512-o5vL7aDWatOTX8LzaS1WMoaoxIiLRQJuIKKe2wAw6IeULDHaqbiqiggmx+pKvZDb1Sj+pE46Sn1T7lCqfFtg1Q==}engines: {node: '>=16'}@@ -3774,14 +3974,6 @@ packages:resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==}engines: {node: '>=18'}- resolution: {integrity: sha512-3+B21mYK2IqUWnd2EivABLT7ueDhb0b8/dGK8LoFQPrU61YITeCMn14F7y7qZafWNZhUEKb24cJdiT5Wxs3prg==}- peerDependencies:- '@types/react': 19.2.2- peerDependenciesMeta:- '@types/react':- optional: true-resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==}@@ -3950,6 +4142,11 @@ packages:engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}hasBin: true+ resolution: {integrity: sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==}+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}+ hasBin: true+resolution: {integrity: sha512-uTp172LLXSxuSYHv/kou+f6KW3SMppU9ivthaVTXian9sOt3XM/zHYHpRZiLgQoxeWfYUnslNWQHF1+G71xcow==}engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0}@@ -4179,10 +4376,6 @@ packages:resolution: {integrity: sha512-V/mpyJAoTsN4cnP31vc0wfNA1+p20evqqnap0KLoRUN0Yk/p3wN52DOEsL4oBFcLdb76hlpKPtzJIgo67j/XLw==}- resolution: {integrity: sha512-DlOzet0HO7OEnmUmB6wWGJrrdvbyJKftI1bhMitK7O2N8W2gc757yyYBbINy9IDafXAV9wmKr9t7xsTaNKRG5Q==}- engines: {node: '>=20.16.0 || >=22.3.0'}-resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}@@ -4214,6 +4407,10 @@ packages:resolution: {integrity: sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==}engines: {node: ^10 || ^12 || >=14}+ resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==}+ engines: {node: ^10 || ^12 || >=14}+resolution: {integrity: sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==}engines: {node: ^10 || ^12 || >=14}@@ -4358,16 +4555,6 @@ packages:react: ^0.14 || ^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0react-dom: ^0.14 || ^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0- resolution: {integrity: sha512-kS/35staVCBqS29verTQJQZXw7RfsRCPO3fdJoW1KXylcv7A9dw6DZ3vJXC2w+bIBgLw5FN4pOFvKSQtkQhPfA==}- peerDependencies:- '@types/react': 19.2.2- react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0- react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0- peerDependenciesMeta:- '@types/react':- optional: true-resolution: {integrity: sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==}engines: {node: '>=10'}@@ -4789,6 +4976,10 @@ packages:resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-w7JvrM5IFl5cmfbY0TLik9o7mjRUJmRMhOR51tBPu708Gr/MjbGs7VnJnr/B0CaXeI4vtnOh7RKxDr0cwhMdDA==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==}engines: {node: '>=20'}@@ -5103,8 +5294,13 @@ packages:yaml:optional: true- resolution: {integrity: sha512-rpJyN222KWIvHJ/F53XSZv0Zl/accqHR8et1kpaMTD/fLCRxtV8iX8czMzY7sVZupTI3zcUTg8eycS2kNF9l6w==}+ resolution: {integrity: sha512-vAMKHfImQlYSy0C+PBue4s3ERZ2xGKfgZg5GXAsLInq1dyh2H78ILVP5sK0KPFPVW4kv+OGCIvBEondcjpZp7A==}+ peerDependencies:+ typescript: '*'+ peerDependenciesMeta:+ typescript:+ optional: trueresolution: {integrity: sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==}@@ -5189,6 +5385,9 @@ packages:resolution: {integrity: sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug==}engines: {node: '>=18'}+ resolution: {integrity: sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==}+resolution: {integrity: sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==}peerDependencies:@@ -5561,6 +5760,178 @@ snapshots:dependencies:'@noble/ciphers': 1.3.0+ '@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/engines': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.14.4+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/fonts-arabic': 1.0.0+ '@embedpdf/fonts-hebrew': 1.0.0+ '@embedpdf/fonts-jp': 1.0.0+ '@embedpdf/fonts-kr': 1.0.0+ '@embedpdf/fonts-latin': 1.0.0+ '@embedpdf/fonts-sc': 1.0.0+ '@embedpdf/fonts-tc': 1.0.0+ '@embedpdf/models': 2.14.4+ '@embedpdf/pdfium': 2.14.4+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected]': {}++ '@embedpdf/[email protected]': {}++ '@embedpdf/[email protected]': {}++ '@embedpdf/[email protected]': {}++ '@embedpdf/[email protected]': {}++ '@embedpdf/[email protected]': {}++ '@embedpdf/[email protected]': {}++ '@embedpdf/[email protected]': {}++ '@embedpdf/[email protected]': {}++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.14.4+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.14.4+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.14.4+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.14.4+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.14.4+ '@embedpdf/plugin-viewport': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.14.4+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.14.4+ '@embedpdf/plugin-interaction-manager': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/utils': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.14.4+ '@embedpdf/plugin-render': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ ? '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'+ : dependencies:+ '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.14.4+ '@embedpdf/plugin-render': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-scroll': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-viewport': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.14.4+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ ? '@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'+ : dependencies:+ '@embedpdf/core': 2.14.4([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/models': 2.14.4+ '@embedpdf/plugin-scroll': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))(@embedpdf/[email protected](@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ '@embedpdf/plugin-viewport': 2.14.4(@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected])))([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@embedpdf/[email protected]([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':+ dependencies:+ preact: 11.0.0-beta.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])+'@emnapi/[email protected]':dependencies:'@emnapi/wasi-threads': 1.0.4@@ -5783,7 +6154,7 @@ snapshots:'@eslint/core': 0.13.0levn: 0.4.1dependencies:'@chenglou/pretext': 0.0.5@@ -5863,7 +6234,7 @@ snapshots:'@humanwhocodes/[email protected]': {}- '@ianvs/[email protected]([email protected])':dependencies:'@babel/generator': 7.28.0'@babel/parser': 7.28.0@@ -5871,6 +6242,8 @@ snapshots:'@babel/types': 7.28.2prettier: 3.6.2semver: 7.7.2+ optionalDependencies:+ '@vue/compiler-sfc': 3.5.38transitivePeerDependencies:- supports-color@@ -6120,54 +6493,6 @@ snapshots:outvariant: 1.4.3strict-event-emitter: 0.5.1- '@napi-rs/[email protected]':- optional: true-- '@napi-rs/[email protected]':- optional: true-- '@napi-rs/[email protected]':- optional: true-- '@napi-rs/[email protected]':- optional: true-- '@napi-rs/[email protected]':- optional: true-- '@napi-rs/[email protected]':- optional: true-- '@napi-rs/[email protected]':- optional: true-- '@napi-rs/[email protected]':- optional: true-- '@napi-rs/[email protected]':- optional: true-- '@napi-rs/[email protected]':- optional: true-- '@napi-rs/[email protected]':- optional: true-- '@napi-rs/[email protected]':- optionalDependencies:- '@napi-rs/canvas-android-arm64': 0.1.100- '@napi-rs/canvas-darwin-arm64': 0.1.100- '@napi-rs/canvas-darwin-x64': 0.1.100- '@napi-rs/canvas-linux-arm-gnueabihf': 0.1.100- '@napi-rs/canvas-linux-arm64-gnu': 0.1.100- '@napi-rs/canvas-linux-arm64-musl': 0.1.100- '@napi-rs/canvas-linux-riscv64-gnu': 0.1.100- '@napi-rs/canvas-linux-x64-gnu': 0.1.100- '@napi-rs/canvas-linux-x64-musl': 0.1.100- '@napi-rs/canvas-win32-arm64-msvc': 0.1.100- '@napi-rs/canvas-win32-x64-msvc': 0.1.100- optional: true-'@napi-rs/[email protected]':dependencies:'@emnapi/core': 1.4.5@@ -6604,6 +6929,10 @@ snapshots:'@standard-schema/[email protected]': {}+ '@sveltejs/[email protected]([email protected])':+ dependencies:+ acorn: 8.15.0+'@swc/[email protected]':dependencies:tslib: 2.8.1@@ -6751,6 +7080,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}@@ -6909,10 +7240,66 @@ snapshots:'@unrs/[email protected]':optional: true- '@vercel/[email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])':+ '@vercel/[email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))':optionalDependencies:next: 16.2.9(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])react: 19.2.3+ svelte: 5.56.3(@typescript-eslint/[email protected])+ vue: 3.5.38([email protected])++ '@vue/[email protected]':+ dependencies:+ '@babel/parser': 7.29.7+ '@vue/shared': 3.5.38+ entities: 7.0.1+ estree-walker: 2.0.2+ source-map-js: 1.2.1++ '@vue/[email protected]':+ dependencies:+ '@vue/compiler-core': 3.5.38+ '@vue/shared': 3.5.38++ '@vue/[email protected]':+ dependencies:+ '@babel/parser': 7.29.7+ '@vue/compiler-core': 3.5.38+ '@vue/compiler-dom': 3.5.38+ '@vue/compiler-ssr': 3.5.38+ '@vue/shared': 3.5.38+ estree-walker: 2.0.2+ magic-string: 0.30.21+ postcss: 8.5.15+ source-map-js: 1.2.1++ '@vue/[email protected]':+ dependencies:+ '@vue/compiler-dom': 3.5.38+ '@vue/shared': 3.5.38++ '@vue/[email protected]':+ dependencies:+ '@vue/shared': 3.5.38++ '@vue/[email protected]':+ dependencies:+ '@vue/reactivity': 3.5.38+ '@vue/shared': 3.5.38++ '@vue/[email protected]':+ dependencies:+ '@vue/reactivity': 3.5.38+ '@vue/runtime-core': 3.5.38+ '@vue/shared': 3.5.38+ csstype: 3.2.3++ dependencies:+ '@vue/compiler-ssr': 3.5.38+ '@vue/shared': 3.5.38+ vue: 3.5.38([email protected])++ '@vue/[email protected]': {}'@wyw-in-js/[email protected]':dependencies:@@ -6976,6 +7363,8 @@ snapshots:dependencies:tslib: 2.8.1+ [email protected]: {}+@@ -7372,6 +7761,8 @@ snapshots:+ [email protected]: {}+dependencies:dequal: 2.0.3@@ -7423,6 +7814,8 @@ snapshots:+ [email protected]: {}+@@ -7803,6 +8196,8 @@ snapshots:- hono- supports-color+ [email protected]: {}+dependencies:acorn: 8.15.0@@ -7815,6 +8210,12 @@ snapshots:dependencies:estraverse: 5.3.0+ [email protected](@typescript-eslint/[email protected]):+ dependencies:+ '@jridgewell/sourcemap-codec': 1.5.5+ optionalDependencies:+ '@typescript-eslint/types': 8.59.1+dependencies:estraverse: 5.3.0@@ -7854,6 +8255,8 @@ snapshots:'@types/estree-jsx': 1.0.5'@types/unist': 3.0.3+ [email protected]: {}+dependencies:'@types/estree': 1.0.8@@ -8520,6 +8923,10 @@ snapshots:+ dependencies:+ '@types/estree': 1.0.8+dependencies:call-bound: 1.0.4@@ -8708,6 +9115,8 @@ snapshots:+ [email protected]: {}+dependencies:p-locate: 5.0.0@@ -8744,10 +9153,6 @@ snapshots:dependencies:'@jridgewell/sourcemap-codec': 1.5.5- [email protected]: {}-- [email protected]: {}-@@ -8923,10 +9328,6 @@ snapshots:- [email protected](@types/[email protected]):- optionalDependencies:- '@types/react': 19.2.2-@@ -9255,6 +9656,8 @@ snapshots:+ [email protected]: {}+@@ -9496,10 +9899,6 @@ snapshots:pako: 1.0.11tslib: 1.14.1- optionalDependencies:- '@napi-rs/canvas': 0.1.100-@@ -9523,6 +9922,12 @@ snapshots:picocolors: 1.1.1source-map-js: 1.2.1+ dependencies:+ nanoid: 3.3.12+ picocolors: 1.1.1+ source-map-js: 1.2.1+dependencies:nanoid: 3.3.11@@ -9539,11 +9944,11 @@ snapshots:+ [email protected](@ianvs/[email protected](@vue/[email protected])([email protected]))([email protected]):dependencies:prettier: 3.6.2optionalDependencies:- '@ianvs/prettier-plugin-sort-imports': 4.6.1([email protected])+ '@ianvs/prettier-plugin-sort-imports': 4.6.1(@vue/[email protected])([email protected])@@ -9624,21 +10029,6 @@ snapshots:react: 19.2.3react-dom: 19.2.3([email protected])- [email protected](@types/[email protected])([email protected]([email protected]))([email protected]):- dependencies:- clsx: 2.1.1- dequal: 2.0.3- make-cancellable-promise: 2.0.0- make-event-props: 2.0.0- merge-refs: 2.0.0(@types/[email protected])- pdfjs-dist: 5.4.296- react: 19.2.3- react-dom: 19.2.3([email protected])- tiny-invariant: 1.3.3- warning: 4.0.3- optionalDependencies:- '@types/react': 19.2.2-dependencies:react: 19.2.3@@ -10282,6 +10672,27 @@ snapshots:+ [email protected](@typescript-eslint/[email protected]):+ dependencies:+ '@jridgewell/remapping': 2.3.5+ '@jridgewell/sourcemap-codec': 1.5.5+ '@sveltejs/acorn-typescript': 1.0.10([email protected])+ '@types/estree': 1.0.8+ '@types/trusted-types': 2.0.7+ acorn: 8.15.0+ aria-query: 5.3.1+ axobject-query: 4.1.0+ clsx: 2.1.1+ devalue: 5.8.1+ esm-env: 1.2.2+ esrap: 2.2.11(@typescript-eslint/[email protected])+ is-reference: 3.0.3+ locate-character: 3.0.0+ magic-string: 0.30.21+ zimmerframe: 1.1.4+ transitivePeerDependencies:+ - '@typescript-eslint/types'+@@ -10596,7 +11007,7 @@ snapshots:esbuild: 0.27.7fdir: 6.5.0([email protected])picomatch: 4.0.4- postcss: 8.5.8+ postcss: 8.5.15rollup: 4.60.1tinyglobby: 0.2.15optionalDependencies:@@ -10608,9 +11019,15 @@ snapshots:yaml: 2.8.1optional: truedependencies:- loose-envify: 1.4.0+ '@vue/compiler-dom': 3.5.38+ '@vue/compiler-sfc': 3.5.38+ '@vue/runtime-dom': 3.5.38+ '@vue/server-renderer': 3.5.38([email protected]([email protected]))+ '@vue/shared': 3.5.38+ optionalDependencies:+ typescript: 5.9.2@@ -10709,6 +11126,8 @@ snapshots:+ [email protected]: {}+dependencies:zod: 3.25.76