TypeScript
Restore runtime file-system thumbnails
Andrew Luoaf97843022d4
diff --git a/apps/v4/app/(app)/(root)/page.tsx b/apps/v4/app/(app)/(root)/page.tsxindex 5d2fe1e..3ab348a 100644--- a/apps/v4/app/(app)/(root)/page.tsx+++ b/apps/v4/app/(app)/(root)/page.tsx@@ -10,7 +10,6 @@ import {} from "@/components/page-header"import {MobileRootPreview,- RootBlocksShowcase,RootComponentsCollage,} from "@/components/root-components-collage"import { RootLiquidLogo } from "@/components/root-liquid-logo"@@ -52,7 +51,7 @@ export default function IndexPage() {return (<div className="flex flex-1 flex-col"><PageHeader className="relative overflow-hidden">- <RootLiquidLogo />+ {/* <RootLiquidLogo /> */}<PageHeaderHeading className="relative z-10 mt-2 max-w-4xl sm:mt-3">{title}</PageHeaderHeading>@@ -88,9 +87,6 @@ export default function IndexPage() {<section><RootComponentsCollage /></section>- <section className="mt-12">- <RootBlocksShowcase />- </section></div></div></div>diff --git a/apps/v4/app/layout.tsx b/apps/v4/app/layout.tsxindex cd594bf..4c6feac 100644--- a/apps/v4/app/layout.tsx+++ b/apps/v4/app/layout.tsx@@ -7,7 +7,6 @@ import { META_THEME_COLORS, siteConfig } from "@/lib/config"import { fontVariables } from "@/lib/fonts"import { cn } from "@/lib/utils"import { withUiBasePath } from "@/lib/zone-path"-import { LayoutProvider } from "@/hooks/use-layout"import { Toaster } from "@/components/ui/sonner"import { TooltipProvider } from "@/components/ui/tooltip"import { ActiveThemeProvider } from "@/components/active-theme"@@ -92,9 +91,6 @@ export default function RootLayout({if (localStorage.theme === 'dark' || ((!('theme' in localStorage) || localStorage.theme === 'system') && window.matchMedia('(prefers-color-scheme: dark)').matches)) {document.querySelector('meta[name="theme-color"]').setAttribute('content', '${META_THEME_COLORS.dark}')}- if (localStorage.layout) {- document.documentElement.classList.add('layout-' + localStorage.layout)- }} catch (_) {}`,}}@@ -107,17 +103,15 @@ export default function RootLayout({)}><ThemeProvider>- <LayoutProvider>- <ActiveThemeProvider>- <NuqsAdapter>- <TooltipProvider delayDuration={0}>- {children}- <Toaster position="top-center" />- </TooltipProvider>- </NuqsAdapter>- <TailwindIndicator />- </ActiveThemeProvider>- </LayoutProvider>+ <ActiveThemeProvider>+ <NuqsAdapter>+ <TooltipProvider delayDuration={0}>+ {children}+ <Toaster position="top-center" />+ </TooltipProvider>+ </NuqsAdapter>+ <TailwindIndicator />+ </ActiveThemeProvider></ThemeProvider><Analytics /><div id="portal" className="fixed top-0 left-0 z-40" />diff --git a/apps/v4/components/file-system-docs.tsx b/apps/v4/components/file-system-docs.tsxindex 307a322..88baa2a 100644--- a/apps/v4/components/file-system-docs.tsx+++ b/apps/v4/components/file-system-docs.tsx@@ -122,6 +122,95 @@ const DEMO_SOURCES: DemoSource[] = [},]+// Synthetic "aurora" project folder so the docs demo covers the complete+// file-type icon set plus search, sort, and the file-type filter — without+// bloating the manifest. Everything derives from the path hash, so it is+// stable across server and client renders.+const AURORA_PROJECT_FILES = [+ ".gitignore",+ ".prettierrc",+ "biome.json",+ "bun.lockb",+ "CLAUDE.md",+ "Dockerfile",+ "docker-compose.yml",+ "eslint.config.js",+ "next.config.ts",+ "package.json",+ "README.md",+ "tailwind.config.ts",+ "tsconfig.json",+ "vite.config.ts",+]++const AURORA_AREAS: Array<{+ extensions: string[]+ folder: string+}> = [+ { extensions: ["tsx", "ts", "css"], folder: "src/components" },+ { extensions: ["ts"], folder: "src/lib" },+ { extensions: ["md", "mdx"], folder: "docs" },+ { extensions: ["csv", "json", "xlsx"], folder: "data" },+ { extensions: ["png", "svg", "webp"], folder: "assets" },+ { extensions: ["sh", "py"], folder: "scripts" },+ { extensions: ["go", "rs", "sql"], folder: "backend" },+]++const AURORA_WORDS = [+ "billing",+ "catalog",+ "checkout",+ "dashboard",+ "gateway",+ "inventory",+]++// djb2, unsigned — deterministic sizes and dates per path.+function auroraHash(value: string) {+ let hash = 5381++ for (let index = 0; index < value.length; index += 1) {+ hash = ((hash << 5) + hash + value.charCodeAt(index)) | 0+ }+ return hash >>> 0+}++function generateAuroraItems(): FileSystemItem[] {+ const items: FileSystemItem[] = []+ const pushFile = (path: string) => {+ const hash = auroraHash(path)+ const createdAt = Date.UTC(2025, 5, 1) + (hash % 320) * 86_400_000+ const updatedAt = createdAt + (hash % 90) * 86_400_000++ items.push({+ createdAt: new Date(createdAt).toISOString(),+ kind: "file",+ path,+ size: 850 + (hash % 3_800_000),+ updatedAt: new Date(updatedAt).toISOString(),+ })+ }++ for (const fileName of AURORA_PROJECT_FILES) {+ pushFile(`aurora/${fileName}`)+ }+ for (const area of AURORA_AREAS) {+ // Two files per extension — enough to show off every file type.+ const fileCount = area.extensions.length * 2++ for (let index = 0; index < fileCount; index += 1) {+ const word = AURORA_WORDS[index % AURORA_WORDS.length]+ const extension = area.extensions[index % area.extensions.length]+ const fileName = `${word}-${String(index + 1).padStart(3, "0")}.${extension}`++ pushFile(`aurora/${area.folder}/${fileName}`)+ }+ }+ return items+}++const AURORA_ITEMS = generateAuroraItems()+function getPdfWorkerUrl(pdfjsVersion: string) {return `//unpkg.com/pdfjs-dist@${pdfjsVersion}/legacy/build/pdf.worker.min.mjs`}@@ -538,28 +627,32 @@ export function useFileSystemDemoItems() {)const items = React.useMemo<FileSystemItem[]>(- () =>- DEMO_SOURCES.map<FileSystemItem>((source) => ({- contentType: source.contentType,- createdAt: source.createdAt,- key: source.path,- kind: "file",- path: source.path,- previewAspectRatio: source.previewAspectRatio,- previewImageUrls:- source.thumbnail === "url"- ? [source.url]- : (thumbnails[source.path]?.urls ?? null),- previewPageCount: thumbnails[source.path]?.pageCount,- size: source.size,- updatedAt: source.updatedAt,- url: source.url,- })),+ () => [+ ...DEMO_SOURCES.map<FileSystemItem>((source) => {+ return {+ contentType: source.contentType,+ createdAt: source.createdAt,+ key: source.path,+ kind: "file",+ path: source.path,+ previewAspectRatio: source.previewAspectRatio,+ previewImageUrls:+ source.thumbnail === "url"+ ? [source.url]+ : (thumbnails[source.path]?.urls ?? null),+ previewPageCount: thumbnails[source.path]?.pageCount,+ size: source.size,+ updatedAt: source.updatedAt,+ url: source.url,+ }+ }),+ ...AURORA_ITEMS,+ ],[thumbnails])- // Remaining PDF pages render on demand; data URLs are memoized per page so- // revisiting a page is instant.+ // PDF previews render on demand; data URLs are memoized per page so+ // revisiting a page is instant without shipping generated thumbnail assets.const lazyPageCacheRef = React.useRef(new Map<string, Promise<string | null>>())@@ -689,8 +782,7 @@ const items: FileSystemItem[] = [size: 2215244,createdAt: "2026-02-12T18:21:00Z",updatedAt: "2026-03-24T21:43:00Z",- // Generated externally, e.g. with react-pdf, react-docx, or react-xlsx.- previewImageUrl: "/thumbnails/reports/attention.png",+ url: "/samples/attention.pdf",},// ...]diff --git a/apps/v4/components/file-system-source-code.tsx b/apps/v4/components/file-system-source-code.tsxindex 8f5b9a4..4f8de58 100644--- a/apps/v4/components/file-system-source-code.tsx+++ b/apps/v4/components/file-system-source-code.tsx@@ -5,7 +5,7 @@ import { DocsSourceCodeBlock } from "@/components/docs-code-block"// Generated from components/ui/file-system.tsx — keep in sync when the// component changes.export const fileSystemSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n ArrowLeft01Icon,\n ArrowRight01Icon,\n Cancel01Icon,\n File01Icon,\n GalleryThumbnailsIcon,\n GridViewIcon,\n LayoutThreeColumnIcon,\n LeftToRightListBulletIcon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { prepareFileTreeInput } from "@pierre/trees"\nimport { FileTree as PierreFileTree, useFileTree } from "@pierre/trees/react"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogTitle,\n} from "@/components/ui/dialog"\nimport { DocxViewerPreview } from "@/components/ui/docx-viewer"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { PDFViewer } from "@/components/ui/pdf-viewer"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"\nimport { XlsxViewerPreview } from "@/components/ui/xlsx-viewer"\n\nexport type FileSystemView = "icons" | "list" | "columns" | "gallery"\n\nexport type FileSystemFolderItem = {\n kind: "folder"\n /** Folder prefix, e.g. `"invoices/2026/"`. A trailing slash is added when missing. */\n path: string\n name?: string\n parentPath?: string\n /** Set when children exist but are not in `items` yet; enables `loadChildren`. */\n hasChildren?: boolean\n createdAt?: string\n updatedAt?: string\n}\n\nexport type FileSystemFileItem = {\n kind: "file"\n /** Display/canonical path, e.g. `"invoices/2026/jan.pdf"`. */\n path: string\n /** Original object key (S3/R2). Defaults to `path`. */\n key?: string\n name?: string\n parentPath?: string\n contentType?: string\n size?: number\n createdAt?: string\n updatedAt?: string\n etag?: string\n /** Optional if already public/presigned. Otherwise resolved via `getFileUrl`. */\n url?: string\n /** Externally generated thumbnail. The component never renders documents itself. */\n previewImageUrl?: string | null\n /**\n * Externally generated page thumbnails (first entry is the cover). When a\n * file has more than one page, large thumbnails show a hover pager.\n */\n previewImageUrls?: string[] | null\n /**\n * Total page count when it exceeds `previewImageUrls.length`; the pager\n * loads the remaining pages on demand via `loadPreviewImageUrl`.\n */\n previewPageCount?: number\n /** Thumbnail aspect ratio (width / height). Defaults to a portrait page. */\n previewAspectRatio?: number\n metadata?: Record<string, string>\n}\n\nexport type FileSystemItem = FileSystemFolderItem | FileSystemFileItem\n\nexport type FileSystemLoadChildrenArgs = {\n path: string\n cursor: string | null\n}\n\nexport type FileSystemLoadChildrenResult = {\n items: FileSystemItem[]\n nextCursor?: string | null\n}\n\nexport type FileSystemProps = {\n /** Flat manifest. Folders are optional; missing prefixes are inferred from file paths. */\n items: FileSystemItem[]\n className?: string\n /** Label for the root folder. */\n title?: string\n defaultView?: FileSystemView\n view?: FileSystemView\n onViewChange?: (view: FileSystemView) => void\n /** Folder prefix to open initially, e.g. `"invoices/"`. */\n defaultPath?: string\n onSelectionChange?: (item: FileSystemItem | null) => void\n /**\n * Called on file open (double-click), replacing the built-in behavior. By\n * default PDF, DOCX, XLSX, and image files open in a viewer dialog and\n * other files open their resolved URL in a new tab.\n */\n onFileOpen?: (file: FileSystemFileItem, url: string | null) => void\n /** Resolve a URL (e.g. presigned) for a file without one. */\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n /** Lazily fetch children for folders with `hasChildren` and no loaded entries. */\n loadChildren?: (\n args: FileSystemLoadChildrenArgs\n ) => Promise<FileSystemLoadChildrenResult>\n /** Custom preview node for files without `previewImageUrl`. */\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n /**\n * Lazily render a page thumbnail beyond the eagerly provided\n * `previewImageUrls` (the pager calls this as pages come into view).\n */\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n}\n\ntype FolderEntry = FileSystemFolderItem & {\n name: string\n parentPath: string\n}\n\ntype FileEntry = FileSystemFileItem & {\n key: string\n name: string\n parentPath: string\n}\n\ntype FileSystemEntry = FolderEntry | FileEntry\n\ntype FileSystemIndex = {\n children: Map<string, FileSystemEntry[]>\n files: Map<string, FileEntry>\n folders: Map<string, FolderEntry>\n}\n\nfunction normalizeFolderPath(path: string) {\n if (!path || path === "/") return ""\n return path.endsWith("/") ? path : `${path}/`\n}\n\nfunction pathName(path: string) {\n const trimmed = path.endsWith("/") ? path.slice(0, -1) : path\n const separatorIndex = trimmed.lastIndexOf("/")\n return separatorIndex === -1 ? trimmed : trimmed.slice(separatorIndex + 1)\n}\n\nfunction pathParent(path: string) {\n const trimmed = path.endsWith("/") ? path.slice(0, -1) : path\n const separatorIndex = trimmed.lastIndexOf("/")\n return separatorIndex === -1 ? "" : trimmed.slice(0, separatorIndex + 1)\n}\n\nfunction fileExtension(name: string) {\n const dotIndex = name.lastIndexOf(".")\n return dotIndex === -1 ? "" : name.slice(dotIndex + 1).toLowerCase()\n}\n\nconst FILE_KIND_LABELS: Record<string, string> = {\n csv: "CSV Document",\n doc: "Word Document",\n docx: "Word Document",\n gif: "GIF Image",\n jpeg: "JPEG Image",\n jpg: "JPEG Image",\n md: "Markdown Document",\n pdf: "PDF Document",\n png: "PNG Image",\n ppt: "PowerPoint Presentation",\n pptx: "PowerPoint Presentation",\n svg: "SVG Image",\n tsv: "TSV Document",\n txt: "Plain Text",\n webp: "WebP Image",\n xls: "Excel Workbook",\n xlsx: "Excel Workbook",\n zip: "ZIP Archive",\n}\n\nfunction fileKindLabel(file: FileEntry) {\n const byExtension = FILE_KIND_LABELS[fileExtension(file.name)]\n\n if (byExtension) return byExtension\n if (file.contentType?.startsWith("image/")) return "Image"\n\n return file.contentType ?? "Document"\n}\n\nexport type FileSystemViewerKind = "docx" | "image" | "pdf" | "xlsx"\n\nfunction viewerKindForFile(\n file: FileSystemFileItem\n): FileSystemViewerKind | null {\n if (file.contentType?.startsWith("image/")) return "image"\n if (file.contentType === "application/pdf") return "pdf"\n\n const name = (file.name ?? file.path).toLowerCase()\n\n if (name.endsWith(".pdf")) return "pdf"\n if (name.endsWith(".docx")) return "docx"\n if (name.endsWith(".xlsx")) return "xlsx"\n if (/\\.(avif|gif|jpe?g|png|svg|webp)$/.test(name)) return "image"\n\n return null\n}\n\n// PDF and DOCX pages want height; spreadsheets want width; images get a\n// roomy but contained frame.\nconst VIEWER_DIALOG_CLASSNAMES: Record<FileSystemViewerKind, string> = {\n docx: "h-[88vh] w-[min(96vw,68rem)] max-w-none",\n image: "max-h-[88vh] w-fit max-w-[min(96vw,64rem)]",\n pdf: "h-[88vh] w-[min(96vw,68rem)] max-w-none",\n xlsx: "h-[85vh] w-[min(96vw,100rem)] max-w-none",\n}\n\nfunction formatByteSize(size: number | undefined) {\n if (size === undefined) return null\n if (size < 1000) return `${size} bytes`\n\n const units = ["KB", "MB", "GB", "TB"]\n let value = size\n\n for (const unit of units) {\n value /= 1000\n if (value < 1000 || unit === "TB") {\n return `${value >= 100 ? Math.round(value) : value.toFixed(value >= 10 ? 1 : 2).replace(/\\.?0+$/, "")} ${unit}`\n }\n }\n\n return null\n}\n\nfunction formatTimestamp(value: string | undefined) {\n if (!value) return null\n\n const date = new Date(value)\n\n if (Number.isNaN(date.getTime())) return null\n\n const day = date.toLocaleDateString("en-US", {\n day: "numeric",\n month: "short",\n year: "numeric",\n })\n const time = date.toLocaleTimeString("en-US", {\n hour: "numeric",\n minute: "2-digit",\n })\n\n return `${day} at ${time}`\n}\n\nfunction buildFileSystemIndex(items: FileSystemItem[]): FileSystemIndex {\n const folders = new Map<string, FolderEntry>()\n const files = new Map<string, FileEntry>()\n\n const ensureFolderChain = (folderPath: string) => {\n let path = normalizeFolderPath(folderPath)\n\n while (path && !folders.has(path)) {\n folders.set(path, {\n kind: "folder",\n name: pathName(path),\n parentPath: pathParent(path),\n path,\n })\n path = pathParent(path)\n }\n }\n\n for (const item of items) {\n if (item.kind === "folder") {\n const path = normalizeFolderPath(item.path)\n\n if (!path) continue\n\n folders.set(path, {\n ...item,\n name: item.name ?? pathName(path),\n parentPath: normalizeFolderPath(item.parentPath ?? pathParent(path)),\n path,\n })\n ensureFolderChain(pathParent(path))\n } else {\n if (!item.path) continue\n\n files.set(item.path, {\n ...item,\n key: item.key ?? item.path,\n name: item.name ?? pathName(item.path),\n parentPath: normalizeFolderPath(\n item.parentPath ?? pathParent(item.path)\n ),\n })\n ensureFolderChain(pathParent(item.path))\n }\n }\n\n const children = new Map<string, FileSystemEntry[]>()\n const pushChild = (entry: FileSystemEntry) => {\n const siblings = children.get(entry.parentPath)\n\n if (siblings) {\n siblings.push(entry)\n } else {\n children.set(entry.parentPath, [entry])\n }\n }\n\n for (const folder of folders.values()) pushChild(folder)\n for (const file of files.values()) pushChild(file)\n for (const siblings of children.values()) {\n siblings.sort((left, right) =>\n left.name.localeCompare(right.name, undefined, {\n numeric: true,\n sensitivity: "base",\n })\n )\n }\n\n return { children, files, folders }\n}\n\nfunction folderHasChildren(index: FileSystemIndex, folder: FolderEntry) {\n return (\n (index.children.get(folder.path)?.length ?? 0) > 0 ||\n folder.hasChildren === true\n )\n}\n\n// A single SVG source so the same glyph renders as a React element, inside the\n// @pierre/trees shadow DOM (via CSS url()), and stays pixel-identical in both.\nconst FOLDER_GLYPH_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 50" width="64" height="50"><defs><linearGradient id="fs-folder-back" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#3dabf5"/><stop offset="1" stop-color="#1d84dd"/></linearGradient><linearGradient id="fs-folder-front" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#7accfb"/><stop offset="1" stop-color="#37a0ef"/></linearGradient></defs><path d="M5 10c0-3.31 2.69-6 6-6h10.9c1.6 0 3.13.7 4.18 1.9l1.5 1.73a3.5 3.5 0 0 0 2.64 1.22H54c2.76 0 5 2.24 5 5V40c0 3.87-3.13 7-7 7H12c-3.87 0-7-3.13-7-7V10Z" fill="url(#fs-folder-back)"/><path d="M5 15.5h54V40c0 3.87-3.13 7-7 7H12c-3.87 0-7-3.13-7-7V15.5Z" fill="url(#fs-folder-front)"/></svg>`\n\nconst FOLDER_GLYPH_DATA_URL = `data:image/svg+xml,${encodeURIComponent(FOLDER_GLYPH_SVG)}`\n\nfunction FileSystemFolderGlyph({ className }: { className?: string }) {\n return (\n <img\n src={FOLDER_GLYPH_DATA_URL}\n alt=""\n aria-hidden="true"\n draggable={false}\n className={className}\n />\n )\n}\n\nfunction escapeXmlAttribute(value: string) {\n return value\n .replaceAll("&", "&")\n .replaceAll("<", "<")\n .replaceAll(">", ">")\n .replaceAll(\'"\', """)\n}\n\nfunction FileGenericPreview({ file }: { file: FileEntry }) {\n const extension = fileExtension(file.name)\n\n return (\n <div className="flex size-full flex-col items-center justify-center gap-1.5 bg-white text-neutral-400 dark:bg-neutral-100">\n <HugeiconsIcon icon={File01Icon} className="size-1/3 min-h-4 min-w-4" />\n {extension ? (\n <span className="text-[min(0.625rem,18cqw)] font-semibold tracking-wide uppercase">\n {extension}\n </span>\n ) : null}\n </div>\n )\n}\n\nfunction filePreviewUrls(file: FileSystemFileItem) {\n if (file.previewImageUrls?.length) return file.previewImageUrls\n return file.previewImageUrl ? [file.previewImageUrl] : []\n}\n\n// djb2 — cheap stable hash for remount keys derived from path lists.\nfunction hashString(value: string) {\n let hash = 5381\n\n for (let index = 0; index < value.length; index += 1) {\n hash = ((hash << 5) + hash + value.charCodeAt(index)) | 0\n }\n return hash\n}\n\nfunction FileVisual({\n file,\n className,\n loadPreviewImageUrl,\n pageable = false,\n previewAspectRatio,\n previewClassName,\n renderFilePreview,\n}: {\n file: FileEntry\n className?: string\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n /** Show a hover pager over multi-page thumbnails. */\n pageable?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n}) {\n const previewUrls = filePreviewUrls(file)\n const canLoadLazily = pageable && Boolean(loadPreviewImageUrl)\n const totalPages = Math.max(\n previewUrls.length,\n canLoadLazily ? (file.previewPageCount ?? 0) : 0\n )\n const [pageIndex, setPageIndex] = React.useState(0)\n const [lazyPageUrls, setLazyPageUrls] = React.useState<\n Record<number, string>\n >({})\n const clampedPageIndex = Math.min(pageIndex, Math.max(totalPages - 1, 0))\n const previewUrl =\n previewUrls[clampedPageIndex] ?? lazyPageUrls[clampedPageIndex] ?? null\n const resolvedAspectRatio = file.previewAspectRatio ?? previewAspectRatio\n const isLazyPagePending =\n canLoadLazily && !previewUrl && clampedPageIndex < totalPages\n\n const fileRef = React.useRef(file)\n\n React.useEffect(() => {\n fileRef.current = file\n })\n\n React.useEffect(() => {\n setPageIndex(0)\n setLazyPageUrls({})\n }, [file.path])\n\n // Keyed by path (not object identity) so manifest churn doesn\'t re-request\n // the page already being loaded.\n React.useEffect(() => {\n if (!isLazyPagePending || !loadPreviewImageUrl) return\n\n let isCurrent = true\n\n void loadPreviewImageUrl(fileRef.current, clampedPageIndex)\n .then((url) => {\n if (isCurrent && url) {\n setLazyPageUrls((previous) => ({\n ...previous,\n [clampedPageIndex]: url,\n }))\n }\n })\n .catch(() => {})\n\n return () => {\n isCurrent = false\n }\n }, [clampedPageIndex, file.path, isLazyPagePending, loadPreviewImageUrl])\n\n const customPreview =\n !previewUrl && !isLazyPagePending ? renderFilePreview?.(file) : null\n const showPager = pageable && totalPages > 1\n const thumbnail = (\n <FileThumbnail\n file={{ name: file.name, type: file.contentType ?? "" }}\n className={cn("@container", !showPager && className)}\n previewAspectRatio={resolvedAspectRatio}\n previewClassName={cn("bg-white dark:bg-neutral-100", previewClassName)}\n previewImageUrl={previewUrl ?? undefined}\n isLoading={isLazyPagePending}\n previewContent={\n previewUrl || isLazyPagePending\n ? undefined\n : (customPreview ?? <FileGenericPreview file={file} />)\n }\n />\n )\n\n if (!showPager) return thumbnail\n\n return (\n <div className={cn("group/pager relative", className)}>\n {thumbnail}\n <div className="absolute inset-x-0 bottom-1.5 flex items-center justify-center gap-1 opacity-0 transition-opacity group-focus-within/pager:opacity-100 group-hover/pager:opacity-100">\n <button\n type="button"\n aria-label="Previous page"\n tabIndex={-1}\n disabled={clampedPageIndex === 0}\n onClick={(event) => {\n event.stopPropagation()\n setPageIndex((previous) => Math.max(0, previous - 1))\n }}\n onDoubleClick={(event) => event.stopPropagation()}\n className="flex size-6 items-center justify-center rounded-md bg-background/80 text-foreground shadow-xs backdrop-blur-sm transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />\n </button>\n <span className="rounded-md bg-background/80 px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground tabular-nums shadow-xs backdrop-blur-sm">\n {clampedPageIndex + 1}/{totalPages}\n </span>\n <button\n type="button"\n aria-label="Next page"\n tabIndex={-1}\n disabled={clampedPageIndex >= totalPages - 1}\n onClick={(event) => {\n event.stopPropagation()\n setPageIndex((previous) => Math.min(totalPages - 1, previous + 1))\n }}\n onDoubleClick={(event) => event.stopPropagation()}\n className="flex size-6 items-center justify-center rounded-md bg-background/80 text-foreground shadow-xs backdrop-blur-sm transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-3.5" />\n </button>\n </div>\n </div>\n )\n}\n\nconst VIEW_OPTIONS: Array<{\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n label: string\n value: FileSystemView\n}> = [\n { icon: GridViewIcon, label: "Grid", value: "icons" },\n { icon: LeftToRightListBulletIcon, label: "List", value: "list" },\n { icon: LayoutThreeColumnIcon, label: "Columns", value: "columns" },\n { icon: GalleryThumbnailsIcon, label: "Gallery", value: "gallery" },\n]\n\nexport function FileSystem({\n items,\n className,\n title = "Files",\n defaultView = "icons",\n view: viewProp,\n onViewChange,\n defaultPath = "",\n onSelectionChange,\n onFileOpen,\n getFileUrl,\n loadChildren,\n loadPreviewImageUrl,\n renderFilePreview,\n}: FileSystemProps) {\n const [internalView, setInternalView] = React.useState(defaultView)\n const view = viewProp ?? internalView\n const setView = React.useCallback(\n (nextView: FileSystemView) => {\n setInternalView(nextView)\n onViewChange?.(nextView)\n },\n [onViewChange]\n )\n\n const [loadedItems, setLoadedItems] = React.useState<FileSystemItem[]>([])\n const allItems = React.useMemo(\n () => (loadedItems.length ? [...items, ...loadedItems] : items),\n [items, loadedItems]\n )\n const index = React.useMemo(() => buildFileSystemIndex(allItems), [allItems])\n\n const [history, setHistory] = React.useState(() => ({\n index: 0,\n stack: [normalizeFolderPath(defaultPath)],\n }))\n const currentPath = history.stack[history.index] ?? ""\n const canGoBack = history.index > 0\n const canGoForward = history.index < history.stack.length - 1\n\n const [selectedPath, setSelectedPath] = React.useState<string | null>(null)\n const selectedEntry = React.useMemo(() => {\n if (selectedPath === null) return null\n\n return (\n index.files.get(selectedPath) ?? index.folders.get(selectedPath) ?? null\n )\n }, [index, selectedPath])\n\n const selectEntry = React.useCallback(\n (entry: FileSystemEntry | null) => {\n setSelectedPath(entry?.path ?? null)\n onSelectionChange?.(entry)\n },\n [onSelectionChange]\n )\n\n // Below 480px the tabs view switcher no longer fits in the toolbar and\n // collapses into a select; below 360px the select label and the folder\n // name are dropped too, leaving icons only.\n const rootRef = React.useRef<HTMLDivElement | null>(null)\n const [headerLayout, setHeaderLayout] = React.useState<\n "full" | "compact" | "minimal"\n >("full")\n\n React.useEffect(() => {\n const root = rootRef.current\n\n if (!root || typeof ResizeObserver === "undefined") return\n\n const observer = new ResizeObserver((observerEntries) => {\n const width = observerEntries[0]?.contentRect.width\n\n if (width === undefined) return\n\n setHeaderLayout(\n width < 360 ? "minimal" : width < 480 ? "compact" : "full"\n )\n })\n\n observer.observe(root)\n return () => observer.disconnect()\n }, [])\n\n const requestedFoldersRef = React.useRef(new Set<string>())\n const [loadingFolders, setLoadingFolders] = React.useState<Set<string>>(\n () => new Set()\n )\n const ensureChildren = React.useCallback(\n (folderPath: string) => {\n if (!loadChildren) return\n\n const folder = index.folders.get(folderPath)\n\n if (!folder?.hasChildren) return\n if (index.children.get(folderPath)?.length) return\n if (requestedFoldersRef.current.has(folderPath)) return\n\n requestedFoldersRef.current.add(folderPath)\n setLoadingFolders((previous) => new Set(previous).add(folderPath))\n\n void (async () => {\n try {\n let cursor: string | null = null\n\n do {\n const result = await loadChildren({ cursor, path: folderPath })\n\n if (result.items.length) {\n setLoadedItems((previous) => [...previous, ...result.items])\n }\n cursor = result.nextCursor ?? null\n } while (cursor)\n } catch {\n requestedFoldersRef.current.delete(folderPath)\n } finally {\n setLoadingFolders((previous) => {\n const next = new Set(previous)\n\n next.delete(folderPath)\n return next\n })\n }\n })()\n },\n [index, loadChildren]\n )\n\n const navigateTo = React.useCallback(\n (folderPath: string) => {\n const path = normalizeFolderPath(folderPath)\n\n setHistory((previous) => {\n if (previous.stack[previous.index] === path) return previous\n\n const stack = [...previous.stack.slice(0, previous.index + 1), path]\n\n return { index: stack.length - 1, stack }\n })\n selectEntry(null)\n ensureChildren(path)\n },\n [ensureChildren, selectEntry]\n )\n\n React.useEffect(() => {\n ensureChildren(currentPath)\n }, [currentPath, ensureChildren])\n\n // Navigation unmounts the focused row, dropping focus to <body> and killing\n // the ⌘ shortcuts; reclaim focus onto the component root when that happens.\n const hasNavigatedRef = React.useRef(false)\n\n React.useEffect(() => {\n if (!hasNavigatedRef.current) {\n hasNavigatedRef.current = true\n return\n }\n\n const root = rootRef.current\n\n if (root && document.activeElement === document.body) {\n root.focus()\n }\n }, [currentPath])\n\n const [openedFile, setOpenedFile] = React.useState<{\n file: FileEntry\n kind: FileSystemViewerKind\n url: string\n } | null>(null)\n\n const openFile = React.useCallback(\n (file: FileEntry) => {\n void (async () => {\n let url = file.url ?? null\n\n if (!url && getFileUrl) {\n try {\n url = await getFileUrl(file)\n } catch {\n url = null\n }\n }\n if (onFileOpen) {\n onFileOpen(file, url)\n return\n }\n\n const kind = viewerKindForFile(file)\n\n if (kind && url) {\n setOpenedFile({ file, kind, url })\n } else if (url && typeof window !== "undefined") {\n window.open(url, "_blank", "noopener,noreferrer")\n }\n })()\n },\n [getFileUrl, onFileOpen]\n )\n\n const openEntry = React.useCallback(\n (entry: FileSystemEntry) => {\n if (entry.kind === "folder") {\n navigateTo(entry.path)\n } else {\n openFile(entry)\n }\n },\n [navigateTo, openFile]\n )\n\n // Selecting a lazy folder (columns view, keyboard nav) prefetches children.\n const selectAndPrefetchEntry = React.useCallback(\n (entry: FileSystemEntry | null) => {\n selectEntry(entry)\n if (entry?.kind === "folder") ensureChildren(entry.path)\n },\n [ensureChildren, selectEntry]\n )\n\n const goBack = React.useCallback(() => {\n setHistory((previous) => ({\n ...previous,\n index: Math.max(0, previous.index - 1),\n }))\n selectEntry(null)\n }, [selectEntry])\n\n const goForward = React.useCallback(() => {\n setHistory((previous) => ({\n ...previous,\n index: Math.min(previous.stack.length - 1, previous.index + 1),\n }))\n selectEntry(null)\n }, [selectEntry])\n\n const currentEntries = index.children.get(currentPath) ?? []\n const currentFolderName =\n currentPath === "" ? title : pathName(currentPath) || title\n const isLoadingCurrentFolder = loadingFolders.has(currentPath)\n\n const viewProps: FileSystemViewProps = {\n currentPath,\n entries: currentEntries,\n getFileUrl,\n index,\n loadPreviewImageUrl,\n loadingFolders,\n onOpen: openEntry,\n onSelect: selectAndPrefetchEntry,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n }\n\n const openedFileName = openedFile\n ? (openedFile.file.name ?? openedFile.file.path)\n : ""\n const activeViewOption = VIEW_OPTIONS.find((option) => option.value === view)\n const viewerCloseToolbarAction = (\n <DialogClose\n aria-label="Close preview"\n render={<Button type="button" variant="ghost" size="icon-sm" />}\n >\n <HugeiconsIcon icon={Cancel01Icon} className="size-4" />\n </DialogClose>\n )\n\n return (\n <div\n ref={rootRef}\n tabIndex={-1}\n className={cn(\n "flex h-[480px] min-h-0 flex-col overflow-hidden rounded-xl border bg-background text-foreground outline-none",\n className\n )}\n >\n <div className="grid h-12 shrink-0 grid-cols-[1fr_auto_1fr] items-center gap-2 border-b bg-muted/40 px-2">\n <div className="flex min-w-0 items-center gap-0.5">\n <button\n type="button"\n aria-label="Back"\n title="Back"\n disabled={!canGoBack}\n onClick={goBack}\n className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4.5" />\n </button>\n <button\n type="button"\n aria-label="Forward"\n title="Forward"\n disabled={!canGoForward}\n onClick={goForward}\n className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-4.5" />\n </button>\n {headerLayout !== "minimal" ? (\n <span className="ml-1.5 truncate text-sm font-semibold">\n {currentFolderName}\n </span>\n ) : null}\n </div>\n {headerLayout !== "full" ? (\n <Select\n value={view}\n onValueChange={(value) => setView(value as FileSystemView)}\n >\n <SelectTrigger\n size="sm"\n aria-label="View"\n className={cn(headerLayout !== "minimal" && "min-w-32")}\n >\n <SelectValue>\n {activeViewOption ? (\n <span className="flex items-center gap-2">\n <HugeiconsIcon\n icon={activeViewOption.icon}\n className="size-4"\n />\n {headerLayout !== "minimal" ? activeViewOption.label : null}\n </span>\n ) : null}\n </SelectValue>\n </SelectTrigger>\n <SelectContent>\n {VIEW_OPTIONS.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n <span className="flex items-center gap-2">\n <HugeiconsIcon icon={option.icon} className="size-4" />\n {option.label}\n </span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : (\n <Tabs\n value={view}\n onValueChange={(value) => setView(value as FileSystemView)}\n className="gap-0"\n >\n <TabsList className="h-8 p-0.5">\n {VIEW_OPTIONS.map((option) => (\n <TabsTrigger\n key={option.value}\n value={option.value}\n aria-label={`${option.label} view`}\n title={option.label}\n className="h-7 grow-0 px-2.5 sm:h-7"\n >\n <HugeiconsIcon icon={option.icon} className="size-4" />\n </TabsTrigger>\n ))}\n </TabsList>\n </Tabs>\n )}\n <div />\n </div>\n <div className="relative min-h-0 flex-1">\n {isLoadingCurrentFolder && currentEntries.length === 0 ? (\n <FileSystemEmptyState label="Loading…" isLoading />\n ) : currentEntries.length === 0 && view !== "columns" ? (\n <FileSystemEmptyState label="This folder is empty" />\n ) : view === "icons" ? (\n <FileSystemIconsView {...viewProps} />\n ) : view === "list" ? (\n <FileSystemListView {...viewProps} />\n ) : view === "columns" ? (\n <FileSystemColumnsView {...viewProps} />\n ) : (\n <FileSystemGalleryView {...viewProps} />\n )}\n </div>\n <div\n aria-live="polite"\n className="flex h-7 shrink-0 items-center justify-center gap-1 border-t bg-muted/40 px-3 text-xs text-muted-foreground"\n >\n <span>\n {currentEntries.length}{" "}\n {currentEntries.length === 1 ? "item" : "items"}\n </span>\n {selectedEntry ? <span>· “{selectedEntry.name}” selected</span> : null}\n </div>\n <Dialog\n open={openedFile !== null}\n onOpenChange={(open) => {\n if (!open) setOpenedFile(null)\n }}\n >\n {openedFile ? (\n <DialogContent\n className={cn(\n "overflow-hidden p-0",\n VIEWER_DIALOG_CLASSNAMES[openedFile.kind]\n )}\n showCloseButton={openedFile.kind === "image"}\n >\n <DialogTitle className="sr-only">{openedFileName}</DialogTitle>\n {openedFile.kind === "pdf" ? (\n <PDFViewer\n file={openedFile.url}\n className="h-full min-h-0 flex-1 overflow-hidden rounded-2xl"\n downloadFileName={openedFileName}\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n ) : openedFile.kind === "docx" ? (\n <DocxViewerPreview\n src={openedFile.url}\n fileName={openedFileName}\n className="h-full min-h-0 flex-1"\n rounded\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n ) : openedFile.kind === "xlsx" ? (\n <XlsxViewerPreview\n src={openedFile.url}\n fileName={openedFileName}\n className="h-full min-h-0 flex-1"\n rounded\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n ) : (\n <img\n src={openedFile.url}\n alt={openedFileName}\n className="max-h-[88vh] w-auto max-w-full rounded-2xl object-contain"\n />\n )}\n </DialogContent>\n ) : null}\n </Dialog>\n </div>\n )\n}\n\ntype FileSystemViewProps = {\n currentPath: string\n entries: FileSystemEntry[]\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n index: FileSystemIndex\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n loadingFolders: Set<string>\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n selectedEntry: FileSystemEntry | null\n selectedPath: string | null\n}\n\n// Resolves a display URL for a file: its own `url`, else via `getFileUrl`.\n// Keyed by path/url (not object identity) so manifest churn — e.g. thumbnails\n// streaming in — doesn\'t re-trigger presign calls for the same file.\nfunction useResolvedFileUrl(\n file: FileEntry | null,\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n) {\n const [state, setState] = React.useState<{\n isResolving: boolean\n url: string | null\n }>({ isResolving: false, url: file?.url ?? null })\n const fileRef = React.useRef(file)\n\n React.useEffect(() => {\n fileRef.current = file\n })\n\n const filePath = file?.path ?? null\n const fileUrl = file?.url ?? null\n\n React.useEffect(() => {\n const currentFile = fileRef.current\n\n if (!currentFile || fileUrl || !getFileUrl) {\n setState({ isResolving: false, url: fileUrl })\n return\n }\n\n let isCurrent = true\n\n setState({ isResolving: true, url: null })\n void Promise.resolve(getFileUrl(currentFile))\n .then((url) => {\n if (isCurrent) setState({ isResolving: false, url })\n })\n .catch(() => {\n if (isCurrent) setState({ isResolving: false, url: null })\n })\n\n return () => {\n isCurrent = false\n }\n }, [filePath, fileUrl, getFileUrl])\n\n return state\n}\n\n// Returns `value` once it has stopped changing for `delay` ms. Gallery\n// navigation scrubs past files quickly; heavy previews (document viewers,\n// presigned URL resolution) only kick in for the file the user lands on.\nfunction useSettledValue<T>(value: T, delay: number): T {\n const [settled, setSettled] = React.useState(value)\n\n React.useEffect(() => {\n if (Object.is(settled, value)) return\n\n const timeout = window.setTimeout(() => setSettled(value), delay)\n\n return () => window.clearTimeout(timeout)\n }, [delay, settled, value])\n\n return settled\n}\n\nfunction FileSystemEmptyState({\n label,\n isLoading = false,\n}: {\n label: string\n isLoading?: boolean\n}) {\n return (\n <div\n className={cn(\n "flex size-full items-center justify-center text-sm text-muted-foreground",\n isLoading && "animate-pulse motion-reduce:animate-none"\n )}\n >\n {label}\n </div>\n )\n}\n\nconst ARROW_KEYS = new Set(["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"])\n\n// Selects (and focuses) the entry reached by an arrow key. Up/down use row\n// geometry so navigation follows the rendered auto-fill grid.\nfunction moveGridSelection({\n entries,\n itemRefs,\n key,\n onSelect,\n selectedPath,\n}: {\n entries: FileSystemEntry[]\n itemRefs: Map<string, HTMLButtonElement>\n key: string\n onSelect: (entry: FileSystemEntry | null) => void\n selectedPath: string | null\n}) {\n if (entries.length === 0) return false\n\n const currentIndex = entries.findIndex((entry) => entry.path === selectedPath)\n let nextEntry: FileSystemEntry | undefined\n\n if (currentIndex === -1) {\n nextEntry = entries[0]\n } else if (key === "ArrowLeft" || key === "ArrowRight") {\n nextEntry = entries[currentIndex + (key === "ArrowLeft" ? -1 : 1)]\n } else {\n const currentElement = itemRefs.get(entries[currentIndex].path)\n\n if (!currentElement) return false\n\n const currentRect = currentElement.getBoundingClientRect()\n let bestScore = Infinity\n\n for (const entry of entries) {\n if (entry.path === selectedPath) continue\n\n const rect = itemRefs.get(entry.path)?.getBoundingClientRect()\n\n if (!rect) continue\n\n const rowDelta =\n key === "ArrowDown"\n ? rect.top - currentRect.top\n : currentRect.top - rect.top\n\n if (rowDelta <= 1) continue\n\n const score = rowDelta * 1000 + Math.abs(rect.left - currentRect.left)\n\n if (score < bestScore) {\n bestScore = score\n nextEntry = entry\n }\n }\n }\n\n if (!nextEntry) return false\n\n onSelect(nextEntry)\n itemRefs.get(nextEntry.path)?.focus()\n return true\n}\n\nfunction FileSystemIconsView({\n entries,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedPath,\n}: FileSystemViewProps) {\n const itemRefs = React.useRef(new Map<string, HTMLButtonElement>())\n // Roving tabindex: the grid is a single tab stop (the selected tile, or the\n // first one), so Shift+Tab returns to the toolbar like in the list view.\n const tabStopPath = entries.some((entry) => entry.path === selectedPath)\n ? selectedPath\n : (entries[0]?.path ?? null)\n\n return (\n <ScrollArea\n orientation="vertical"\n viewportClassName="p-3"\n viewportProps={{\n onClick: (event) => {\n if (event.target === event.currentTarget) onSelect(null)\n },\n }}\n >\n <div\n role="listbox"\n aria-label="Files"\n className="grid grid-cols-[repeat(auto-fill,minmax(6.5rem,1fr))] gap-x-1 gap-y-3"\n onKeyDown={(event) => {\n if (!ARROW_KEYS.has(event.key)) return\n if (\n moveGridSelection({\n entries,\n itemRefs: itemRefs.current,\n key: event.key,\n onSelect,\n selectedPath,\n })\n ) {\n event.preventDefault()\n }\n }}\n >\n {entries.map((entry) => {\n const isSelected = entry.path === selectedPath\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isSelected}\n tabIndex={entry.path === tabStopPath ? 0 : -1}\n ref={(element) => {\n if (element) {\n itemRefs.current.set(entry.path, element)\n } else {\n itemRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n className="group flex flex-col items-center gap-1.5 outline-none"\n >\n <span\n className={cn(\n "flex h-16 w-20 items-center justify-center rounded-lg p-1 transition-colors group-focus-visible:ring-2 group-focus-visible:ring-ring",\n isSelected && "bg-accent"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-13 w-auto drop-shadow-sm" />\n ) : (\n <FileVisual\n file={entry}\n className={cn(\n "rounded-sm shadow-xs",\n // Landscape thumbnails get extra width so they fill\n // the tile instead of rendering as a short sliver.\n (entry.previewAspectRatio ?? 0.78) > 1.2\n ? "w-[4.75rem]"\n : "w-12"\n )}\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )}\n </span>\n <span\n className={cn(\n "max-w-full rounded-sm px-1.5 py-px text-center text-xs leading-tight break-words",\n isSelected\n ? "bg-primary text-primary-foreground"\n : "text-foreground"\n )}\n >\n <span className="line-clamp-2">{entry.name}</span>\n </span>\n </button>\n )\n })}\n </div>\n </ScrollArea>\n )\n}\n\nfunction FileSystemListView({\n currentPath,\n index,\n onOpen,\n onSelect,\n selectedPath,\n}: FileSystemViewProps) {\n const relativePaths = React.useMemo(() => {\n const paths: string[] = []\n\n for (const path of index.files.keys()) {\n if (currentPath === "" || path.startsWith(currentPath)) {\n const relativePath = path.slice(currentPath.length)\n\n if (relativePath) paths.push(relativePath)\n }\n }\n return paths.sort()\n }, [currentPath, index])\n // Content-derived key: the tree only remounts when the path set actually\n // changes (a bare length check misses same-count replacements).\n const treeKey = React.useMemo(\n () => hashString(relativePaths.join("\\n")),\n [relativePaths]\n )\n\n if (relativePaths.length === 0) {\n return <FileSystemEmptyState label="This folder is empty" />\n }\n\n return (\n <div className="flex size-full flex-col">\n {/* Paddings match the tree\'s row geometry: name text starts 46px in\n (16px tree padding + 30px icon lane), metadata ends 24px from the\n right (16px tree padding + 8px decoration inset). */}\n <div className="flex shrink-0 items-center border-b py-1.5 pr-6 pl-[46px] text-xs font-medium text-muted-foreground">\n <span className="flex-1">Name</span>\n <span className="w-44 text-right">Date Modified</span>\n <span className="w-20 text-right">Size</span>\n </div>\n <FileSystemPierreTree\n key={`${currentPath}::${treeKey}`}\n currentPath={currentPath}\n index={index}\n initialSelectedPath={\n selectedPath?.startsWith(currentPath)\n ? selectedPath.slice(currentPath.length).replace(/\\/$/, "")\n : null\n }\n onOpen={onOpen}\n onSelect={onSelect}\n relativePaths={relativePaths}\n />\n </div>\n )\n}\n\nfunction FileSystemPierreTree({\n currentPath,\n index,\n initialSelectedPath,\n onOpen,\n onSelect,\n relativePaths,\n}: {\n currentPath: string\n index: FileSystemIndex\n initialSelectedPath: string | null\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n relativePaths: string[]\n}) {\n const preparedInput = React.useMemo(\n () => prepareFileTreeInput(relativePaths, { sort: "default" }),\n [relativePaths]\n )\n // Inject per-file thumbnails into the tree\'s shadow DOM as sprite symbols\n // wrapping an <image>, remapped onto rows by file basename. The chevron is\n // remapped to the Hugeicons arrow so it matches the rest of the component;\n // the tree\'s rotation CSS keys off data-icon-name, which remapping keeps.\n const icons = React.useMemo(() => {\n const byFileName: Record<string, { name: string; viewBox: string }> = {}\n const symbols: string[] = [\n `<symbol id="file-system-chevron" viewBox="0 0 24 24"><path d="M18 9.00005C18 9.00005 13.5811 15 12 15C10.4188 15 6 9 6 9" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/></symbol>`,\n ]\n\n for (const relativePath of relativePaths) {\n const file = index.files.get(`${currentPath}${relativePath}`)\n const coverUrl = file ? filePreviewUrls(file)[0] : undefined\n\n if (!file || !coverUrl) continue\n\n const baseName = file.name.toLowerCase()\n\n if (byFileName[baseName]) continue\n\n const symbolId = `file-system-thumbnail-${symbols.length}`\n\n symbols.push(\n `<symbol id="${symbolId}" viewBox="0 0 16 16"><clipPath id="${symbolId}-clip"><rect width="16" height="16" rx="2.5"/></clipPath><image href="${escapeXmlAttribute(coverUrl)}" width="16" height="16" preserveAspectRatio="xMidYMid slice" clip-path="url(#${symbolId}-clip)"/></symbol>`\n )\n byFileName[baseName] = { name: symbolId, viewBox: "0 0 16 16" }\n }\n\n return {\n byFileName,\n remap: {\n "file-tree-icon-chevron": {\n name: "file-system-chevron",\n viewBox: "0 0 24 24",\n },\n },\n spriteSheet: `<svg data-icon-sprite aria-hidden="true" width="0" height="0">${symbols.join("")}</svg>`,\n }\n }, [currentPath, index, relativePaths])\n const { model } = useFileTree({\n flattenEmptyDirectories: false,\n icons,\n initialExpansion: "closed",\n initialSelectedPaths: initialSelectedPath ? [initialSelectedPath] : [],\n itemHeight: 28,\n overscan: 12,\n preparedInput,\n renderRowDecoration: ({ row }) => {\n const entry =\n row.kind === "file"\n ? index.files.get(`${currentPath}${row.path}`)\n : index.folders.get(normalizeFolderPath(`${currentPath}${row.path}`))\n\n if (!entry) return null\n\n // The decoration lane renders one <span title>; CSS splits it into\n // aligned Date Modified (::before from title) and Size columns.\n const dateColumn =\n formatTimestamp(entry.updatedAt ?? entry.createdAt) ?? "—"\n\n if (entry.kind === "folder") {\n const childCount = index.children.get(entry.path)?.length\n\n return {\n text:\n childCount === undefined\n ? "—"\n : `${childCount} ${childCount === 1 ? "item" : "items"}`,\n title: dateColumn,\n }\n }\n\n return { text: formatByteSize(entry.size) ?? "—", title: dateColumn }\n },\n unsafeCSS: `\n button[data-type=\'item\']:not([data-item-selected]):hover {\n background: color-mix(in oklab, var(--color-accent) 50%, transparent);\n }\n button[data-type=\'item\'][data-item-selected] {\n background: var(--color-primary);\n color: var(--color-primary-foreground);\n }\n button[data-type=\'item\'][data-item-selected] *,\n button[data-type=\'item\'][data-item-selected] [data-item-section]::before,\n button[data-type=\'item\'][data-item-selected] svg {\n color: var(--color-primary-foreground) !important;\n }\n [data-item-section=\'decoration\'] > span {\n display: grid;\n grid-template-columns: 11rem 5rem;\n justify-items: end;\n white-space: nowrap;\n }\n [data-item-section=\'decoration\'] > span::before {\n content: attr(title);\n }\n button[data-type=\'item\'][data-item-type=\'folder\'] [data-item-section=\'content\'] {\n display: flex;\n align-items: center;\n min-width: 0;\n }\n button[data-type=\'item\'][data-item-type=\'folder\'] [data-item-section=\'content\']::before {\n content: "";\n flex: none;\n width: 18px;\n height: 14px;\n margin-right: 4px;\n background: url("${FOLDER_GLYPH_DATA_URL}") center / contain no-repeat;\n }\n `,\n onSelectionChange: (selectedPaths) => {\n const relativePath = selectedPaths[0]\n\n if (!relativePath) {\n onSelect(null)\n return\n }\n\n const absolutePath = `${currentPath}${relativePath}`\n const entry =\n index.files.get(absolutePath) ??\n index.folders.get(normalizeFolderPath(absolutePath)) ??\n null\n\n onSelect(entry)\n },\n })\n\n // Thumbnails can resolve after mount (e.g. generated client-side); push\n // sprite updates into the existing model instead of remounting the tree.\n React.useEffect(() => {\n model.setIcons(icons)\n }, [icons, model])\n\n // The tree\'s arrow keys move focus and only select on click/Enter; mirror\n // focus into the (single) selection so arrowing selects like Finder. Shift\n // ranges keep the focused row selected, so they pass through untouched.\n React.useEffect(() => {\n let lastFocusedPath = model.getFocusedPath()\n\n return model.subscribe(() => {\n const focusedPath = model.getFocusedPath()\n\n if (focusedPath === lastFocusedPath) return\n\n lastFocusedPath = focusedPath\n\n if (!focusedPath) return\n\n const item = model.getItem(focusedPath)\n\n if (!item || item.isSelected()) return\n\n for (const path of model.getSelectedPaths()) {\n model.getItem(path)?.deselect()\n }\n item.select()\n })\n }, [model])\n\n return (\n <PierreFileTree\n model={model}\n className="block min-h-0 flex-1"\n onDoubleClick={(event) => {\n // Rows live in the tree\'s shadow DOM; composedPath surfaces the row\n // element so double-clicked files open like in the other views.\n for (const target of event.nativeEvent.composedPath()) {\n if (!(target instanceof HTMLElement)) continue\n const relativePath = target.dataset?.itemPath\n if (!relativePath) continue\n\n const file = index.files.get(`${currentPath}${relativePath}`)\n\n if (file) onOpen(file)\n return\n }\n }}\n style={\n {\n "--trees-bg-override": "transparent",\n "--trees-border-color-override": "var(--color-border)",\n "--trees-fg-override": "var(--color-foreground)",\n // Match the focus-visible ring used by the tabs and the other\n // views (`ring-2 ring-ring`) instead of the tree\'s accent blue.\n "--trees-focus-ring-color-override": "var(--color-ring)",\n "--trees-focus-ring-width-override": "2px",\n "--trees-selected-bg-override": "var(--color-primary)",\n "--trees-selected-focused-border-color-override": "var(--color-ring)",\n } as React.CSSProperties\n }\n />\n )\n}\n\nfunction FileSystemColumnsView(props: FileSystemViewProps) {\n const {\n currentPath,\n index,\n loadPreviewImageUrl,\n loadingFolders,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n } = props\n const scrollContainerRef = React.useRef<HTMLDivElement | null>(null)\n const rowRefs = React.useRef(new Map<string, HTMLButtonElement>())\n\n // The selection highlight tracks every keypress; mounting the trailing\n // child column and the preview pane is deferred so holding an arrow key\n // doesn\'t pay that DOM churn per step.\n const deferredSelectedEntry = React.useDeferredValue(selectedEntry)\n const deferredSelectedPath = React.useDeferredValue(selectedPath)\n const pendingFocusPathRef = React.useRef<string | null>(null)\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (!ARROW_KEYS.has(event.key)) return\n\n let nextEntry: FileSystemEntry | null | undefined\n\n if (!selectedEntry || !selectedPath?.startsWith(currentPath)) {\n nextEntry = index.children.get(currentPath)?.[0]\n } else if (event.key === "ArrowUp" || event.key === "ArrowDown") {\n const siblings = index.children.get(selectedEntry.parentPath) ?? []\n const currentIndex = siblings.findIndex(\n (sibling) => sibling.path === selectedEntry.path\n )\n\n nextEntry = siblings[currentIndex + (event.key === "ArrowUp" ? -1 : 1)]\n } else if (event.key === "ArrowLeft") {\n if (selectedEntry.parentPath !== currentPath) {\n nextEntry = index.folders.get(selectedEntry.parentPath)\n }\n } else if (selectedEntry.kind === "folder") {\n nextEntry = index.children.get(selectedEntry.path)?.[0]\n }\n\n if (!nextEntry) return\n\n onSelect(nextEntry)\n\n const row = rowRefs.current.get(nextEntry.path)\n\n if (row) {\n pendingFocusPathRef.current = null\n row.focus()\n } else {\n // The target row lives in a deferred column that hasn\'t mounted yet;\n // focus it from the effect below once it exists.\n pendingFocusPathRef.current = nextEntry.path\n }\n event.preventDefault()\n }\n\n React.useEffect(() => {\n const path = pendingFocusPathRef.current\n\n if (!path) return\n\n const row = rowRefs.current.get(path)\n\n if (row) {\n pendingFocusPathRef.current = null\n row.focus()\n }\n })\n\n const columnPaths = React.useMemo(() => {\n const paths = [currentPath]\n\n if (!deferredSelectedPath?.startsWith(currentPath)) return paths\n\n const targetFolder =\n deferredSelectedEntry?.kind === "folder"\n ? deferredSelectedEntry.path\n : (deferredSelectedEntry?.parentPath ?? currentPath)\n const relativePath = targetFolder.slice(currentPath.length)\n let walkedPath = currentPath\n\n for (const segment of relativePath.split("/")) {\n if (!segment) continue\n walkedPath = `${walkedPath}${segment}/`\n paths.push(walkedPath)\n }\n return paths\n }, [currentPath, deferredSelectedEntry, deferredSelectedPath])\n const columnPathSet = React.useMemo(() => new Set(columnPaths), [columnPaths])\n // Roving tabindex: all columns together form a single tab stop (the\n // selected row when its column is mounted, else the first row), so\n // Shift+Tab returns to the toolbar like in the list view.\n const tabStopPath = React.useMemo(() => {\n if (selectedPath) {\n for (const columnPath of columnPaths) {\n if (\n index.children\n .get(columnPath)\n ?.some((entry) => entry.path === selectedPath)\n ) {\n return selectedPath\n }\n }\n }\n return index.children.get(columnPaths[0] ?? "")?.[0]?.path ?? null\n }, [columnPaths, index, selectedPath])\n const selectedFile =\n deferredSelectedEntry?.kind === "file"\n ? (deferredSelectedEntry as FileEntry)\n : null\n const selectedFileSize = selectedFile\n ? formatByteSize(selectedFile.size)\n : null\n\n React.useEffect(() => {\n const container = scrollContainerRef.current\n\n if (container) container.scrollLeft = container.scrollWidth\n }, [columnPaths.length, deferredSelectedPath])\n\n return (\n <ScrollArea\n orientation="horizontal"\n viewportRef={scrollContainerRef}\n viewportClassName="overscroll-x-contain"\n >\n <div className="flex h-full w-max min-w-full" onKeyDown={handleKeyDown}>\n {columnPaths.map((columnPath) => (\n <ScrollArea\n key={columnPath || "(root)"}\n orientation="vertical"\n className="w-60 shrink-0 border-r"\n viewportClassName="flex flex-col gap-px p-1.5"\n viewportProps={{ "aria-label": "Files", role: "listbox" }}\n >\n {loadingFolders.has(columnPath) &&\n !index.children.get(columnPath)?.length ? (\n <div className="animate-pulse px-2 py-1.5 text-xs text-muted-foreground motion-reduce:animate-none">\n Loading…\n </div>\n ) : (\n (index.children.get(columnPath) ?? []).map((entry) => {\n const isSelected = entry.path === selectedPath\n const isOnTrail =\n entry.kind === "folder" && columnPathSet.has(entry.path)\n\n const coverUrl =\n entry.kind === "file" ? filePreviewUrls(entry)[0] : undefined\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isSelected}\n tabIndex={entry.path === tabStopPath ? 0 : -1}\n ref={(element) => {\n if (element) {\n rowRefs.current.set(entry.path, element)\n } else {\n rowRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n className={cn(\n "flex shrink-0 items-center gap-2 rounded-md px-2 py-1 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",\n isSelected\n ? "bg-primary text-primary-foreground"\n : isOnTrail\n ? "bg-accent"\n : "hover:bg-accent/50"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-3.5 w-auto shrink-0" />\n ) : coverUrl ? (\n <img\n src={coverUrl}\n alt=""\n draggable={false}\n className="size-4 shrink-0 rounded-[3px] bg-white object-cover"\n />\n ) : (\n <HugeiconsIcon\n icon={File01Icon}\n className={cn(\n "size-4 shrink-0",\n !isSelected && "text-muted-foreground"\n )}\n />\n )}\n <span className="min-w-0 flex-1 truncate">\n {entry.name}\n </span>\n {entry.kind === "folder" &&\n folderHasChildren(index, entry) ? (\n <HugeiconsIcon\n icon={ArrowRight01Icon}\n className={cn(\n "size-3.5 shrink-0",\n !isSelected && "text-muted-foreground/60"\n )}\n />\n ) : null}\n </button>\n )\n })\n )}\n </ScrollArea>\n ))}\n {selectedFile ? (\n <ScrollArea\n orientation="vertical"\n className="min-w-72 flex-1"\n viewportClassName="flex justify-center p-4"\n >\n <div className="flex w-full max-w-lg flex-col items-stretch gap-3">\n {/* Width derives from the aspect ratio so the thumbnail grows\n with the pane up to a 20rem height cap. */}\n <div\n className="mx-auto w-full shrink-0"\n style={{\n maxWidth: `min(100%, ${(selectedFile.previewAspectRatio ?? 0.78) * 20}rem)`,\n }}\n >\n <FileVisual\n file={selectedFile}\n className="w-full"\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageable\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n </div>\n <div className="text-center">\n <div className="text-sm font-semibold break-words">\n {selectedFile.name}\n </div>\n <div className="text-xs text-muted-foreground">\n {fileKindLabel(selectedFile)}\n {selectedFileSize ? ` - ${selectedFileSize}` : null}\n </div>\n </div>\n <FileSystemInformation entry={selectedFile} index={index} />\n </div>\n </ScrollArea>\n ) : null}\n </div>\n </ScrollArea>\n )\n}\n\nfunction FileSystemInformation({\n entry,\n index,\n}: {\n entry: FileSystemEntry\n index: FileSystemIndex\n}) {\n const rows: Array<[string, string]> = []\n const created = formatTimestamp(entry.createdAt)\n const updated = formatTimestamp(entry.updatedAt)\n\n if (created) rows.push(["Created", created])\n if (updated) rows.push(["Modified", updated])\n if (entry.kind === "file") {\n const size = formatByteSize(entry.size)\n\n if (size) rows.push(["Size", size])\n } else {\n const childCount = index.children.get(entry.path)?.length\n\n if (childCount !== undefined) {\n rows.push(["Items", `${childCount}`])\n }\n }\n\n if (rows.length === 0) return null\n\n return (\n <div className="border-t pt-3">\n <div className="mb-1.5 text-xs font-semibold">Information</div>\n <dl className="space-y-1">\n {rows.map(([label, value]) => (\n <div\n key={label}\n className="flex items-baseline justify-between gap-3 text-xs"\n >\n <dt className="shrink-0 text-muted-foreground">{label}</dt>\n <dd className="text-right" suppressHydrationWarning>\n {value}\n </dd>\n </div>\n ))}\n </dl>\n </div>\n )\n}\n\nfunction FileSystemGalleryView(props: FileSystemViewProps) {\n const {\n entries,\n getFileUrl,\n index,\n loadPreviewImageUrl,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n } = props\n const stripRefs = React.useRef(new Map<string, HTMLButtonElement>())\n const activeEntry =\n selectedEntry && entries.some((entry) => entry.path === selectedEntry.path)\n ? selectedEntry\n : (entries[0] ?? null)\n const activeFile = activeEntry?.kind === "file" ? activeEntry : null\n const activeViewerKind = activeFile ? viewerKindForFile(activeFile) : null\n // While arrow keys are scrubbing the strip, the center pane shows a\n // spinner; the full-size viewer (and its URL resolution) mounts once the\n // selection settles so each keystroke stays cheap.\n const settledPath = useSettledValue(activeEntry?.path ?? null, 200)\n const isSettled = settledPath === (activeEntry?.path ?? null)\n const { isResolving, url: activeFileUrl } = useResolvedFileUrl(\n isSettled ? activeFile : null,\n getFileUrl\n )\n const isStageLoading =\n activeFile !== null &&\n (!isSettled || (activeViewerKind !== null && isResolving))\n const activeFileSize = activeFile ? formatByteSize(activeFile.size) : null\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return\n if (entries.length === 0) return\n\n const currentIndex = activeEntry\n ? entries.findIndex((entry) => entry.path === activeEntry.path)\n : -1\n const nextEntry =\n entries[\n currentIndex === -1\n ? 0\n : currentIndex + (event.key === "ArrowLeft" ? -1 : 1)\n ]\n\n if (!nextEntry) return\n\n onSelect(nextEntry)\n stripRefs.current.get(nextEntry.path)?.focus()\n event.preventDefault()\n }\n\n return (\n <div className="flex size-full flex-col" onKeyDown={handleKeyDown}>\n {/* The strip comes first in DOM order (rendered below via order-last)\n so the filmstrip is the view\'s single tab stop: Shift+Tab exits to\n the toolbar instead of landing inside the embedded viewers. */}\n <ScrollArea\n orientation="horizontal"\n className="order-last h-auto w-full shrink-0 border-t"\n >\n <div\n role="listbox"\n aria-label="Files"\n className="flex w-max min-w-full items-center gap-1.5 p-2"\n >\n {entries.map((entry) => {\n const isActive = entry.path === (activeEntry?.path ?? selectedPath)\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isActive}\n tabIndex={isActive ? 0 : -1}\n ref={(element) => {\n if (element) {\n stripRefs.current.set(entry.path, element)\n } else {\n stripRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n title={entry.name}\n className={cn(\n "flex size-14 shrink-0 items-center justify-center rounded-md border border-transparent p-1 outline-none focus-visible:ring-2 focus-visible:ring-ring",\n isActive && "border-ring/40 bg-accent"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-9 w-auto" />\n ) : (\n <FileVisual\n file={entry}\n className="w-9 rounded-sm"\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )}\n </button>\n )\n })}\n </div>\n </ScrollArea>\n <div className="flex min-h-0 flex-1">\n <div className="flex min-h-0 min-w-0 flex-1 items-center justify-center p-3">\n {activeEntry ? (\n activeEntry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-40 max-h-full w-auto drop-shadow-md" />\n ) : isStageLoading ? (\n <Spinner className="size-6 text-muted-foreground" />\n ) : activeViewerKind === "image" && activeFileUrl ? (\n <img\n src={activeFileUrl}\n alt={activeEntry.name}\n className="max-h-full max-w-full rounded-lg object-contain"\n />\n ) : activeViewerKind === "pdf" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <PDFViewer\n key={activeEntry.path}\n file={activeFileUrl}\n className="h-full"\n showToolbar={false}\n />\n </div>\n ) : activeViewerKind === "docx" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <DocxViewerPreview\n key={activeEntry.path}\n src={activeFileUrl}\n fileName={activeEntry.name}\n className="h-full"\n showToolbar={false}\n />\n </div>\n ) : activeViewerKind === "xlsx" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <XlsxViewerPreview\n key={activeEntry.path}\n src={activeFileUrl}\n fileName={activeEntry.name}\n className="h-full"\n showToolbar={false}\n />\n </div>\n ) : (\n <FileVisual\n file={activeEntry}\n className="w-56 max-w-full"\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageable\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )\n ) : null}\n </div>\n {activeEntry ? (\n <ScrollArea\n orientation="vertical"\n className="hidden w-64 shrink-0 border-l sm:block"\n viewportClassName="flex flex-col gap-3 p-4"\n >\n <div className="flex items-center gap-3">\n {activeFile ? (\n <FileVisual\n file={activeFile}\n className={cn(\n "shrink-0 rounded-sm",\n (activeFile.previewAspectRatio ?? 0.78) > 1.2\n ? "w-16"\n : "w-9"\n )}\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n ) : (\n <FileSystemFolderGlyph className="h-8 w-auto shrink-0" />\n )}\n <div className="min-w-0 flex-1">\n <div className="text-sm font-semibold break-words">\n {activeEntry.name}\n </div>\n <div className="text-xs text-muted-foreground">\n {activeFile ? fileKindLabel(activeFile) : "Folder"}\n {activeFileSize ? ` - ${activeFileSize}` : null}\n </div>\n </div>\n </div>\n <FileSystemInformation entry={activeEntry} index={index} />\n </ScrollArea>\n ) : null}\n </div>\n </div>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n ArrowDown01Icon,\n ArrowLeft01Icon,\n ArrowRight01Icon,\n ArrowUp01Icon,\n ArrowUpDownIcon,\n Calendar03Icon,\n Cancel01Icon,\n File01Icon,\n FilterIcon,\n GalleryThumbnailsIcon,\n GridViewIcon,\n LayoutThreeColumnIcon,\n LeftToRightListBulletIcon,\n Search01Icon,\n Tick02Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport {\n createFileTreeIconResolver,\n getBuiltInSpriteSheet,\n prepareFileTreeInput,\n type FileTreeSortComparator,\n type FileTreeSortEntry,\n} from "@pierre/trees"\nimport { FileTree as PierreFileTree, useFileTree } from "@pierre/trees/react"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n Command,\n CommandEmpty,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n} from "@/components/ui/command"\nimport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogFooter,\n DialogHeader,\n DialogPanel,\n DialogTitle,\n} from "@/components/ui/dialog"\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSub,\n DropdownMenuSubContent,\n DropdownMenuSubTrigger,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\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 { Spinner } from "@/components/ui/spinner"\nimport { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"\n\nconst LazyPDFViewer = React.lazy(() =>\n import("@/components/ui/pdf-viewer").then((mod) => ({\n default: mod.PDFViewer,\n }))\n)\nconst LazyDocxViewerPreview = React.lazy(() =>\n import("@/components/ui/docx-viewer").then((mod) => ({\n default: mod.DocxViewerPreview,\n }))\n)\nconst LazyXlsxViewerPreview = React.lazy(() =>\n import("@/components/ui/xlsx-viewer").then((mod) => ({\n default: mod.XlsxViewerPreview,\n }))\n)\n\nexport type FileSystemView = "icons" | "list" | "columns" | "gallery"\n\nexport type FileSystemFolderItem = {\n kind: "folder"\n /** Folder prefix, e.g. `"invoices/2026/"`. A trailing slash is added when missing. */\n path: string\n name?: string\n parentPath?: string\n /** Set when children exist but are not in `items` yet; enables `loadChildren`. */\n hasChildren?: boolean\n createdAt?: string\n updatedAt?: string\n}\n\nexport type FileSystemFileItem = {\n kind: "file"\n /** Display/canonical path, e.g. `"invoices/2026/jan.pdf"`. */\n path: string\n /** Original object key (S3/R2). Defaults to `path`. */\n key?: string\n name?: string\n parentPath?: string\n contentType?: string\n size?: number\n createdAt?: string\n updatedAt?: string\n etag?: string\n /** Optional if already public/presigned. Otherwise resolved via `getFileUrl`. */\n url?: string\n /** Externally generated thumbnail. The component never renders documents itself. */\n previewImageUrl?: string | null\n /**\n * Externally generated page thumbnails (first entry is the cover). When a\n * file has more than one page, large thumbnails show a hover pager.\n */\n previewImageUrls?: string[] | null\n /**\n * Total page count when it exceeds `previewImageUrls.length`; the pager\n * loads the remaining pages on demand via `loadPreviewImageUrl`.\n */\n previewPageCount?: number\n /** Thumbnail aspect ratio (width / height). Defaults to a portrait page. */\n previewAspectRatio?: number\n metadata?: Record<string, string>\n}\n\nexport type FileSystemItem = FileSystemFolderItem | FileSystemFileItem\n\nexport type FileSystemLoadChildrenArgs = {\n path: string\n cursor: string | null\n}\n\nexport type FileSystemLoadChildrenResult = {\n items: FileSystemItem[]\n nextCursor?: string | null\n}\n\nexport type FileSystemProps = {\n /** Flat manifest. Folders are optional; missing prefixes are inferred from file paths. */\n items: FileSystemItem[]\n className?: string\n /** Label for the root folder. */\n title?: string\n defaultView?: FileSystemView\n view?: FileSystemView\n onViewChange?: (view: FileSystemView) => void\n /** Folder prefix to open initially, e.g. `"invoices/"`. */\n defaultPath?: string\n onSelectionChange?: (item: FileSystemItem | null) => void\n /**\n * Called on file open (double-click), replacing the built-in behavior. By\n * default PDF, DOCX, XLSX, and image files open in a viewer dialog and\n * other files open their resolved URL in a new tab.\n */\n onFileOpen?: (file: FileSystemFileItem, url: string | null) => void\n /** Resolve a URL (e.g. presigned) for a file without one. */\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n /** Lazily fetch children for folders with `hasChildren` and no loaded entries. */\n loadChildren?: (\n args: FileSystemLoadChildrenArgs\n ) => Promise<FileSystemLoadChildrenResult>\n /** Custom preview node for files without `previewImageUrl`. */\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n /**\n * Lazily render a page thumbnail beyond the eagerly provided\n * `previewImageUrls` (the pager calls this as pages come into view).\n */\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n}\n\ntype FolderEntry = FileSystemFolderItem & {\n name: string\n parentPath: string\n}\n\ntype FileEntry = FileSystemFileItem & {\n key: string\n name: string\n parentPath: string\n}\n\ntype FileSystemEntry = FolderEntry | FileEntry\n\ntype FileSystemIndex = {\n children: Map<string, FileSystemEntry[]>\n files: Map<string, FileEntry>\n folders: Map<string, FolderEntry>\n}\n\nfunction normalizeFolderPath(path: string) {\n if (!path || path === "/") return ""\n return path.endsWith("/") ? path : `${path}/`\n}\n\nfunction pathName(path: string) {\n const trimmed = path.endsWith("/") ? path.slice(0, -1) : path\n const separatorIndex = trimmed.lastIndexOf("/")\n return separatorIndex === -1 ? trimmed : trimmed.slice(separatorIndex + 1)\n}\n\nfunction pathParent(path: string) {\n const trimmed = path.endsWith("/") ? path.slice(0, -1) : path\n const separatorIndex = trimmed.lastIndexOf("/")\n return separatorIndex === -1 ? "" : trimmed.slice(0, separatorIndex + 1)\n}\n\nfunction fileExtension(name: string) {\n const dotIndex = name.lastIndexOf(".")\n return dotIndex === -1 ? "" : name.slice(dotIndex + 1).toLowerCase()\n}\n\nconst FILE_KIND_LABELS: Record<string, string> = {\n csv: "CSV Document",\n doc: "Word Document",\n docx: "Word Document",\n gif: "GIF Image",\n jpeg: "JPEG Image",\n jpg: "JPEG Image",\n md: "Markdown Document",\n pdf: "PDF Document",\n png: "PNG Image",\n ppt: "PowerPoint Presentation",\n pptx: "PowerPoint Presentation",\n svg: "SVG Image",\n tsv: "TSV Document",\n txt: "Plain Text",\n webp: "WebP Image",\n xls: "Excel Workbook",\n xlsx: "Excel Workbook",\n zip: "ZIP Archive",\n}\n\nfunction fileKindLabel(file: FileEntry) {\n const byExtension = FILE_KIND_LABELS[fileExtension(file.name)]\n\n if (byExtension) return byExtension\n if (file.contentType?.startsWith("image/")) return "Image"\n\n return file.contentType ?? "Document"\n}\n\n// MIME types inferred from the extension when a file carries no\n// `contentType`, so the file-type filter can classify every manifest entry.\nconst EXTENSION_MIME_TYPES: Record<string, string> = {\n css: "text/css",\n csv: "text/csv",\n doc: "application/msword",\n docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",\n gif: "image/gif",\n go: "text/x-go",\n jpeg: "image/jpeg",\n jpg: "image/jpeg",\n js: "text/javascript",\n json: "application/json",\n jsx: "text/jsx",\n md: "text/markdown",\n mdx: "text/mdx",\n pdf: "application/pdf",\n png: "image/png",\n ppt: "application/vnd.ms-powerpoint",\n pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",\n py: "text/x-python",\n rs: "text/x-rust",\n sh: "application/x-sh",\n sql: "application/sql",\n svg: "image/svg+xml",\n ts: "text/x-typescript",\n tsv: "text/tab-separated-values",\n tsx: "text/x-typescript",\n txt: "text/plain",\n webp: "image/webp",\n xls: "application/vnd.ms-excel",\n xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",\n yaml: "text/yaml",\n yml: "text/yaml",\n zip: "application/zip",\n}\n\nconst FALLBACK_MIME_TYPE = "application/octet-stream"\n\nconst MIME_TYPE_LABELS: Record<string, string> = {\n [FALLBACK_MIME_TYPE]: "Binary",\n "application/json": "JSON",\n "application/msword": "Word document (legacy)",\n "application/pdf": "PDF",\n "application/sql": "SQL",\n "application/vnd.ms-excel": "Excel workbook (legacy)",\n "application/vnd.ms-powerpoint": "PowerPoint (legacy)",\n "application/vnd.openxmlformats-officedocument.presentationml.presentation":\n "PowerPoint",\n "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":\n "Excel workbook",\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document":\n "Word document",\n "application/x-sh": "Shell script",\n "application/zip": "ZIP archive",\n "image/gif": "GIF image",\n "image/jpeg": "JPEG image",\n "image/png": "PNG image",\n "image/svg+xml": "SVG image",\n "image/webp": "WebP image",\n "text/css": "CSS",\n "text/csv": "CSV",\n "text/javascript": "JavaScript",\n "text/jsx": "JSX",\n "text/markdown": "Markdown",\n "text/mdx": "MDX",\n "text/plain": "Plain text",\n "text/tab-separated-values": "TSV",\n "text/x-go": "Go",\n "text/x-python": "Python",\n "text/x-rust": "Rust",\n "text/x-typescript": "TypeScript",\n "text/yaml": "YAML",\n}\n\nfunction mimeTypeForFile(file: FileEntry) {\n return (\n file.contentType ??\n EXTENSION_MIME_TYPES[fileExtension(file.name)] ??\n FALLBACK_MIME_TYPE\n )\n}\n\nexport type FileSystemViewerKind = "docx" | "image" | "pdf" | "xlsx"\n\nfunction viewerKindForFile(\n file: FileSystemFileItem\n): FileSystemViewerKind | null {\n if (file.contentType?.startsWith("image/")) return "image"\n if (file.contentType === "application/pdf") return "pdf"\n\n const name = (file.name ?? file.path).toLowerCase()\n\n if (name.endsWith(".pdf")) return "pdf"\n if (name.endsWith(".docx")) return "docx"\n if (name.endsWith(".xlsx")) return "xlsx"\n if (/\\.(avif|gif|jpe?g|png|svg|webp)$/.test(name)) return "image"\n\n return null\n}\n\n// PDF and DOCX pages want height; spreadsheets want width; images get a\n// roomy but contained frame.\nconst VIEWER_DIALOG_CLASSNAMES: Record<FileSystemViewerKind, string> = {\n docx: "h-[88vh] w-[min(96vw,68rem)] max-w-none",\n image: "max-h-[88vh] w-fit max-w-[min(96vw,64rem)]",\n pdf: "h-[88vh] w-[min(96vw,68rem)] max-w-none",\n xlsx: "h-[85vh] w-[min(96vw,100rem)] max-w-none",\n}\n\nfunction FileSystemViewerLoading() {\n return (\n <div className="grid h-full min-h-48 flex-1 place-items-center bg-background">\n <Spinner className="size-4 text-muted-foreground" />\n </div>\n )\n}\n\nfunction formatByteSize(size: number | undefined) {\n if (size === undefined) return null\n if (size < 1000) return `${size} bytes`\n\n const units = ["KB", "MB", "GB", "TB"]\n let value = size\n\n for (const unit of units) {\n value /= 1000\n if (value < 1000 || unit === "TB") {\n return `${value >= 100 ? Math.round(value) : value.toFixed(value >= 10 ? 1 : 2).replace(/\\.?0+$/, "")} ${unit}`\n }\n }\n\n return null\n}\n\nfunction formatTimestamp(value: string | undefined) {\n if (!value) return null\n\n const date = new Date(value)\n\n if (Number.isNaN(date.getTime())) return null\n\n const day = date.toLocaleDateString("en-US", {\n day: "numeric",\n month: "short",\n year: "numeric",\n })\n const time = date.toLocaleTimeString("en-US", {\n hour: "numeric",\n minute: "2-digit",\n })\n\n return `${day} at ${time}`\n}\n\n// Every directory prefix appearing in the given relative file paths.\nfunction directoryPathsOf(paths: readonly string[]) {\n const directoryPaths = new Set<string>()\n\n for (const relativePath of paths) {\n let slashIndex = relativePath.indexOf("/")\n\n while (slashIndex !== -1) {\n directoryPaths.add(relativePath.slice(0, slashIndex))\n slashIndex = relativePath.indexOf("/", slashIndex + 1)\n }\n }\n return directoryPaths\n}\n\nfunction compareEntryNames(left: { name: string }, right: { name: string }) {\n return left.name.localeCompare(right.name, undefined, {\n numeric: true,\n sensitivity: "base",\n })\n}\n\nexport type FileSystemSortKey = "createdAt" | "name" | "size" | "updatedAt"\n\ntype FileSystemSortState = {\n direction: "asc" | "desc"\n key: FileSystemSortKey\n}\n\nconst SORT_OPTIONS: Array<{\n defaultDirection: "asc" | "desc"\n key: FileSystemSortKey\n label: string\n /** Shorter label so the toolbar trigger stays narrow. */\n triggerLabel: string\n}> = [\n { defaultDirection: "asc", key: "name", label: "Name", triggerLabel: "Name" },\n {\n defaultDirection: "desc",\n key: "createdAt",\n label: "Date created",\n triggerLabel: "Created",\n },\n {\n defaultDirection: "desc",\n key: "updatedAt",\n label: "Date modified",\n triggerLabel: "Modified",\n },\n {\n defaultDirection: "desc",\n key: "size",\n label: "Size",\n triggerLabel: "Size",\n },\n]\n\nconst DEFAULT_SORT: FileSystemSortState = { direction: "asc", key: "name" }\n\nfunction defaultSortDirection(key: FileSystemSortKey) {\n return (\n SORT_OPTIONS.find((option) => option.key === key)?.defaultDirection ?? "asc"\n )\n}\n\nfunction entrySortTimestamp(\n entry: FileSystemEntry,\n key: "createdAt" | "updatedAt"\n) {\n const value = entry[key]\n const time = value ? Date.parse(value) : Number.NaN\n\n return Number.isNaN(time) ? 0 : time\n}\n\n// Primary key per the active sort; ties (and missing metadata) fall back to\n// the name order so results stay stable. The name tiebreak ignores the\n// direction, like Finder.\nfunction compareEntriesBySort(\n left: FileSystemEntry,\n right: FileSystemEntry,\n sort: FileSystemSortState\n) {\n let result = 0\n\n if (sort.key === "name") {\n result = compareEntryNames(left, right)\n } else if (sort.key === "size") {\n // Folders have no byte size; group them at the small end.\n const leftSize = left.kind === "file" ? (left.size ?? 0) : -1\n const rightSize = right.kind === "file" ? (right.size ?? 0) : -1\n\n result = leftSize - rightSize\n } else {\n result =\n entrySortTimestamp(left, sort.key) - entrySortTimestamp(right, sort.key)\n }\n\n if (result === 0) return compareEntryNames(left, right)\n return sort.direction === "asc" ? (result < 0 ? -1 : 1) : result < 0 ? 1 : -1\n}\n\nexport type FileSystemFilterType = "dateCreated" | "dateModified" | "fileType"\n\ntype FileSystemDateFilterType = Exclude<FileSystemFilterType, "fileType">\n\ntype FileSystemFilterOperator =\n | "after"\n | "before"\n | "in-range"\n | "is"\n | "is-any-of"\n | "is-not"\n | "not-in-range"\n\ntype FileSystemFilter = {\n id: string\n operator: FileSystemFilterOperator\n type: FileSystemFilterType\n value: string[]\n}\n\ntype FileTypeFilterOption = {\n /** Sample file name so the option icon reuses the file-type sprite. */\n iconFileName: string\n label: string\n mime: string\n}\n\nconst FILTER_TYPE_LABELS: Record<FileSystemFilterType, string> = {\n dateCreated: "Date created",\n dateModified: "Date modified",\n fileType: "File type",\n}\n\nconst FILTER_OPERATOR_LABELS: Record<FileSystemFilterOperator, string> = {\n after: "after",\n before: "before",\n "in-range": "in range",\n is: "is",\n "is-any-of": "is any of",\n "is-not": "is not",\n "not-in-range": "not in range",\n}\n\n// Relative cutoffs for the date filters, mirroring Extend\'s table filters.\nconst DATE_FILTER_PRESETS = [\n "1 day ago",\n "3 days ago",\n "1 week ago",\n "1 month ago",\n "3 months ago",\n "6 months ago",\n "1 year ago",\n]\n\nfunction dateFilterPresetCutoff(preset: string) {\n const date = new Date()\n\n switch (preset) {\n case "1 day ago":\n date.setDate(date.getDate() - 1)\n break\n case "3 days ago":\n date.setDate(date.getDate() - 3)\n break\n case "1 week ago":\n date.setDate(date.getDate() - 7)\n break\n case "1 month ago":\n date.setMonth(date.getMonth() - 1)\n break\n case "3 months ago":\n date.setMonth(date.getMonth() - 3)\n break\n case "6 months ago":\n date.setMonth(date.getMonth() - 6)\n break\n case "1 year ago":\n date.setFullYear(date.getFullYear() - 1)\n break\n default: {\n const parsed = Date.parse(preset)\n\n if (!Number.isNaN(parsed)) return new Date(parsed)\n }\n }\n return date\n}\n\n// Custom ranges store two ISO timestamps instead of a relative preset.\nfunction isCustomDateRangeValue(value: string[]) {\n return (\n value.length === 2 &&\n value.every(\n (entry) =>\n !DATE_FILTER_PRESETS.includes(entry) && !Number.isNaN(Date.parse(entry))\n )\n )\n}\n\nfunction filterOperatorChoices(\n filter: FileSystemFilter\n): FileSystemFilterOperator[] {\n if (filter.type === "fileType") {\n return filter.value.length > 1 ? ["is-any-of", "is-not"] : ["is", "is-not"]\n }\n if (isCustomDateRangeValue(filter.value)) return ["in-range", "not-in-range"]\n return ["before", "after"]\n}\n\nfunction fileMatchesFilter(file: FileEntry, filter: FileSystemFilter) {\n if (filter.value.length === 0) return true\n if (filter.type === "fileType") {\n const matches = filter.value.includes(mimeTypeForFile(file))\n\n return filter.operator === "is-not" ? !matches : matches\n }\n\n const timestamp =\n filter.type === "dateCreated" ? file.createdAt : file.updatedAt\n const time = timestamp ? Date.parse(timestamp) : Number.NaN\n\n if (Number.isNaN(time)) return false\n if (filter.operator === "in-range" || filter.operator === "not-in-range") {\n const from = Date.parse(filter.value[0])\n const to = Date.parse(filter.value[1] ?? filter.value[0])\n const isInRange = time >= from && time <= to\n\n return filter.operator === "not-in-range" ? !isInRange : isInRange\n }\n\n const cutoff = dateFilterPresetCutoff(filter.value[0]).getTime()\n\n return filter.operator === "before" ? time <= cutoff : time >= cutoff\n}\n\nfunction buildFileSystemIndex(items: FileSystemItem[]): FileSystemIndex {\n const folders = new Map<string, FolderEntry>()\n const files = new Map<string, FileEntry>()\n\n const ensureFolderChain = (folderPath: string) => {\n let path = normalizeFolderPath(folderPath)\n\n while (path && !folders.has(path)) {\n folders.set(path, {\n kind: "folder",\n name: pathName(path),\n parentPath: pathParent(path),\n path,\n })\n path = pathParent(path)\n }\n }\n\n for (const item of items) {\n if (item.kind === "folder") {\n const path = normalizeFolderPath(item.path)\n\n if (!path) continue\n\n folders.set(path, {\n ...item,\n name: item.name ?? pathName(path),\n parentPath: normalizeFolderPath(item.parentPath ?? pathParent(path)),\n path,\n })\n ensureFolderChain(pathParent(path))\n } else {\n if (!item.path) continue\n\n files.set(item.path, {\n ...item,\n key: item.key ?? item.path,\n name: item.name ?? pathName(item.path),\n parentPath: normalizeFolderPath(\n item.parentPath ?? pathParent(item.path)\n ),\n })\n ensureFolderChain(pathParent(item.path))\n }\n }\n\n const children = new Map<string, FileSystemEntry[]>()\n const pushChild = (entry: FileSystemEntry) => {\n const siblings = children.get(entry.parentPath)\n\n if (siblings) {\n siblings.push(entry)\n } else {\n children.set(entry.parentPath, [entry])\n }\n }\n\n for (const folder of folders.values()) pushChild(folder)\n for (const file of files.values()) pushChild(file)\n for (const siblings of children.values()) {\n siblings.sort(compareEntryNames)\n }\n\n return { children, files, folders }\n}\n\nfunction folderHasChildren(index: FileSystemIndex, folder: FolderEntry) {\n return (\n (index.children.get(folder.path)?.length ?? 0) > 0 ||\n folder.hasChildren === true\n )\n}\n\n// A single SVG source so the same glyph renders as a React element, inside the\n// @pierre/trees shadow DOM (via CSS url()), and stays pixel-identical in both.\nconst FOLDER_GLYPH_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 50" width="64" height="50"><defs><linearGradient id="fs-folder-back" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#3dabf5"/><stop offset="1" stop-color="#1d84dd"/></linearGradient><linearGradient id="fs-folder-front" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#7accfb"/><stop offset="1" stop-color="#37a0ef"/></linearGradient></defs><path d="M5 10c0-3.31 2.69-6 6-6h10.9c1.6 0 3.13.7 4.18 1.9l1.5 1.73a3.5 3.5 0 0 0 2.64 1.22H54c2.76 0 5 2.24 5 5V40c0 3.87-3.13 7-7 7H12c-3.87 0-7-3.13-7-7V10Z" fill="url(#fs-folder-back)"/><path d="M5 15.5h54V40c0 3.87-3.13 7-7 7H12c-3.87 0-7-3.13-7-7V15.5Z" fill="url(#fs-folder-front)"/></svg>`\n\nconst FOLDER_GLYPH_DATA_URL = `data:image/svg+xml,${encodeURIComponent(FOLDER_GLYPH_SVG)}`\n\nfunction FileSystemFolderGlyph({ className }: { className?: string }) {\n return (\n <img\n src={FOLDER_GLYPH_DATA_URL}\n alt=""\n aria-hidden="true"\n draggable={false}\n className={className}\n />\n )\n}\n\nfunction escapeXmlAttribute(value: string) {\n return value\n .replaceAll("&", "&")\n .replaceAll("<", "<")\n .replaceAll(">", ">")\n .replaceAll(\'"\', """)\n}\n\n// The @pierre/trees "complete" set — the full, colored suite with brand and\n// framework glyphs — ships as an SVG sprite. The list view tree consumes it\n// natively inside its shadow DOM; the icon, column, and gallery views render\n// the same sprite from the light DOM so every view falls back to the same\n// file-type icon when a file has no thumbnail.\nconst FILE_ICON_SPRITE_SHEET = getBuiltInSpriteSheet("complete")\n\nconst { resolveIcon: resolveFileIcon } = createFileTreeIconResolver({\n colored: true,\n set: "complete",\n})\n\n// Per-token light/dark colors mirroring the palette the tree applies inside\n// its shadow DOM. Tokens without an entry (font, nextjs, stylelint) stay\n// muted-foreground there too.\nconst FILE_ICON_COLORS: Record<string, [light: string, dark: string]> = {\n astro: ["#a631be", "#d568ea"],\n babel: ["#d5a910", "#ffd452"],\n bash: ["#199f43", "#5ecc71"],\n biome: ["#1a85d4", "#69b1ff"],\n bootstrap: ["#693acf", "#9d6afb"],\n browserslist: ["#d5a910", "#ffd452"],\n bun: ["#594c5b", "#79697b"],\n c: ["#1a85d4", "#69b1ff"],\n claude: ["#d47628", "#ffa359"],\n cpp: ["#1a85d4", "#69b1ff"],\n css: ["#693acf", "#9d6afb"],\n database: ["#a631be", "#d568ea"],\n default: ["#84848a", "#adadb1"],\n docker: ["#1a85d4", "#69b1ff"],\n eslint: ["#693acf", "#9d6afb"],\n git: ["#ff8c5b", "#d5512f"],\n go: ["#1ca1c7", "#68cdf2"],\n graphql: ["#d32a61", "#ff678d"],\n html: ["#d47628", "#ffa359"],\n image: ["#d32a61", "#ff678d"],\n javascript: ["#d5a910", "#ffd452"],\n json: ["#d47628", "#ffa359"],\n markdown: ["#199f43", "#5ecc71"],\n mcp: ["#17a5af", "#64d1db"],\n npm: ["#d52c36", "#ff6762"],\n oxc: ["#1ca1c7", "#68cdf2"],\n postcss: ["#d52c36", "#ff6762"],\n prettier: ["#17a5af", "#64d1db"],\n python: ["#1a85d4", "#69b1ff"],\n react: ["#1ca1c7", "#68cdf2"],\n ruby: ["#d52c36", "#ff6762"],\n rust: ["#d47628", "#ffa359"],\n sass: ["#d32a61", "#ff678d"],\n svelte: ["#d52c36", "#ff6762"],\n svg: ["#d47628", "#ffa359"],\n svgo: ["#199f43", "#5ecc71"],\n swift: ["#d47628", "#ffa359"],\n table: ["#17a5af", "#64d1db"],\n tailwind: ["#1ca1c7", "#68cdf2"],\n terraform: ["#693acf", "#9d6afb"],\n text: ["#84848a", "#adadb1"],\n typescript: ["#1a85d4", "#69b1ff"],\n vite: ["#a631be", "#d568ea"],\n vscode: ["#1a85d4", "#69b1ff"],\n vue: ["#199f43", "#5ecc71"],\n wasm: ["#693acf", "#9d6afb"],\n webpack: ["#1a85d4", "#69b1ff"],\n yml: ["#d52c36", "#ff6762"],\n zig: ["#d47628", "#ffa359"],\n zip: ["#d47628", "#ffa359"],\n}\n\nfunction fileIconColorVariables(mode: 0 | 1) {\n return Object.entries(FILE_ICON_COLORS)\n .map(([token, colors]) => `--fs-file-icon-${token}: ${colors[mode]};`)\n .join(" ")\n}\n\n// The variables live on :root rather than the component root because the\n// filter menus and dialogs portal outside it; the --fs-file-icon-*\n// namespace keeps them collision-free. Thumbnail tiles keep a light\n// (paper) surface in dark mode, so icons inside them revert to the light\n// palette ([data-file-system-on-light]); selected rows sit on the primary\n// surface — the opposite of the mode\'s background — so icons there swap to\n// the opposite palette ([data-file-system-on-primary] in the light DOM,\n// --fs-selected-color-scheme for the tree\'s light-dark() colors inside its\n// shadow DOM).\nconst FILE_ICON_COLOR_CSS = `\n:root { ${fileIconColorVariables(0)} --fs-selected-color-scheme: dark; }\n.dark { ${fileIconColorVariables(1)} --fs-selected-color-scheme: light; }\n.dark [data-file-system-on-light] { ${fileIconColorVariables(0)} }\n[data-file-system-on-primary] { ${fileIconColorVariables(1)} }\n.dark [data-file-system-on-primary] { ${fileIconColorVariables(0)} }\n`\n\nfunction FileSystemIconSpriteSheet() {\n return (\n <>\n <span\n aria-hidden="true"\n className="hidden"\n dangerouslySetInnerHTML={{ __html: FILE_ICON_SPRITE_SHEET }}\n />\n <style>{FILE_ICON_COLOR_CSS}</style>\n </>\n )\n}\n\nfunction FileTypeIcon({\n fileName,\n className,\n}: {\n fileName: string\n className?: string\n}) {\n const icon = resolveFileIcon("file-tree-icon-file", fileName)\n\n return (\n <svg\n aria-hidden="true"\n viewBox={icon.viewBox ?? "0 0 16 16"}\n className={cn("shrink-0 text-muted-foreground", className)}\n style={\n icon.token\n ? {\n color: `var(--fs-file-icon-${icon.token}, var(--color-muted-foreground))`,\n }\n : undefined\n }\n >\n <use href={`#${icon.name}`} />\n </svg>\n )\n}\n\nfunction FileGenericPreview({ file }: { file: FileEntry }) {\n const extension = fileExtension(file.name)\n\n return (\n <div\n data-file-system-on-light=""\n className="flex size-full flex-col items-center justify-center gap-1.5 bg-white text-neutral-400 dark:bg-neutral-100"\n >\n <FileTypeIcon fileName={file.name} className="size-1/3 min-h-4 min-w-4" />\n {extension ? (\n <span className="text-[min(0.625rem,18cqw)] font-semibold tracking-wide uppercase">\n {extension}\n </span>\n ) : null}\n </div>\n )\n}\n\nfunction filePreviewUrls(file: FileSystemFileItem) {\n if (file.previewImageUrls?.length) return file.previewImageUrls\n return file.previewImageUrl ? [file.previewImageUrl] : []\n}\n\n// Mirrors @pierre/trees\' query normalization so the toolbar search filters\n// the icon, column, and gallery views exactly like the list view tree:\n// trimmed, backslashes to slashes, lowercased, substring match on the path.\nfunction normalizeSearchQuery(value: string) {\n const trimmed = value.trim()\n\n if (!trimmed) return ""\n return trimmed.replaceAll("\\\\", "/").toLowerCase()\n}\n\n// Windowed rendering, the approach @pierre/trees uses for the list view:\n// with a fixed item stride only the items intersecting the viewport — plus\n// `overscan` on each side — are mounted, so views stay flat-cost at\n// thousands of entries. The window keeps a one-item margin before\n// recomputing (scrolling doesn\'t re-render per item) and that margin also\n// guarantees single-step keyboard moves land on a mounted neighbor.\nfunction useVirtualWindow({\n count,\n horizontal = false,\n itemStride,\n leadingPx = 0,\n overscan = 8,\n viewportRef,\n}: {\n count: number\n horizontal?: boolean\n itemStride: number\n leadingPx?: number\n overscan?: number\n viewportRef: React.RefObject<HTMLDivElement | null>\n}) {\n const [window_, setWindow] = React.useState(() => ({\n end: Math.min(count, overscan * 2),\n start: 0,\n }))\n\n React.useLayoutEffect(() => {\n const viewport = viewportRef.current\n\n if (!viewport || itemStride <= 0) return\n\n const update = () => {\n const scrollStart =\n (horizontal ? viewport.scrollLeft : viewport.scrollTop) - leadingPx\n const viewportSize = horizontal\n ? viewport.clientWidth\n : viewport.clientHeight\n const firstVisible = Math.max(0, Math.floor(scrollStart / itemStride))\n const lastVisible = Math.min(\n count,\n Math.ceil((scrollStart + viewportSize) / itemStride)\n )\n\n setWindow((previous) => {\n if (\n previous.end <= count &&\n previous.start <= Math.max(0, firstVisible - 1) &&\n previous.end >= Math.min(count, lastVisible + 1)\n ) {\n return previous\n }\n return {\n end: Math.min(count, lastVisible + overscan),\n start: Math.max(0, firstVisible - overscan),\n }\n })\n }\n\n update()\n viewport.addEventListener("scroll", update, { passive: true })\n\n const observer =\n typeof ResizeObserver === "undefined" ? null : new ResizeObserver(update)\n\n observer?.observe(viewport)\n return () => {\n viewport.removeEventListener("scroll", update)\n observer?.disconnect()\n }\n }, [count, horizontal, itemStride, leadingPx, overscan, viewportRef])\n\n return window_\n}\n\n// Scrolls the item at `index` into the viewport when it sits outside it —\n// virtualized views need this because off-window items have no DOM node to\n// call scrollIntoView on.\nfunction scrollIndexIntoView({\n horizontal = false,\n index,\n itemSize,\n itemStride,\n leadingPx = 0,\n viewport,\n}: {\n horizontal?: boolean\n index: number\n itemSize: number\n itemStride: number\n leadingPx?: number\n viewport: HTMLDivElement | null\n}) {\n if (!viewport || index < 0) return\n\n const start = leadingPx + index * itemStride\n const end = start + itemSize\n const scrollStart = horizontal ? viewport.scrollLeft : viewport.scrollTop\n const viewportSize = horizontal ? viewport.clientWidth : viewport.clientHeight\n\n let nextScrollStart: number | null = null\n\n if (start < scrollStart) {\n nextScrollStart = start\n } else if (end > scrollStart + viewportSize) {\n nextScrollStart = end - viewportSize\n }\n if (nextScrollStart === null) return\n if (horizontal) {\n viewport.scrollLeft = nextScrollStart\n } else {\n viewport.scrollTop = nextScrollStart\n }\n}\n\nfunction FileVisual({\n file,\n className,\n loadPreviewImageUrl,\n pageable = false,\n previewAspectRatio,\n previewClassName,\n renderFilePreview,\n}: {\n file: FileEntry\n className?: string\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n /** Show a hover pager over multi-page thumbnails. */\n pageable?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n}) {\n const previewUrls = filePreviewUrls(file)\n const canLoadLazily = pageable && Boolean(loadPreviewImageUrl)\n const totalPages = Math.max(\n previewUrls.length,\n canLoadLazily ? (file.previewPageCount ?? 0) : 0\n )\n const [pageIndex, setPageIndex] = React.useState(0)\n const [lazyPageUrls, setLazyPageUrls] = React.useState<\n Record<number, string>\n >({})\n const clampedPageIndex = Math.min(pageIndex, Math.max(totalPages - 1, 0))\n const previewUrl =\n previewUrls[clampedPageIndex] ?? lazyPageUrls[clampedPageIndex] ?? null\n const resolvedAspectRatio = file.previewAspectRatio ?? previewAspectRatio\n const isLazyPagePending =\n canLoadLazily && !previewUrl && clampedPageIndex < totalPages\n\n const fileRef = React.useRef(file)\n\n React.useEffect(() => {\n fileRef.current = file\n })\n\n React.useEffect(() => {\n setPageIndex(0)\n setLazyPageUrls({})\n }, [file.path])\n\n // Keyed by path (not object identity) so manifest churn doesn\'t re-request\n // the page already being loaded.\n React.useEffect(() => {\n if (!isLazyPagePending || !loadPreviewImageUrl) return\n\n let isCurrent = true\n\n void loadPreviewImageUrl(fileRef.current, clampedPageIndex)\n .then((url) => {\n if (isCurrent && url) {\n setLazyPageUrls((previous) => ({\n ...previous,\n [clampedPageIndex]: url,\n }))\n }\n })\n .catch(() => {})\n\n return () => {\n isCurrent = false\n }\n }, [clampedPageIndex, file.path, isLazyPagePending, loadPreviewImageUrl])\n\n const customPreview =\n !previewUrl && !isLazyPagePending ? renderFilePreview?.(file) : null\n const showPager = pageable && totalPages > 1\n const thumbnail = (\n <FileThumbnail\n file={{ name: file.name, type: file.contentType ?? "" }}\n className={cn("@container", !showPager && className)}\n previewAspectRatio={resolvedAspectRatio}\n previewClassName={cn("bg-white dark:bg-neutral-100", previewClassName)}\n previewImageUrl={previewUrl ?? undefined}\n isLoading={isLazyPagePending}\n previewContent={\n previewUrl || isLazyPagePending\n ? undefined\n : (customPreview ?? <FileGenericPreview file={file} />)\n }\n />\n )\n\n if (!showPager) return thumbnail\n\n return (\n <div className={cn("group/pager relative", className)}>\n {thumbnail}\n <div className="absolute inset-x-0 bottom-1.5 flex items-center justify-center gap-1 opacity-0 transition-opacity group-focus-within/pager:opacity-100 group-hover/pager:opacity-100">\n <button\n type="button"\n aria-label="Previous page"\n tabIndex={-1}\n disabled={clampedPageIndex === 0}\n onClick={(event) => {\n event.stopPropagation()\n setPageIndex((previous) => Math.max(0, previous - 1))\n }}\n onDoubleClick={(event) => event.stopPropagation()}\n className="flex size-6 items-center justify-center rounded-md bg-background/80 text-foreground shadow-xs backdrop-blur-sm transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />\n </button>\n <span className="rounded-md bg-background/80 px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground tabular-nums shadow-xs backdrop-blur-sm">\n {clampedPageIndex + 1}/{totalPages}\n </span>\n <button\n type="button"\n aria-label="Next page"\n tabIndex={-1}\n disabled={clampedPageIndex >= totalPages - 1}\n onClick={(event) => {\n event.stopPropagation()\n setPageIndex((previous) => Math.min(totalPages - 1, previous + 1))\n }}\n onDoubleClick={(event) => event.stopPropagation()}\n className="flex size-6 items-center justify-center rounded-md bg-background/80 text-foreground shadow-xs backdrop-blur-sm transition-colors outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-3.5" />\n </button>\n </div>\n </div>\n )\n}\n\nconst VIEW_OPTIONS: Array<{\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n label: string\n value: FileSystemView\n}> = [\n { icon: GridViewIcon, label: "Grid", value: "icons" },\n { icon: LeftToRightListBulletIcon, label: "List", value: "list" },\n { icon: LayoutThreeColumnIcon, label: "Columns", value: "columns" },\n { icon: GalleryThumbnailsIcon, label: "Gallery", value: "gallery" },\n]\n\nexport function FileSystem({\n items,\n className,\n title = "Files",\n defaultView = "icons",\n view: viewProp,\n onViewChange,\n defaultPath = "",\n onSelectionChange,\n onFileOpen,\n getFileUrl,\n loadChildren,\n loadPreviewImageUrl,\n renderFilePreview,\n}: FileSystemProps) {\n const [internalView, setInternalView] = React.useState(defaultView)\n const view = viewProp ?? internalView\n const setView = React.useCallback(\n (nextView: FileSystemView) => {\n setInternalView(nextView)\n onViewChange?.(nextView)\n },\n [onViewChange]\n )\n\n const [loadedItems, setLoadedItems] = React.useState<FileSystemItem[]>([])\n const allItems = React.useMemo(\n () => (loadedItems.length ? [...items, ...loadedItems] : items),\n [items, loadedItems]\n )\n const index = React.useMemo(() => buildFileSystemIndex(allItems), [allItems])\n\n const [history, setHistory] = React.useState(() => ({\n index: 0,\n stack: [normalizeFolderPath(defaultPath)],\n }))\n const currentPath = history.stack[history.index] ?? ""\n const canGoBack = history.index > 0\n const canGoForward = history.index < history.stack.length - 1\n\n const [selectedPath, setSelectedPath] = React.useState<string | null>(null)\n const selectedEntry = React.useMemo(() => {\n if (selectedPath === null) return null\n\n return (\n index.files.get(selectedPath) ?? index.folders.get(selectedPath) ?? null\n )\n }, [index, selectedPath])\n\n const [searchInput, setSearchInput] = React.useState("")\n const searchInputRef = React.useRef<HTMLInputElement | null>(null)\n const [isSearchExpanded, setIsSearchExpanded] = React.useState(false)\n const searchQuery = normalizeSearchQuery(searchInput)\n const isSearching = searchQuery.length > 0\n\n const [sort, setSort] = React.useState(DEFAULT_SORT)\n const [filters, setFilters] = React.useState<FileSystemFilter[]>([])\n const hasActiveFilters = filters.length > 0\n\n // Files must pass every active filter; folders stay visible through\n // matching descendants, so the predicate only ever sees files.\n const fileFilter = React.useMemo(() => {\n if (filters.length === 0) return null\n return (file: FileEntry) =>\n filters.every((filter) => fileMatchesFilter(file, filter))\n }, [filters])\n\n // Paths that stay visible while searching or filtering: every file whose\n // currentPath-relative path contains the query — the list view tree\'s\n // hide-non-matches semantics — and that passes the filters, plus the\n // ancestor folders leading to it. Folder names participate in search\n // matches only when no filters are active; with filters, a folder is only\n // as visible as the files inside it.\n const visiblePaths = React.useMemo(() => {\n if (!isSearching && !fileFilter) return null\n\n const visible = new Set<string>()\n const markVisible = (path: string) => {\n while (path && path !== currentPath && !visible.has(path)) {\n visible.add(path)\n path = pathParent(path)\n }\n }\n const matchesQuery = (path: string) =>\n !isSearching ||\n path.slice(currentPath.length).toLowerCase().includes(searchQuery)\n\n for (const [path, file] of index.files) {\n if (path === currentPath) continue\n if (currentPath && !path.startsWith(currentPath)) continue\n if (!matchesQuery(path)) continue\n if (fileFilter && !fileFilter(file)) continue\n markVisible(path)\n }\n if (!fileFilter) {\n for (const path of index.folders.keys()) {\n if (path === currentPath) continue\n if (currentPath && !path.startsWith(currentPath)) continue\n if (matchesQuery(path)) markVisible(path)\n }\n }\n return visible\n }, [currentPath, fileFilter, index, isSearching, searchQuery])\n\n const visibleIndex = React.useMemo(() => {\n if (!visiblePaths) return index\n\n const children = new Map<string, FileSystemEntry[]>()\n\n for (const [parentPath, parentChildren] of index.children) {\n const visibleChildren = parentChildren.filter((entry) =>\n visiblePaths.has(entry.path)\n )\n\n if (visibleChildren.length) children.set(parentPath, visibleChildren)\n }\n return { ...index, children }\n }, [index, visiblePaths])\n\n // Children re-sorted per the active sort; the default (name ascending)\n // reuses the index\'s pre-sorted arrays untouched.\n const sortedIndex = React.useMemo(() => {\n if (\n sort.key === DEFAULT_SORT.key &&\n sort.direction === DEFAULT_SORT.direction\n ) {\n return visibleIndex\n }\n\n const children = new Map<string, FileSystemEntry[]>()\n\n for (const [parentPath, parentChildren] of visibleIndex.children) {\n children.set(\n parentPath,\n [...parentChildren].sort((left, right) =>\n compareEntriesBySort(left, right, sort)\n )\n )\n }\n return { ...visibleIndex, children }\n }, [sort, visibleIndex])\n\n // The ref mirrors the state so re-selecting the same entry (e.g. the\n // pointerdown + click pair the columns view emits per press) stays a\n // no-op without widening the callback\'s dependencies.\n const selectedPathRef = React.useRef<string | null>(null)\n const selectEntry = React.useCallback(\n (entry: FileSystemEntry | null) => {\n const path = entry?.path ?? null\n\n if (selectedPathRef.current === path) return\n selectedPathRef.current = path\n setSelectedPath(path)\n onSelectionChange?.(entry)\n },\n [onSelectionChange]\n )\n\n // A query or filter change can hide the selected entry out from under the\n // views.\n React.useEffect(() => {\n if (!visiblePaths || !selectedPath) return\n if (!visiblePaths.has(selectedPath)) selectEntry(null)\n }, [selectEntry, selectedPath, visiblePaths])\n\n const applySortKey = React.useCallback((key: FileSystemSortKey) => {\n setSort((previous) =>\n previous.key === key\n ? previous\n : { direction: defaultSortDirection(key), key }\n )\n }, [])\n\n // Column headers toggle the direction when the column is already active,\n // like Finder.\n const toggleSortColumn = React.useCallback((key: FileSystemSortKey) => {\n setSort((previous) =>\n previous.key === key\n ? { direction: previous.direction === "asc" ? "desc" : "asc", key }\n : { direction: defaultSortDirection(key), key }\n )\n }, [])\n\n // Distinct MIME types across the loaded manifest, labeled for the filter\n // menu; the first file seen per type lends its name to the option icon.\n const fileTypeOptions = React.useMemo(() => {\n const byMime = new Map<string, FileTypeFilterOption>()\n\n for (const file of index.files.values()) {\n const mime = mimeTypeForFile(file)\n\n if (!byMime.has(mime)) {\n byMime.set(mime, {\n iconFileName: file.name,\n label: MIME_TYPE_LABELS[mime] ?? mime,\n mime,\n })\n }\n }\n return [...byMime.values()].sort((left, right) =>\n left.label.localeCompare(right.label)\n )\n }, [index])\n\n const filterIdRef = React.useRef(0)\n const [dateRangeDialog, setDateRangeDialog] = React.useState<{\n initialRange?: { from: Date; to: Date }\n type: FileSystemDateFilterType\n } | null>(null)\n\n const toggleFileTypeFilterValue = React.useCallback(\n (mime: string, checked: boolean) => {\n const id = `filter-${++filterIdRef.current}`\n\n setFilters((previous) => {\n const existing = previous.find((filter) => filter.type === "fileType")\n\n if (!existing) {\n if (!checked) return previous\n return [\n ...previous,\n {\n id,\n operator: "is" as const,\n type: "fileType" as const,\n value: [mime],\n },\n ]\n }\n\n const value = checked\n ? [...new Set([...existing.value, mime])]\n : existing.value.filter((entry) => entry !== mime)\n\n if (value.length === 0) {\n return previous.filter((filter) => filter !== existing)\n }\n\n // "is" and "is any of" track the value count; "is not" is unaffected.\n const operator =\n existing.operator === "is" || existing.operator === "is-any-of"\n ? value.length > 1\n ? ("is-any-of" as const)\n : ("is" as const)\n : existing.operator\n\n return previous.map((filter) =>\n filter === existing ? { ...filter, operator, value } : filter\n )\n })\n },\n []\n )\n\n const setDatePresetFilter = React.useCallback(\n (type: FileSystemDateFilterType, preset: string) => {\n const id = `filter-${++filterIdRef.current}`\n\n setFilters((previous) => [\n ...previous.filter((filter) => filter.type !== type),\n { id, operator: "after", type, value: [preset] },\n ])\n },\n []\n )\n\n // Editing an existing custom range seeds the dialog with its bounds.\n const openDateRangeDialog = React.useCallback(\n (type: FileSystemDateFilterType) => {\n const existing = filters.find((filter) => filter.type === type)\n\n setDateRangeDialog({\n initialRange:\n existing && isCustomDateRangeValue(existing.value)\n ? {\n from: new Date(existing.value[0]),\n to: new Date(existing.value[1]),\n }\n : undefined,\n type,\n })\n },\n [filters]\n )\n\n const applyCustomDateRange = React.useCallback(\n (type: FileSystemDateFilterType, from: Date, to: Date) => {\n const id = `filter-${++filterIdRef.current}`\n\n setFilters((previous) => {\n const existing = previous.find((filter) => filter.type === type)\n\n return [\n ...previous.filter((filter) => filter.type !== type),\n {\n id,\n operator:\n existing?.operator === "not-in-range"\n ? ("not-in-range" as const)\n : ("in-range" as const),\n type,\n value: [from.toISOString(), to.toISOString()],\n },\n ]\n })\n },\n []\n )\n\n // Below 560px the tabs view switcher no longer fits in the toolbar and\n // collapses into a select while the search input collapses into a popover;\n // below 360px the select labels and the folder name are dropped too,\n // leaving icons only.\n const rootRef = React.useRef<HTMLDivElement | null>(null)\n const [headerLayout, setHeaderLayout] = React.useState<\n "full" | "compact" | "minimal"\n >("full")\n\n React.useEffect(() => {\n const root = rootRef.current\n\n if (!root || typeof ResizeObserver === "undefined") return\n\n const applyWidth = (width: number | undefined) => {\n if (width === undefined) return\n\n setHeaderLayout(\n width < 360 ? "minimal" : width < 560 ? "compact" : "full"\n )\n }\n const observer = new ResizeObserver((observerEntries) =>\n applyWidth(observerEntries[0]?.contentRect.width)\n )\n\n // Measure synchronously so the first painted layout is already correct;\n // the observer then tracks resizes.\n applyWidth(root.clientWidth)\n observer.observe(root)\n return () => observer.disconnect()\n }, [])\n\n const requestedFoldersRef = React.useRef(new Set<string>())\n const [loadingFolders, setLoadingFolders] = React.useState<Set<string>>(\n () => new Set()\n )\n const ensureChildren = React.useCallback(\n (folderPath: string) => {\n if (!loadChildren) return\n\n const folder = index.folders.get(folderPath)\n\n if (!folder?.hasChildren) return\n if (index.children.get(folderPath)?.length) return\n if (requestedFoldersRef.current.has(folderPath)) return\n\n requestedFoldersRef.current.add(folderPath)\n setLoadingFolders((previous) => new Set(previous).add(folderPath))\n\n void (async () => {\n try {\n let cursor: string | null = null\n\n do {\n const result = await loadChildren({ cursor, path: folderPath })\n\n if (result.items.length) {\n setLoadedItems((previous) => [...previous, ...result.items])\n }\n cursor = result.nextCursor ?? null\n } while (cursor)\n } catch {\n requestedFoldersRef.current.delete(folderPath)\n } finally {\n setLoadingFolders((previous) => {\n const next = new Set(previous)\n\n next.delete(folderPath)\n return next\n })\n }\n })()\n },\n [index, loadChildren]\n )\n\n const navigateTo = React.useCallback(\n (folderPath: string) => {\n const path = normalizeFolderPath(folderPath)\n\n setHistory((previous) => {\n if (previous.stack[previous.index] === path) return previous\n\n const stack = [...previous.stack.slice(0, previous.index + 1), path]\n\n return { index: stack.length - 1, stack }\n })\n // Navigation exits search, like Finder.\n setSearchInput("")\n selectEntry(null)\n ensureChildren(path)\n },\n [ensureChildren, selectEntry]\n )\n\n React.useEffect(() => {\n ensureChildren(currentPath)\n }, [currentPath, ensureChildren])\n\n // Navigation unmounts the focused row, dropping focus to <body> and killing\n // the ⌘ shortcuts; reclaim focus onto the component root when that happens.\n const hasNavigatedRef = React.useRef(false)\n\n React.useEffect(() => {\n if (!hasNavigatedRef.current) {\n hasNavigatedRef.current = true\n return\n }\n\n const root = rootRef.current\n\n if (root && document.activeElement === document.body) {\n root.focus()\n }\n }, [currentPath])\n\n const [openedFile, setOpenedFile] = React.useState<{\n file: FileEntry\n kind: FileSystemViewerKind\n url: string\n } | null>(null)\n\n const openFile = React.useCallback(\n (file: FileEntry) => {\n void (async () => {\n let url = file.url ?? null\n\n if (!url && getFileUrl) {\n try {\n url = await getFileUrl(file)\n } catch {\n url = null\n }\n }\n if (onFileOpen) {\n onFileOpen(file, url)\n return\n }\n\n const kind = viewerKindForFile(file)\n\n if (kind && url) {\n setOpenedFile({ file, kind, url })\n } else if (url && typeof window !== "undefined") {\n window.open(url, "_blank", "noopener,noreferrer")\n }\n })()\n },\n [getFileUrl, onFileOpen]\n )\n\n const openEntry = React.useCallback(\n (entry: FileSystemEntry) => {\n if (entry.kind === "folder") {\n navigateTo(entry.path)\n } else {\n openFile(entry)\n }\n },\n [navigateTo, openFile]\n )\n\n // Selecting a lazy folder (columns view, keyboard nav) prefetches children.\n const selectAndPrefetchEntry = React.useCallback(\n (entry: FileSystemEntry | null) => {\n selectEntry(entry)\n if (entry?.kind === "folder") ensureChildren(entry.path)\n },\n [ensureChildren, selectEntry]\n )\n\n const goBack = React.useCallback(() => {\n setHistory((previous) => ({\n ...previous,\n index: Math.max(0, previous.index - 1),\n }))\n setSearchInput("")\n selectEntry(null)\n }, [selectEntry])\n\n const goForward = React.useCallback(() => {\n setHistory((previous) => ({\n ...previous,\n index: Math.min(previous.stack.length - 1, previous.index + 1),\n }))\n setSearchInput("")\n selectEntry(null)\n }, [selectEntry])\n\n const currentEntries = sortedIndex.children.get(currentPath) ?? []\n const currentFolderName =\n currentPath === "" ? title : pathName(currentPath) || title\n const isLoadingCurrentFolder = loadingFolders.has(currentPath)\n\n // The list view tree saves its expanded folders here when it unmounts\n // (view switches, navigation) so returning to the list view — or to a\n // previously visited folder — restores the same disclosure state.\n const treeExpansionRef = React.useRef(new Map<string, readonly string[]>())\n\n const viewProps: FileSystemViewProps = {\n currentPath,\n entries: currentEntries,\n fileFilter,\n getFileUrl,\n index: sortedIndex,\n loadPreviewImageUrl,\n loadingFolders,\n onOpen: openEntry,\n onSelect: selectAndPrefetchEntry,\n onSortColumnClick: toggleSortColumn,\n renderFilePreview,\n searchQuery,\n selectedEntry,\n selectedPath,\n sort,\n treeExpansionRef,\n }\n\n const openedFileName = openedFile\n ? (openedFile.file.name ?? openedFile.file.path)\n : ""\n const activeViewOption = VIEW_OPTIONS.find((option) => option.value === view)\n const viewerCloseToolbarAction = (\n <DialogClose\n aria-label="Close preview"\n render={<Button type="button" variant="ghost" size="icon-sm" />}\n >\n <HugeiconsIcon icon={Cancel01Icon} className="size-4" />\n </DialogClose>\n )\n\n return (\n <div\n ref={rootRef}\n tabIndex={-1}\n data-slot="file-system"\n onKeyDown={(event) => {\n // ⌘F focuses the toolbar search while focus is inside the component.\n if ((event.metaKey || event.ctrlKey) && event.key === "f") {\n event.preventDefault()\n setIsSearchExpanded(true)\n searchInputRef.current?.focus()\n }\n }}\n className={cn(\n "flex h-[480px] min-h-0 flex-col overflow-hidden rounded-xl border bg-background text-foreground outline-none",\n className\n )}\n >\n <FileSystemIconSpriteSheet />\n <div className="relative grid h-12 shrink-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-2 border-b bg-muted/40 px-2">\n <div className="flex min-w-0 items-center gap-0.5">\n <button\n type="button"\n aria-label="Back"\n title="Back"\n disabled={!canGoBack}\n onClick={goBack}\n className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4.5" />\n </button>\n <button\n type="button"\n aria-label="Forward"\n title="Forward"\n disabled={!canGoForward}\n onClick={goForward}\n className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-4.5" />\n </button>\n {headerLayout !== "minimal" ? (\n <span className="ml-1.5 truncate text-sm font-semibold">\n {currentFolderName}\n </span>\n ) : null}\n </div>\n {headerLayout !== "full" ? (\n <Select\n value={view}\n onValueChange={(value) => setView(value as FileSystemView)}\n >\n <SelectTrigger\n size="sm"\n aria-label="View"\n // Icon-only like the sort select: sheds the base min-width to\n // hug icon + chevron at the filter button\'s 28px height.\n className="h-7 min-h-7 w-auto min-w-0 [&_svg]:size-4"\n >\n <SelectValue>\n {activeViewOption ? (\n <HugeiconsIcon\n icon={activeViewOption.icon}\n className="size-4"\n />\n ) : null}\n </SelectValue>\n </SelectTrigger>\n <SelectContent>\n {VIEW_OPTIONS.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n <span className="flex items-center gap-2">\n <HugeiconsIcon icon={option.icon} className="size-4" />\n {option.label}\n </span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : (\n <Tabs\n value={view}\n onValueChange={(value) => setView(value as FileSystemView)}\n className="gap-0"\n >\n <TabsList className="h-8 p-0.5">\n {VIEW_OPTIONS.map((option) => (\n <TabsTrigger\n key={option.value}\n value={option.value}\n aria-label={`${option.label} view`}\n title={option.label}\n className="h-7 grow-0 px-2.5 sm:h-7"\n >\n <HugeiconsIcon icon={option.icon} className="size-4" />\n </TabsTrigger>\n ))}\n </TabsList>\n </Tabs>\n )}\n <div className="flex min-w-0 items-center justify-end gap-1">\n <FileSystemSortSelect\n layout={headerLayout}\n onKeyChange={applySortKey}\n sort={sort}\n />\n <FileSystemFilterMenu\n fileTypeOptions={fileTypeOptions}\n filters={filters}\n onOpenCustomRange={openDateRangeDialog}\n onSelectDatePreset={setDatePresetFilter}\n onToggleFileType={toggleFileTypeFilterValue}\n />\n <FileSystemSearchField\n inputRef={searchInputRef}\n isExpanded={isSearchExpanded}\n layout={headerLayout}\n onExpandedChange={setIsSearchExpanded}\n onValueChange={setSearchInput}\n value={searchInput}\n />\n </div>\n </div>\n {hasActiveFilters ? (\n <div className="flex shrink-0 flex-wrap items-center gap-1 border-b bg-muted/20 px-2 py-1.5 text-xs text-muted-foreground">\n {filters.map((filter) => {\n const dateFilterType =\n filter.type === "fileType" ? null : filter.type\n\n return (\n <FileSystemFilterPill\n key={filter.id}\n fileTypeOptions={fileTypeOptions}\n filter={filter}\n onOpenCustomRange={\n dateFilterType\n ? () => openDateRangeDialog(dateFilterType)\n : undefined\n }\n onOperatorChange={(operator) =>\n setFilters((previous) =>\n previous.map((entry) =>\n entry.id === filter.id ? { ...entry, operator } : entry\n )\n )\n }\n onRemove={() =>\n setFilters((previous) =>\n previous.filter((entry) => entry.id !== filter.id)\n )\n }\n onSelectDatePreset={(preset) =>\n setFilters((previous) =>\n previous.map((entry) =>\n entry.id === filter.id\n ? {\n ...entry,\n operator:\n entry.operator === "before" ||\n entry.operator === "after"\n ? entry.operator\n : "after",\n value: [preset],\n }\n : entry\n )\n )\n }\n onToggleFileType={toggleFileTypeFilterValue}\n />\n )\n })}\n <button\n type="button"\n onClick={() => setFilters([])}\n className="rounded-md px-1.5 py-0.5 transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"\n >\n Clear\n </button>\n </div>\n ) : null}\n <div className="relative min-h-0 flex-1">\n {isLoadingCurrentFolder && currentEntries.length === 0 ? (\n <FileSystemEmptyState label="Loading…" isLoading />\n ) : currentEntries.length === 0 &&\n (view !== "columns" || isSearching || hasActiveFilters) ? (\n <FileSystemEmptyState\n label={\n isSearching\n ? `No results for “${searchInput.trim()}”`\n : hasActiveFilters\n ? "No items match the active filters"\n : "This folder is empty"\n }\n />\n ) : view === "icons" ? (\n <FileSystemIconsView {...viewProps} />\n ) : view === "list" ? (\n <FileSystemListView {...viewProps} />\n ) : view === "columns" ? (\n <FileSystemColumnsView {...viewProps} />\n ) : (\n <FileSystemGalleryView {...viewProps} />\n )}\n </div>\n <div\n aria-live="polite"\n className="flex h-7 shrink-0 items-center justify-center gap-1 border-t bg-muted/40 px-3 text-xs text-muted-foreground"\n >\n <span>\n {currentEntries.length}{" "}\n {isSearching\n ? currentEntries.length === 1\n ? "result"\n : "results"\n : currentEntries.length === 1\n ? "item"\n : "items"}\n </span>\n {selectedEntry ? <span>· “{selectedEntry.name}” selected</span> : null}\n </div>\n <Dialog\n open={openedFile !== null}\n onOpenChange={(open) => {\n if (!open) setOpenedFile(null)\n }}\n >\n {openedFile ? (\n <DialogContent\n className={cn(\n "overflow-hidden p-0",\n VIEWER_DIALOG_CLASSNAMES[openedFile.kind]\n )}\n showCloseButton={openedFile.kind === "image"}\n >\n <DialogTitle className="sr-only">{openedFileName}</DialogTitle>\n {openedFile.kind === "pdf" ? (\n <React.Suspense fallback={<FileSystemViewerLoading />}>\n <LazyPDFViewer\n file={openedFile.url}\n className="h-full min-h-0 flex-1 overflow-hidden rounded-2xl"\n downloadFileName={openedFileName}\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n </React.Suspense>\n ) : openedFile.kind === "docx" ? (\n <React.Suspense fallback={<FileSystemViewerLoading />}>\n <LazyDocxViewerPreview\n src={openedFile.url}\n fileName={openedFileName}\n className="h-full min-h-0 flex-1"\n rounded\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n </React.Suspense>\n ) : openedFile.kind === "xlsx" ? (\n <React.Suspense fallback={<FileSystemViewerLoading />}>\n <LazyXlsxViewerPreview\n src={openedFile.url}\n fileName={openedFileName}\n className="h-full min-h-0 flex-1"\n rounded\n showUpload={false}\n toolbarActions={viewerCloseToolbarAction}\n />\n </React.Suspense>\n ) : (\n <img\n src={openedFile.url}\n alt={openedFileName}\n className="max-h-[88vh] w-auto max-w-full rounded-2xl object-contain"\n />\n )}\n </DialogContent>\n ) : null}\n </Dialog>\n {dateRangeDialog ? (\n <FileSystemDateRangeDialog\n initialRange={dateRangeDialog.initialRange}\n onApply={(from, to) => {\n applyCustomDateRange(dateRangeDialog.type, from, to)\n setDateRangeDialog(null)\n }}\n onClose={() => setDateRangeDialog(null)}\n />\n ) : null}\n </div>\n )\n}\n\n// Shared style for the ghost icon buttons in the toolbar.\nconst TOOLBAR_ICON_BUTTON_CLASSNAME =\n "flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"\n\n// macOS Finder-style toolbar search. At the full layout it sits inline in\n// the header\'s right column; at compact widths it collapses into a ghost\n// icon button that opens the input in a popover (a dot marks the button\n// while a query keeps filtering the views).\nfunction FileSystemSearchField({\n inputRef,\n isExpanded,\n layout,\n onExpandedChange,\n onValueChange,\n value,\n}: {\n inputRef: React.RefObject<HTMLInputElement | null>\n isExpanded: boolean\n layout: "full" | "compact" | "minimal"\n onExpandedChange: (isExpanded: boolean) => void\n onValueChange: (value: string) => void\n value: string\n}) {\n const isInline = layout === "full"\n\n React.useEffect(() => {\n if (!isInline && isExpanded) inputRef.current?.focus()\n }, [inputRef, isExpanded, isInline])\n\n const input = (\n <div\n className={cn(\n "relative flex h-7 min-w-0 flex-1 items-center rounded-lg border border-input bg-popover text-sm text-foreground shadow-xs/5 transition-shadow outline-none not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-focus-within:before:shadow-[0_1px_--theme(--color-black/4%)] focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-1 focus-within:ring-offset-background dark:bg-input/32 dark:not-focus-within:before:shadow-[0_-1px_--theme(--color-white/6%)]",\n isInline && "max-w-44"\n )}\n >\n <HugeiconsIcon\n icon={Search01Icon}\n className="pointer-events-none absolute left-2 size-3.5 text-muted-foreground"\n />\n <input\n ref={inputRef}\n type="text"\n role="searchbox"\n aria-label="Search files"\n placeholder="Search"\n value={value}\n onChange={(event) => onValueChange(event.target.value)}\n onKeyDown={(event) => {\n if (event.key !== "Escape") return\n event.preventDefault()\n event.stopPropagation()\n if (value) {\n onValueChange("")\n } else {\n onExpandedChange(false)\n event.currentTarget.blur()\n }\n }}\n className="h-full w-full min-w-0 rounded-[inherit] bg-transparent pr-6 pl-7 outline-none placeholder:text-muted-foreground"\n />\n {value ? (\n <button\n type="button"\n aria-label="Clear search"\n onClick={() => {\n onValueChange("")\n inputRef.current?.focus()\n }}\n className="absolute right-1 flex size-5 items-center justify-center rounded-sm text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"\n >\n <HugeiconsIcon icon={Cancel01Icon} className="size-3" />\n </button>\n ) : null}\n </div>\n )\n\n if (isInline) {\n // A fixed basis (not flex-1) keeps the whole toolbar cluster packed\n // against the header\'s right edge; the input shrinks first when the\n // header tightens.\n return <div className="flex w-44 min-w-9 items-center">{input}</div>\n }\n\n return (\n <Popover open={isExpanded} onOpenChange={onExpandedChange}>\n <PopoverTrigger\n render={\n <button\n type="button"\n aria-label="Search"\n title="Search"\n className={cn(TOOLBAR_ICON_BUTTON_CLASSNAME, "relative")}\n />\n }\n >\n <HugeiconsIcon icon={Search01Icon} className="size-4" />\n {value ? (\n <span className="absolute top-1 right-1 size-1.5 rounded-full bg-primary" />\n ) : null}\n </PopoverTrigger>\n <PopoverContent align="end" sideOffset={6} className="w-64 p-1">\n {input}\n </PopoverContent>\n </Popover>\n )\n}\n\n// Toolbar "sort by" select. The full layout shows the active key\'s label; at\n// compact widths the trigger collapses to the sort glyph + chevron.\nfunction FileSystemSortSelect({\n layout,\n onKeyChange,\n sort,\n}: {\n layout: "full" | "compact" | "minimal"\n onKeyChange: (key: FileSystemSortKey) => void\n sort: FileSystemSortState\n}) {\n const activeOption = SORT_OPTIONS.find((option) => option.key === sort.key)\n\n return (\n <Select\n value={sort.key}\n onValueChange={(value) => onKeyChange(value as FileSystemSortKey)}\n >\n <SelectTrigger\n size="sm"\n aria-label="Sort by"\n title="Sort by"\n className="h-7 min-h-7 w-auto min-w-0 shrink-0 [&_svg]:size-4"\n >\n <SelectValue>\n <span className="flex items-center gap-1.5">\n <HugeiconsIcon icon={ArrowUpDownIcon} className="size-4" />\n {layout === "full" ? activeOption?.triggerLabel : null}\n </span>\n </SelectValue>\n </SelectTrigger>\n <SelectContent align="end" alignItemWithTrigger={false}>\n {SORT_OPTIONS.map((option) => (\n <SelectItem key={option.key} value={option.key}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )\n}\n\n// Searchable file-type list (cmdk) rendered inside a menu popup, so the\n// long MIME list can be filtered by typing. Selection toggles stay open for\n// multi-select; ArrowUp/Down and Enter come from cmdk\'s combobox semantics.\nfunction FileSystemFileTypeCommand({\n checkedMimes,\n onToggle,\n options,\n}: {\n checkedMimes: string[]\n onToggle: (mime: string, checked: boolean) => void\n options: FileTypeFilterOption[]\n}) {\n const inputRef = React.useRef<HTMLInputElement | null>(null)\n\n // The menu focuses its popup when it opens; pull focus into the search\n // field so typing filters immediately.\n React.useEffect(() => {\n const frame = requestAnimationFrame(() => inputRef.current?.focus())\n\n return () => cancelAnimationFrame(frame)\n }, [])\n\n return (\n <Command\n // -m-1 spans the menu viewport\'s built-in padding so the search\n // field\'s bottom border runs edge to edge.\n className="-m-1 w-[calc(100%+--spacing(2))] bg-transparent"\n // cmdk owns the keyboard while focus is in the list; only Escape\n // (close the menu) and Tab continue outward.\n onKeyDown={(event) => {\n if (event.key !== "Escape" && event.key !== "Tab") {\n event.stopPropagation()\n }\n }}\n >\n <CommandInput\n ref={inputRef}\n placeholder="Search file types…"\n className="h-9"\n />\n <CommandList className="max-h-none">\n <CommandEmpty>No file types found.</CommandEmpty>\n <ScrollArea orientation="vertical" className="h-auto max-h-64">\n <CommandGroup>\n {options.map((option) => {\n const isChecked = checkedMimes.includes(option.mime)\n\n return (\n <CommandItem\n key={option.mime}\n value={option.label}\n keywords={[option.mime]}\n onSelect={() => onToggle(option.mime, !isChecked)}\n >\n <HugeiconsIcon\n icon={Tick02Icon}\n className={cn(\n "size-4 text-foreground",\n !isChecked && "opacity-0"\n )}\n />\n <FileTypeIcon\n fileName={option.iconFileName}\n className="size-4"\n />\n {option.label}\n </CommandItem>\n )\n })}\n </CommandGroup>\n </ScrollArea>\n </CommandList>\n </Command>\n )\n}\n\n// Toolbar filter menu: file types as a searchable checklist, dates as\n// single-select presets plus a custom range, mirroring Extend\'s table\n// filters.\nfunction FileSystemFilterMenu({\n fileTypeOptions,\n filters,\n onOpenCustomRange,\n onSelectDatePreset,\n onToggleFileType,\n}: {\n fileTypeOptions: FileTypeFilterOption[]\n filters: FileSystemFilter[]\n onOpenCustomRange: (type: FileSystemDateFilterType) => void\n onSelectDatePreset: (type: FileSystemDateFilterType, preset: string) => void\n onToggleFileType: (mime: string, checked: boolean) => void\n}) {\n const fileTypeFilter = filters.find((filter) => filter.type === "fileType")\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger\n render={\n <Button\n type="button"\n variant="outline"\n size="icon-sm"\n aria-label="Filter"\n title="Filter"\n className="relative size-7 sm:size-7"\n />\n }\n >\n <HugeiconsIcon icon={FilterIcon} className="size-4" />\n {filters.length > 0 ? (\n <span className="absolute top-1 right-1 size-1.5 rounded-full bg-primary" />\n ) : null}\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="min-w-44">\n <DropdownMenuSub>\n <DropdownMenuSubTrigger>\n <HugeiconsIcon\n icon={File01Icon}\n className="size-4 text-muted-foreground"\n />\n File type\n </DropdownMenuSubTrigger>\n <DropdownMenuSubContent className="w-60">\n <FileSystemFileTypeCommand\n checkedMimes={fileTypeFilter?.value ?? []}\n onToggle={onToggleFileType}\n options={fileTypeOptions}\n />\n </DropdownMenuSubContent>\n </DropdownMenuSub>\n {(["dateModified", "dateCreated"] as const).map((type) => (\n <DropdownMenuSub key={type}>\n <DropdownMenuSubTrigger>\n <HugeiconsIcon\n icon={Calendar03Icon}\n className="size-4 text-muted-foreground"\n />\n {FILTER_TYPE_LABELS[type]}\n </DropdownMenuSubTrigger>\n <DropdownMenuSubContent>\n <ScrollArea orientation="vertical" className="h-auto max-h-72">\n {DATE_FILTER_PRESETS.map((preset) => (\n <DropdownMenuItem\n key={preset}\n onClick={() => onSelectDatePreset(type, preset)}\n >\n {preset}\n </DropdownMenuItem>\n ))}\n <DropdownMenuItem onClick={() => onOpenCustomRange(type)}>\n Custom date range…\n </DropdownMenuItem>\n </ScrollArea>\n </DropdownMenuSubContent>\n </DropdownMenuSub>\n ))}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nconst FILTER_PILL_SEGMENT_CLASSNAME =\n "flex h-5 items-center gap-1 border border-l-0 bg-background px-1.5 whitespace-nowrap text-foreground"\n\nconst FILTER_PILL_BUTTON_CLASSNAME = cn(\n FILTER_PILL_SEGMENT_CLASSNAME,\n "transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"\n)\n\n// One applied filter, rendered as a segmented pill in the status bar:\n// type · operator · value · remove, each segment interactive like Extend\'s\n// table filter pills.\nfunction FileSystemFilterPill({\n fileTypeOptions,\n filter,\n onOpenCustomRange,\n onOperatorChange,\n onRemove,\n onSelectDatePreset,\n onToggleFileType,\n}: {\n fileTypeOptions: FileTypeFilterOption[]\n filter: FileSystemFilter\n onOpenCustomRange?: () => void\n onOperatorChange: (operator: FileSystemFilterOperator) => void\n onRemove: () => void\n onSelectDatePreset: (preset: string) => void\n onToggleFileType: (mime: string, checked: boolean) => void\n}) {\n const isCustomRange =\n filter.type !== "fileType" && isCustomDateRangeValue(filter.value)\n const selectedTypeLabels =\n filter.type === "fileType"\n ? filter.value.map(\n (mime) =>\n fileTypeOptions.find((option) => option.mime === mime)?.label ??\n mime\n )\n : []\n\n return (\n <div className="flex items-center text-xs">\n <span\n className={cn(\n FILTER_PILL_SEGMENT_CLASSNAME,\n "rounded-l-md border-l text-primary"\n )}\n >\n <HugeiconsIcon\n icon={filter.type === "fileType" ? File01Icon : Calendar03Icon}\n className="size-3"\n />\n {FILTER_TYPE_LABELS[filter.type]}\n </span>\n <DropdownMenu>\n <DropdownMenuTrigger\n render={\n <button\n type="button"\n className={cn(FILTER_PILL_BUTTON_CLASSNAME, "text-primary")}\n />\n }\n >\n {FILTER_OPERATOR_LABELS[filter.operator]}\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="min-w-28">\n {filterOperatorChoices(filter).map((operator) => (\n <DropdownMenuItem\n key={operator}\n onClick={() => onOperatorChange(operator)}\n >\n {FILTER_OPERATOR_LABELS[operator]}\n </DropdownMenuItem>\n ))}\n </DropdownMenuContent>\n </DropdownMenu>\n {filter.type === "fileType" ? (\n <DropdownMenu>\n <DropdownMenuTrigger\n render={\n <button\n type="button"\n title={selectedTypeLabels.join(", ")}\n className={FILTER_PILL_BUTTON_CLASSNAME}\n />\n }\n >\n {filter.value.length === 1\n ? selectedTypeLabels[0]\n : `${filter.value.length} selected`}\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="w-60">\n <FileSystemFileTypeCommand\n checkedMimes={filter.value}\n onToggle={onToggleFileType}\n options={fileTypeOptions}\n />\n </DropdownMenuContent>\n </DropdownMenu>\n ) : isCustomRange ? (\n <button\n type="button"\n onClick={onOpenCustomRange}\n className={FILTER_PILL_BUTTON_CLASSNAME}\n >\n {filter.value\n .map((value) => new Date(value).toLocaleDateString("en-US"))\n .join(" – ")}\n </button>\n ) : (\n <DropdownMenu>\n <DropdownMenuTrigger\n render={\n <button type="button" className={FILTER_PILL_BUTTON_CLASSNAME} />\n }\n >\n {filter.value[0]}\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start">\n <ScrollArea orientation="vertical" className="h-auto max-h-72">\n {DATE_FILTER_PRESETS.map((preset) => (\n <DropdownMenuItem\n key={preset}\n onClick={() => onSelectDatePreset(preset)}\n >\n {preset}\n </DropdownMenuItem>\n ))}\n <DropdownMenuItem onClick={onOpenCustomRange}>\n Custom date range…\n </DropdownMenuItem>\n </ScrollArea>\n </DropdownMenuContent>\n </DropdownMenu>\n )}\n <button\n type="button"\n aria-label={`Remove ${FILTER_TYPE_LABELS[filter.type]} filter`}\n onClick={onRemove}\n className={cn(\n FILTER_PILL_BUTTON_CLASSNAME,\n "rounded-r-md px-1 text-muted-foreground hover:text-foreground"\n )}\n >\n <HugeiconsIcon icon={Cancel01Icon} className="size-3" />\n </button>\n </div>\n )\n}\n\nfunction formatDateInputValue(date: Date | undefined) {\n if (!date) return ""\n\n const pad = (value: number) => String(value).padStart(2, "0")\n\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`\n}\n\nfunction parseDateInputValue(value: string) {\n const trimmed = value.trim()\n\n if (!trimmed) return undefined\n\n const isoMatch = /^(\\d{4})-(\\d{1,2})-(\\d{1,2})$/.exec(trimmed)\n\n if (isoMatch) {\n const date = new Date(\n Number(isoMatch[1]),\n Number(isoMatch[2]) - 1,\n Number(isoMatch[3])\n )\n\n return Number.isNaN(date.getTime()) ? undefined : date\n }\n\n const parsed = Date.parse(trimmed)\n\n return Number.isNaN(parsed) ? undefined : new Date(parsed)\n}\n\nconst DATE_RANGE_DIALOG_PRESETS = [\n "Last 7 days",\n "This month",\n "Last 1 month",\n "Last 3 months",\n "This year",\n "Last 12 months",\n]\n\nfunction dateRangePresetRange(preset: string) {\n const from = new Date()\n const to = new Date()\n\n from.setHours(0, 0, 0, 0)\n to.setHours(23, 59, 59, 999)\n\n switch (preset) {\n case "Last 7 days":\n from.setDate(from.getDate() - 6)\n break\n case "This month":\n from.setDate(1)\n break\n case "Last 1 month":\n from.setMonth(from.getMonth() - 1)\n break\n case "Last 3 months":\n from.setMonth(from.getMonth() - 3)\n break\n case "This year":\n from.setMonth(0, 1)\n break\n case "Last 12 months":\n from.setFullYear(from.getFullYear() - 1)\n break\n }\n return { from, to }\n}\n\nconst WEEKDAY_LABELS = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]\n\nfunction calendarDayKey(date: Date) {\n return date.getFullYear() * 10_000 + date.getMonth() * 100 + date.getDate()\n}\n\n// Two-month range calendar for the custom date range dialog (one month at\n// phone widths). Clicking sets the start, then the end; clicking before the\n// start swaps the ends, and a third click restarts the range.\nfunction FileSystemRangeCalendar({\n onSelect,\n range,\n}: {\n onSelect: (range: { from?: Date; to?: Date }) => void\n range: { from?: Date; to?: Date }\n}) {\n const [viewMonth, setViewMonth] = React.useState(() => {\n const base = range.from ?? new Date()\n\n return new Date(base.getFullYear(), base.getMonth(), 1)\n })\n const months = [\n viewMonth,\n new Date(viewMonth.getFullYear(), viewMonth.getMonth() + 1, 1),\n ]\n const fromKey = range.from ? calendarDayKey(range.from) : null\n const toKey = range.to ? calendarDayKey(range.to) : null\n const todayKey = calendarDayKey(new Date())\n\n const handleDayClick = (day: Date) => {\n if (!range.from || range.to) {\n onSelect({ from: day })\n } else if (calendarDayKey(day) < calendarDayKey(range.from)) {\n onSelect({ from: day, to: range.from })\n } else {\n onSelect({ from: range.from, to: day })\n }\n }\n\n return (\n <div className="relative">\n <button\n type="button"\n aria-label="Previous month"\n onClick={() =>\n setViewMonth(\n (previous) =>\n new Date(previous.getFullYear(), previous.getMonth() - 1, 1)\n )\n }\n className="absolute top-0 left-0 flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />\n </button>\n <button\n type="button"\n aria-label="Next month"\n onClick={() =>\n setViewMonth(\n (previous) =>\n new Date(previous.getFullYear(), previous.getMonth() + 1, 1)\n )\n }\n className="absolute top-0 right-0 flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"\n >\n <HugeiconsIcon icon={ArrowRight01Icon} className="size-4" />\n </button>\n <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">\n {months.map((month, monthIndex) => {\n const firstWeekday = month.getDay()\n const dayCount = new Date(\n month.getFullYear(),\n month.getMonth() + 1,\n 0\n ).getDate()\n const cells = [\n ...Array.from({ length: firstWeekday }, () => null),\n ...Array.from(\n { length: dayCount },\n (_, index) =>\n new Date(month.getFullYear(), month.getMonth(), index + 1)\n ),\n ]\n\n return (\n <div\n key={`${month.getFullYear()}-${month.getMonth()}`}\n className={cn(monthIndex === 1 && "max-sm:hidden")}\n >\n <div className="text-center text-sm leading-6 font-medium">\n {month.toLocaleDateString("en-US", {\n month: "long",\n year: "numeric",\n })}\n </div>\n <div className="mt-1 grid grid-cols-7 text-center text-xs text-muted-foreground">\n {WEEKDAY_LABELS.map((weekday) => (\n <span key={weekday} className="h-6 leading-6">\n {weekday}\n </span>\n ))}\n </div>\n <div className="grid grid-cols-7 gap-y-px">\n {cells.map((day, cellIndex) => {\n if (!day) return <span key={cellIndex} />\n\n const dayKey = calendarDayKey(day)\n const isFrom = dayKey === fromKey\n const isTo = dayKey === toKey\n const isWithinRange =\n fromKey !== null &&\n toKey !== null &&\n dayKey > fromKey &&\n dayKey < toKey\n\n return (\n <button\n key={cellIndex}\n type="button"\n onClick={() => handleDayClick(day)}\n className={cn(\n "flex h-7 items-center justify-center rounded-md text-xs tabular-nums transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",\n isWithinRange && "rounded-none bg-accent",\n (isFrom || isTo) &&\n "bg-primary text-primary-foreground hover:bg-primary",\n isFrom &&\n toKey !== null &&\n fromKey !== toKey &&\n "rounded-r-none",\n isTo && fromKey !== toKey && "rounded-l-none",\n dayKey === todayKey &&\n !isFrom &&\n !isTo &&\n "font-semibold text-primary"\n )}\n >\n {day.getDate()}\n </button>\n )\n })}\n </div>\n </div>\n )\n })}\n </div>\n </div>\n )\n}\n\n// Custom date range dialog mirroring Extend\'s table filters: From/To inputs,\n// a two-month range calendar, and quick presets. Applied ranges span from\n// the start of the first day to the end of the last.\nfunction FileSystemDateRangeDialog({\n initialRange,\n onApply,\n onClose,\n}: {\n initialRange?: { from: Date; to: Date }\n onApply: (from: Date, to: Date) => void\n onClose: () => void\n}) {\n const [range, setRange] = React.useState<{ from?: Date; to?: Date }>(\n () => initialRange ?? {}\n )\n const [fromInput, setFromInput] = React.useState(() =>\n formatDateInputValue(initialRange?.from)\n )\n const [toInput, setToInput] = React.useState(() =>\n formatDateInputValue(initialRange?.to)\n )\n\n const selectRange = (next: { from?: Date; to?: Date }) => {\n setRange(next)\n if (next.from) setFromInput(formatDateInputValue(next.from))\n if (next.to) setToInput(formatDateInputValue(next.to))\n }\n\n const dateField = (\n label: string,\n value: string,\n onChange: (value: string) => void\n ) => (\n <div className="flex flex-1 flex-col gap-1.5">\n <span className="text-xs font-medium">{label}</span>\n <div className="relative flex items-center">\n <HugeiconsIcon\n icon={Calendar03Icon}\n className="pointer-events-none absolute left-2.5 size-3.5 text-muted-foreground"\n />\n <Input\n type="text"\n value={value}\n placeholder="YYYY-MM-DD"\n aria-label={`${label} date`}\n onChange={(event) => onChange(event.target.value)}\n className="h-8 pl-8 sm:h-8"\n />\n </div>\n </div>\n )\n\n return (\n <Dialog\n open\n onOpenChange={(open) => {\n if (!open) onClose()\n }}\n >\n <DialogContent className="w-[30rem] max-w-[calc(100vw-2rem)]">\n <DialogHeader>\n <DialogTitle>Custom date range</DialogTitle>\n </DialogHeader>\n <DialogPanel className="flex flex-col gap-4">\n <div className="flex gap-3">\n {dateField("From", fromInput, (value) => {\n setFromInput(value)\n\n const parsed = parseDateInputValue(value)\n\n if (parsed)\n setRange((previous) => ({ ...previous, from: parsed }))\n })}\n {dateField("To", toInput, (value) => {\n setToInput(value)\n\n const parsed = parseDateInputValue(value)\n\n if (parsed) setRange((previous) => ({ ...previous, to: parsed }))\n })}\n </div>\n <FileSystemRangeCalendar range={range} onSelect={selectRange} />\n <div className="grid grid-cols-3 gap-2">\n {DATE_RANGE_DIALOG_PRESETS.map((preset) => (\n <Button\n key={preset}\n type="button"\n variant="outline"\n size="sm"\n onClick={() => selectRange(dateRangePresetRange(preset))}\n >\n {preset}\n </Button>\n ))}\n </div>\n </DialogPanel>\n <DialogFooter>\n <Button type="button" variant="outline" onClick={onClose}>\n Cancel\n </Button>\n <Button\n type="button"\n disabled={!range.from || !range.to}\n onClick={() => {\n if (!range.from || !range.to) return\n\n const from = new Date(range.from)\n const to = new Date(range.to)\n\n from.setHours(0, 0, 0, 0)\n to.setHours(23, 59, 59, 999)\n onApply(from, to)\n }}\n >\n Apply\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\ntype FileSystemViewProps = {\n currentPath: string\n entries: FileSystemEntry[]\n fileFilter: ((file: FileEntry) => boolean) | null\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n index: FileSystemIndex\n loadPreviewImageUrl?: (\n file: FileSystemFileItem,\n pageIndex: number\n ) => Promise<string | null>\n loadingFolders: Set<string>\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n onSortColumnClick: (key: FileSystemSortKey) => void\n renderFilePreview?: (file: FileSystemFileItem) => React.ReactNode\n searchQuery: string\n selectedEntry: FileSystemEntry | null\n selectedPath: string | null\n sort: FileSystemSortState\n /** Expanded tree folders per folder path, surviving view switches. */\n treeExpansionRef: React.RefObject<Map<string, readonly string[]>>\n}\n\n// Resolves a display URL for a file: its own `url`, else via `getFileUrl`.\n// Keyed by path/url (not object identity) so manifest churn — e.g. thumbnails\n// streaming in — doesn\'t re-trigger presign calls for the same file.\nfunction useResolvedFileUrl(\n file: FileEntry | null,\n getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>\n) {\n const [state, setState] = React.useState<{\n isResolving: boolean\n url: string | null\n }>({ isResolving: false, url: file?.url ?? null })\n const fileRef = React.useRef(file)\n\n React.useEffect(() => {\n fileRef.current = file\n })\n\n const filePath = file?.path ?? null\n const fileUrl = file?.url ?? null\n\n React.useEffect(() => {\n const currentFile = fileRef.current\n\n if (!currentFile || fileUrl || !getFileUrl) {\n setState({ isResolving: false, url: fileUrl })\n return\n }\n\n let isCurrent = true\n\n setState({ isResolving: true, url: null })\n void Promise.resolve(getFileUrl(currentFile))\n .then((url) => {\n if (isCurrent) setState({ isResolving: false, url })\n })\n .catch(() => {\n if (isCurrent) setState({ isResolving: false, url: null })\n })\n\n return () => {\n isCurrent = false\n }\n }, [filePath, fileUrl, getFileUrl])\n\n return state\n}\n\n// Returns `value` once it has stopped changing for `delay` ms. Gallery\n// navigation scrubs past files quickly; heavy previews (document viewers,\n// presigned URL resolution) only kick in for the file the user lands on.\nfunction useSettledValue<T>(value: T, delay: number): T {\n const [settled, setSettled] = React.useState(value)\n\n React.useEffect(() => {\n if (Object.is(settled, value)) return\n\n const timeout = window.setTimeout(() => setSettled(value), delay)\n\n return () => window.clearTimeout(timeout)\n }, [delay, settled, value])\n\n return settled\n}\n\nfunction FileSystemEmptyState({\n label,\n isLoading = false,\n}: {\n label: string\n isLoading?: boolean\n}) {\n return (\n <div\n className={cn(\n "flex size-full items-center justify-center text-sm text-muted-foreground",\n isLoading && "animate-pulse motion-reduce:animate-none"\n )}\n >\n {label}\n </div>\n )\n}\n\nconst ARROW_KEYS = new Set(["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"])\n\n// Type-ahead buffers reset after this idle period, like Finder.\nconst TYPE_AHEAD_RESET_MS = 700\n\n// Letters and digits only — the same key test the tree uses — so shortcuts\n// and whitespace scrolling stay untouched.\nfunction isTypeAheadKey(event: React.KeyboardEvent) {\n return (\n event.key.length === 1 &&\n /^[\\p{L}\\p{N}]$/u.test(event.key) &&\n !event.altKey &&\n !event.ctrlKey &&\n !event.metaKey\n )\n}\n\n// Shared Finder-style type-ahead used by every view: printable keys\n// accumulate a buffer that jumps to the next entry whose name starts with\n// it, and repeating a single letter cycles through entries with that\n// prefix. Each view passes its own display-ordered candidate list, so the\n// same keystrokes land on the same file everywhere.\nfunction useEntryTypeAhead() {\n const stateRef = React.useRef({ buffer: "", timeout: 0 })\n\n React.useEffect(() => {\n const state = stateRef.current\n\n return () => window.clearTimeout(state.timeout)\n }, [])\n\n return React.useCallback(\n (\n event: React.KeyboardEvent,\n entries: readonly FileSystemEntry[],\n currentIndex: number\n ) => {\n if (!isTypeAheadKey(event) || entries.length === 0) return null\n\n // Embedded viewers (and any future inputs) keep their keystrokes.\n const target = event.target\n\n if (\n target instanceof HTMLElement &&\n (target.isContentEditable ||\n target.tagName === "INPUT" ||\n target.tagName === "TEXTAREA" ||\n target.tagName === "SELECT")\n ) {\n return null\n }\n\n const state = stateRef.current\n\n window.clearTimeout(state.timeout)\n state.timeout = window.setTimeout(() => {\n state.buffer = ""\n }, TYPE_AHEAD_RESET_MS)\n state.buffer += event.key.toLowerCase()\n\n // A repeated single letter advances past the current entry; a longer\n // buffer refines the match in place.\n const startIndex =\n currentIndex < 0\n ? 0\n : currentIndex + (state.buffer.length === 1 ? 1 : 0)\n\n for (let step = 0; step < entries.length; step += 1) {\n const entry = entries[(startIndex + step) % entries.length]\n\n if (entry.name.toLowerCase().startsWith(state.buffer)) {\n event.preventDefault()\n return entry\n }\n }\n event.preventDefault()\n return null\n },\n []\n )\n}\n\n// Selects (and focuses) the entry reached by an arrow key. Up/down use row\n// geometry so navigation follows the rendered auto-fill grid.\nfunction moveGridSelection({\n entries,\n itemRefs,\n key,\n onSelect,\n selectedPath,\n}: {\n entries: FileSystemEntry[]\n itemRefs: Map<string, HTMLButtonElement>\n key: string\n onSelect: (entry: FileSystemEntry | null) => void\n selectedPath: string | null\n}) {\n if (entries.length === 0) return false\n\n const currentIndex = entries.findIndex((entry) => entry.path === selectedPath)\n let nextEntry: FileSystemEntry | undefined\n\n if (currentIndex === -1) {\n nextEntry = entries[0]\n } else if (key === "ArrowLeft" || key === "ArrowRight") {\n nextEntry = entries[currentIndex + (key === "ArrowLeft" ? -1 : 1)]\n } else {\n const currentElement = itemRefs.get(entries[currentIndex].path)\n\n if (!currentElement) return false\n\n const currentRect = currentElement.getBoundingClientRect()\n let bestScore = Infinity\n\n for (const entry of entries) {\n if (entry.path === selectedPath) continue\n\n const rect = itemRefs.get(entry.path)?.getBoundingClientRect()\n\n if (!rect) continue\n\n const rowDelta =\n key === "ArrowDown"\n ? rect.top - currentRect.top\n : currentRect.top - rect.top\n\n if (rowDelta <= 1) continue\n\n const score = rowDelta * 1000 + Math.abs(rect.left - currentRect.left)\n\n if (score < bestScore) {\n bestScore = score\n nextEntry = entry\n }\n }\n }\n\n if (!nextEntry) return false\n\n onSelect(nextEntry)\n itemRefs.get(nextEntry.path)?.focus()\n return true\n}\n\n// Icon grid geometry (px at the default 16px root font size). Tiles have a\n// fixed height — a 4rem glyph box plus a reserved two-line label — so rows\n// share one stride and the grid can window cleanly.\nconst ICON_GRID_PADDING = 12 // p-3\nconst ICON_MIN_TILE_WIDTH = 104 // 6.5rem\nconst ICON_TILE_GAP_X = 4 // gap-x-1\nconst ICON_TILE_HEIGHT = 102 // h-16 glyph box + gap-1.5 + two text-xs lines\nconst ICON_ROW_GAP = 12 // gap-y-3\nconst ICON_ROW_STRIDE = ICON_TILE_HEIGHT + ICON_ROW_GAP\n\nfunction FileSystemIconsView({\n entries,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedPath,\n}: FileSystemViewProps) {\n const itemRefs = React.useRef(new Map<string, HTMLButtonElement>())\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const typeAhead = useEntryTypeAhead()\n // The column count mirrors what `repeat(auto-fill, minmax(6.5rem, 1fr))`\n // produces (the CSS owns the actual layout) so item indices map to grid\n // rows — the windowing below depends on that mapping. It stays null until\n // the first client measure; server markup must not guess.\n const [columnCount, setColumnCount] = React.useState<number | null>(null)\n\n React.useLayoutEffect(() => {\n const viewport = viewportRef.current\n\n if (!viewport || typeof ResizeObserver === "undefined") return\n\n const update = () => {\n const available = viewport.clientWidth - ICON_GRID_PADDING * 2\n\n setColumnCount(\n Math.max(\n 1,\n Math.floor(\n (available + ICON_TILE_GAP_X) /\n (ICON_MIN_TILE_WIDTH + ICON_TILE_GAP_X)\n )\n )\n )\n }\n const observer = new ResizeObserver(update)\n\n update()\n observer.observe(viewport)\n return () => observer.disconnect()\n }, [])\n\n const resolvedColumnCount = columnCount ?? 1\n const rowCount = Math.ceil(entries.length / resolvedColumnCount)\n const { end, start } = useVirtualWindow({\n count: rowCount,\n itemStride: ICON_ROW_STRIDE,\n leadingPx: ICON_GRID_PADDING,\n overscan: 4,\n viewportRef,\n })\n const visibleEntries = entries.slice(\n start * resolvedColumnCount,\n end * resolvedColumnCount\n )\n\n // Selection can land outside the window (view switches, shrinking results);\n // bring its row back into the viewport so the tile mounts and is focusable.\n React.useLayoutEffect(() => {\n if (!selectedPath) return\n\n const entryIndex = entries.findIndex((entry) => entry.path === selectedPath)\n\n if (entryIndex === -1) return\n\n scrollIndexIntoView({\n index: Math.floor(entryIndex / resolvedColumnCount),\n itemSize: ICON_TILE_HEIGHT,\n itemStride: ICON_ROW_STRIDE,\n leadingPx: ICON_GRID_PADDING,\n viewport: viewportRef.current,\n })\n }, [entries, resolvedColumnCount, selectedPath])\n\n // Roving tabindex: the grid is a single tab stop (the selected tile when\n // rendered, else the first rendered one), so Shift+Tab returns to the\n // toolbar like in the list view.\n const tabStopPath = visibleEntries.some(\n (entry) => entry.path === selectedPath\n )\n ? selectedPath\n : (visibleEntries[0]?.path ?? null)\n\n return (\n <ScrollArea\n orientation="vertical"\n viewportRef={viewportRef}\n viewportClassName="p-3"\n viewportProps={{\n onClick: (event) => {\n if (event.target === event.currentTarget) onSelect(null)\n },\n }}\n >\n <div\n className="relative"\n // The scroll-height spacer needs the measured column count; until\n // then the absolutely positioned grid alone defines the scrollable\n // overflow, so the server-rendered frame doesn\'t flash an\n // oversized scroll range.\n style={{\n height:\n columnCount !== null && rowCount\n ? rowCount * ICON_ROW_STRIDE - ICON_ROW_GAP\n : undefined,\n }}\n >\n <div\n role="listbox"\n aria-label="Files"\n className="absolute inset-x-0 grid gap-x-1 gap-y-3"\n // The auto-fill expression produces the same column count the\n // ResizeObserver measures (the measurement exists only for the\n // windowing math), so the server-rendered first paint is already\n // a grid instead of flashing a single stacked column until the\n // first client measure.\n style={{\n gridTemplateColumns: "repeat(auto-fill, minmax(6.5rem, 1fr))",\n top: start * ICON_ROW_STRIDE,\n }}\n onKeyDown={(event) => {\n if (!ARROW_KEYS.has(event.key)) {\n const match = typeAhead(\n event,\n entries,\n entries.findIndex((entry) => entry.path === selectedPath)\n )\n\n if (match) {\n onSelect(match)\n // The matched tile may be outside the virtual window; the\n // selection effect scrolls it in, and focus follows once it\n // has mounted.\n requestAnimationFrame(() =>\n itemRefs.current.get(match.path)?.focus()\n )\n }\n return\n }\n if (\n moveGridSelection({\n entries,\n itemRefs: itemRefs.current,\n key: event.key,\n onSelect,\n selectedPath,\n })\n ) {\n event.preventDefault()\n }\n }}\n >\n {visibleEntries.map((entry) => {\n const isSelected = entry.path === selectedPath\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isSelected}\n tabIndex={entry.path === tabStopPath ? 0 : -1}\n ref={(element) => {\n if (element) {\n itemRefs.current.set(entry.path, element)\n } else {\n itemRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n className="group flex h-[6.375rem] flex-col items-center gap-1.5 outline-none"\n >\n <span\n className={cn(\n "flex h-16 w-20 shrink-0 items-center justify-center rounded-lg p-1 transition-colors group-focus-visible:ring-2 group-focus-visible:ring-ring",\n isSelected && "bg-accent"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-13 w-auto drop-shadow-sm" />\n ) : (\n <FileVisual\n file={entry}\n className={cn(\n "rounded-sm shadow-xs",\n // Landscape thumbnails get extra width so they fill\n // the tile instead of rendering as a short sliver.\n (entry.previewAspectRatio ?? 0.78) > 1.2\n ? "w-[4.75rem]"\n : "w-12"\n )}\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )}\n </span>\n <span\n className={cn(\n "max-w-full rounded-sm px-1.5 py-px text-center text-xs leading-tight break-words",\n isSelected\n ? "bg-primary text-primary-foreground"\n : "text-foreground"\n )}\n >\n <span className="line-clamp-2">{entry.name}</span>\n </span>\n </button>\n )\n })}\n </div>\n </div>\n </ScrollArea>\n )\n}\n\n// One sortable column header for the list view; the active column shows the\n// direction chevron on its right.\nfunction FileSystemListColumnHeader({\n className,\n label,\n onClick,\n sort,\n sortKey,\n}: {\n className?: string\n label: string\n onClick: (key: FileSystemSortKey) => void\n sort: FileSystemSortState\n sortKey: FileSystemSortKey\n}) {\n const isActive = sort.key === sortKey\n\n return (\n <button\n type="button"\n onClick={() => onClick(sortKey)}\n className={cn(\n "flex items-center gap-0.5 rounded-sm py-0.5 transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",\n isActive && "text-foreground",\n className\n )}\n >\n {label}\n {isActive ? (\n <HugeiconsIcon\n icon={sort.direction === "asc" ? ArrowUp01Icon : ArrowDown01Icon}\n className="size-3 shrink-0"\n />\n ) : null}\n </button>\n )\n}\n\nfunction FileSystemListView({\n currentPath,\n fileFilter,\n index,\n onOpen,\n onSelect,\n onSortColumnClick,\n searchQuery,\n selectedPath,\n sort,\n treeExpansionRef,\n}: FileSystemViewProps) {\n // Filters narrow the path list handed to the tree; the search query stays\n // out of it so the tree\'s own search session (with match highlighting)\n // keeps handling it without remounts per keystroke.\n const relativePaths = React.useMemo(() => {\n const paths: string[] = []\n\n for (const [path, file] of index.files) {\n if (currentPath === "" || path.startsWith(currentPath)) {\n const relativePath = path.slice(currentPath.length)\n\n if (!relativePath) continue\n if (fileFilter && !fileFilter(file)) continue\n paths.push(relativePath)\n }\n }\n return paths.sort()\n }, [currentPath, fileFilter, index])\n\n if (relativePaths.length === 0) {\n return (\n <FileSystemEmptyState\n label={\n fileFilter\n ? "No items match the active filters"\n : "This folder is empty"\n }\n />\n )\n }\n\n return (\n <div className="flex size-full flex-col">\n {/* Paddings match the tree\'s row geometry: name text starts 46px in\n (16px tree padding + 30px icon lane), metadata ends 24px from the\n right (16px tree padding + 8px decoration inset). */}\n <div className="flex shrink-0 items-center border-b py-1 pr-6 pl-[46px] text-xs font-medium text-muted-foreground">\n <FileSystemListColumnHeader\n className="flex-1 justify-start"\n label="Name"\n onClick={onSortColumnClick}\n sort={sort}\n sortKey="name"\n />\n <FileSystemListColumnHeader\n className="w-44 justify-end"\n label="Date Modified"\n onClick={onSortColumnClick}\n sort={sort}\n sortKey="updatedAt"\n />\n <FileSystemListColumnHeader\n className="w-20 justify-end"\n label="Size"\n onClick={onSortColumnClick}\n sort={sort}\n sortKey="size"\n />\n </div>\n {/* Keyed by folder only: navigation remounts the tree, while filter,\n sort, and manifest changes update the mounted model in place so\n folder disclosure state survives them. */}\n <FileSystemPierreTree\n key={currentPath}\n currentPath={currentPath}\n hasActiveFilters={fileFilter !== null}\n index={index}\n initialSelectedPath={\n selectedPath?.startsWith(currentPath)\n ? selectedPath.slice(currentPath.length).replace(/\\/$/, "")\n : null\n }\n onOpen={onOpen}\n onSelect={onSelect}\n relativePaths={relativePaths}\n searchQuery={searchQuery}\n sort={sort}\n treeExpansionRef={treeExpansionRef}\n />\n </div>\n )\n}\n\n// Embedded thumbnail symbols grow the sprite injected into the tree\'s shadow\n// DOM (data-URL covers can run hundreds of KB each); past this many the\n// remaining files fall back to the built-in file-type icons alone.\nconst TREE_THUMBNAIL_SPRITE_LIMIT = 400\n\nfunction FileSystemPierreTree({\n currentPath,\n hasActiveFilters,\n index,\n initialSelectedPath,\n onOpen,\n onSelect,\n relativePaths,\n searchQuery,\n sort,\n treeExpansionRef,\n}: {\n currentPath: string\n hasActiveFilters: boolean\n index: FileSystemIndex\n initialSelectedPath: string | null\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n relativePaths: string[]\n searchQuery: string\n sort: FileSystemSortState\n treeExpansionRef: React.RefObject<Map<string, readonly string[]>>\n}) {\n // The tree\'s comparator receives whole paths, not siblings, so it walks\n // the shared segments and applies the active sort at the first level the\n // two paths diverge — keeping directories first per level, the tree\'s\n // default convention. Lookups go through the index maps, which are stable\n // across search keystrokes.\n const indexFiles = index.files\n const indexFolders = index.folders\n const sortComparator = React.useMemo<\n "default" | FileTreeSortComparator\n >(() => {\n if (\n sort.key === DEFAULT_SORT.key &&\n sort.direction === DEFAULT_SORT.direction\n ) {\n return "default"\n }\n\n const entryAtDepth = (sortEntry: FileTreeSortEntry, depth: number) => {\n const isDirectory =\n depth < sortEntry.segments.length - 1 || sortEntry.isDirectory\n const absolutePath = `${currentPath}${sortEntry.segments\n .slice(0, depth + 1)\n .join("/")}${isDirectory ? "/" : ""}`\n\n return isDirectory\n ? indexFolders.get(absolutePath)\n : indexFiles.get(absolutePath)\n }\n\n return (left, right) => {\n const sharedDepth = Math.min(left.segments.length, right.segments.length)\n\n for (let depth = 0; depth < sharedDepth; depth += 1) {\n if (left.segments[depth] === right.segments[depth]) continue\n\n const leftIsDirectory =\n depth < left.segments.length - 1 || left.isDirectory\n const rightIsDirectory =\n depth < right.segments.length - 1 || right.isDirectory\n\n if (leftIsDirectory !== rightIsDirectory) {\n return leftIsDirectory ? -1 : 1\n }\n\n const leftEntry = entryAtDepth(left, depth)\n const rightEntry = entryAtDepth(right, depth)\n\n if (leftEntry && rightEntry) {\n return compareEntriesBySort(leftEntry, rightEntry, sort)\n }\n return left.segments[depth] < right.segments[depth] ? -1 : 1\n }\n return left.segments.length - right.segments.length\n }\n }, [currentPath, indexFiles, indexFolders, sort])\n const preparedInput = React.useMemo(\n () => prepareFileTreeInput(relativePaths, { sort: sortComparator }),\n [relativePaths, sortComparator]\n )\n // Inject per-file thumbnails into the tree\'s shadow DOM as sprite symbols\n // wrapping an <image>, remapped onto rows by file basename. Files without\n // a thumbnail resolve through the built-in complete icon set instead — the\n // same colored file-type icons the other views use. The chevron is\n // remapped to the Hugeicons arrow so it matches the rest of the component;\n // the tree\'s rotation CSS keys off data-icon-name, which remapping keeps.\n const icons = React.useMemo(() => {\n const byFileName: Record<string, { name: string; viewBox: string }> = {}\n const symbols: string[] = [\n `<symbol id="file-system-chevron" viewBox="0 0 24 24"><path d="M18 9.00005C18 9.00005 13.5811 15 12 15C10.4188 15 6 9 6 9" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/></symbol>`,\n ]\n\n let thumbnailCount = 0\n\n for (const relativePath of relativePaths) {\n if (thumbnailCount >= TREE_THUMBNAIL_SPRITE_LIMIT) break\n\n const file = index.files.get(`${currentPath}${relativePath}`)\n const coverUrl = file ? filePreviewUrls(file)[0] : undefined\n\n if (!file || !coverUrl) continue\n\n const baseName = file.name.toLowerCase()\n\n if (byFileName[baseName]) continue\n\n const symbolId = `file-system-thumbnail-${symbols.length}`\n\n symbols.push(\n `<symbol id="${symbolId}" viewBox="0 0 16 16"><clipPath id="${symbolId}-clip"><rect width="16" height="16" rx="2.5"/></clipPath><image href="${escapeXmlAttribute(coverUrl)}" width="16" height="16" preserveAspectRatio="xMidYMid slice" clip-path="url(#${symbolId}-clip)"/></symbol>`\n )\n byFileName[baseName] = { name: symbolId, viewBox: "0 0 16 16" }\n thumbnailCount += 1\n }\n\n return {\n byFileName,\n colored: true,\n remap: {\n "file-tree-icon-chevron": {\n name: "file-system-chevron",\n viewBox: "0 0 24 24",\n },\n },\n set: "complete" as const,\n spriteSheet: `<svg data-icon-sprite aria-hidden="true" width="0" height="0">${symbols.join("")}</svg>`,\n }\n }, [currentPath, index, relativePaths])\n const { model } = useFileTree({\n flattenEmptyDirectories: false,\n icons,\n initialExpansion: "closed",\n // Remounts (folder changes, manifest updates) keep the active filter.\n initialSearchQuery: searchQuery || null,\n initialSelectedPaths: initialSelectedPath ? [initialSelectedPath] : [],\n itemHeight: 28,\n overscan: 12,\n preparedInput,\n renderRowDecoration: ({ row }) => {\n const entry =\n row.kind === "file"\n ? index.files.get(`${currentPath}${row.path}`)\n : index.folders.get(normalizeFolderPath(`${currentPath}${row.path}`))\n\n if (!entry) return null\n\n // The decoration lane renders one <span title>; CSS splits it into\n // aligned Date Modified (::before from title) and Size columns.\n const dateColumn =\n formatTimestamp(entry.updatedAt ?? entry.createdAt) ?? "—"\n\n if (entry.kind === "folder") {\n const childCount = index.children.get(entry.path)?.length\n\n return {\n text:\n childCount === undefined\n ? "—"\n : `${childCount} ${childCount === 1 ? "item" : "items"}`,\n title: dateColumn,\n }\n }\n\n return { text: formatByteSize(entry.size) ?? "—", title: dateColumn }\n },\n unsafeCSS: `\n button[data-type=\'item\']:not([data-item-selected]):hover {\n background: color-mix(in oklab, var(--color-accent) 50%, transparent);\n }\n button[data-type=\'item\'][data-item-selected] {\n background: var(--color-primary);\n color: var(--color-primary-foreground);\n /* The primary surface is the opposite of the mode\'s background, so\n the row\'s light-dark() icon colors resolve against the opposite\n scheme — light-palette icons on the light pill in dark mode and\n vice versa. */\n color-scheme: var(--fs-selected-color-scheme, normal);\n }\n button[data-type=\'item\'][data-item-selected] *:not([data-icon-token]):not([data-icon-token] *),\n button[data-type=\'item\'][data-item-selected] [data-item-section]::before {\n color: var(--color-primary-foreground) !important;\n }\n [data-item-section=\'decoration\'] > span {\n display: grid;\n grid-template-columns: 11rem 5rem;\n justify-items: end;\n white-space: nowrap;\n }\n [data-item-section=\'decoration\'] > span::before {\n content: attr(title);\n }\n button[data-type=\'item\'][data-item-type=\'folder\'] [data-item-section=\'content\'] {\n display: flex;\n align-items: center;\n min-width: 0;\n }\n button[data-type=\'item\'][data-item-type=\'folder\'] [data-item-section=\'content\']::before {\n content: "";\n flex: none;\n width: 18px;\n height: 14px;\n margin-right: 4px;\n background: url("${FOLDER_GLYPH_DATA_URL}") center / contain no-repeat;\n }\n `,\n onSelectionChange: (selectedPaths) => {\n const relativePath = selectedPaths[0]\n\n if (!relativePath) {\n onSelect(null)\n return\n }\n\n const absolutePath = `${currentPath}${relativePath}`\n const entry =\n index.files.get(absolutePath) ??\n index.folders.get(normalizeFolderPath(absolutePath)) ??\n null\n\n onSelect(entry)\n },\n })\n\n // Thumbnails can resolve after mount (e.g. generated client-side); push\n // sprite updates into the existing model instead of remounting the tree.\n React.useEffect(() => {\n model.setIcons(icons)\n }, [icons, model])\n\n // The folders currently expanded in the mounted model, derived from the\n // given path list (the model knows the rows; the paths name the\n // directories to ask about).\n const collectExpandedDirectories = React.useCallback(\n (paths: readonly string[]) => {\n const expandedPaths: string[] = []\n\n for (const directoryPath of directoryPathsOf(paths)) {\n const item =\n model.getItem(directoryPath) ?? model.getItem(`${directoryPath}/`)\n\n if (item && "isExpanded" in item && item.isExpanded()) {\n expandedPaths.push(directoryPath)\n }\n }\n return expandedPaths\n },\n [model]\n )\n\n // Opens every given folder on the mounted model (no-ops on the already\n // open ones).\n const expandDirectories = React.useCallback(\n (directoryPaths: Iterable<string>) => {\n for (const directoryPath of directoryPaths) {\n const item =\n model.getItem(directoryPath) ?? model.getItem(`${directoryPath}/`)\n\n if (item && "isExpanded" in item && !item.isExpanded()) {\n item.toggle()\n }\n }\n },\n [model]\n )\n\n // Sort and filter changes swap the prepared input in place — remounting\n // would reset every folder\'s disclosure. The folders expanded in the\n // outgoing path list, the selection, and the active search query are\n // captured first and handed back to the reset.\n const appliedPreparedInputRef = React.useRef(preparedInput)\n // Filter bookkeeping: the latest prop (for unmount-time decisions), the\n // state at the last applied reset (for transition detection), and the\n // disclosure to restore once the filters clear.\n const hasActiveFiltersRef = React.useRef(hasActiveFilters)\n const filteredAtLastResetRef = React.useRef(hasActiveFilters)\n const preFilterExpansionRef = React.useRef<readonly string[] | null>(null)\n\n React.useEffect(() => {\n hasActiveFiltersRef.current = hasActiveFilters\n })\n\n React.useEffect(() => {\n const previousPreparedInput = appliedPreparedInputRef.current\n\n if (previousPreparedInput === preparedInput) return\n appliedPreparedInputRef.current = preparedInput\n\n const wasFiltered = filteredAtLastResetRef.current\n\n filteredAtLastResetRef.current = hasActiveFilters\n\n // Filters reveal their matches the way the search session does: every\n // folder on the way to a match opens. The disclosure from just before\n // filtering is kept aside and comes back when the filters clear.\n let expandedPaths: readonly string[]\n\n if (hasActiveFilters) {\n if (!wasFiltered) {\n preFilterExpansionRef.current = collectExpandedDirectories(\n previousPreparedInput.paths\n )\n }\n expandedPaths = [...directoryPathsOf(preparedInput.paths)]\n } else if (wasFiltered) {\n expandedPaths = preFilterExpansionRef.current ?? []\n preFilterExpansionRef.current = null\n } else {\n expandedPaths = collectExpandedDirectories(previousPreparedInput.paths)\n }\n\n const searchValue = model.getSearchValue()\n\n // The `paths` argument must stay unset: when both are given, resetPaths\n // re-prepares the paths with the comparator the model was CREATED with\n // and rejects the differently-ordered prepared input. Passing only the\n // prepared input makes the reset adopt its path list as-is, and the\n // reset itself carries the selection over.\n model.resetPaths(undefined as unknown as readonly string[], {\n initialExpandedPaths: expandedPaths,\n preparedInput,\n })\n if (searchValue) model.setSearch(searchValue)\n }, [collectExpandedDirectories, hasActiveFilters, model, preparedInput])\n\n // View switches and navigation unmount the tree; remember which folders\n // were left expanded and reopen them on the next mount of this folder\n // (before paint, so the restored disclosure never flashes closed). While\n // filters are active their matches are revealed instead, and the\n // remembered disclosure is the pre-filter one.\n React.useLayoutEffect(() => {\n const expansionStore = treeExpansionRef.current\n const savedExpansion = expansionStore.get(currentPath) ?? []\n\n if (hasActiveFiltersRef.current) {\n preFilterExpansionRef.current = savedExpansion\n expandDirectories(directoryPathsOf(appliedPreparedInputRef.current.paths))\n } else {\n expandDirectories(savedExpansion)\n }\n\n return () => {\n expansionStore.set(\n currentPath,\n hasActiveFiltersRef.current\n ? (preFilterExpansionRef.current ?? [])\n : collectExpandedDirectories(appliedPreparedInputRef.current.paths)\n )\n }\n }, [\n collectExpandedDirectories,\n currentPath,\n expandDirectories,\n treeExpansionRef,\n ])\n\n // The toolbar search drives the tree\'s own search session, which filters\n // rows with hide-non-matches semantics and highlights the matched text.\n React.useEffect(() => {\n model.setSearch(searchQuery || null)\n }, [model, searchQuery])\n\n // The tree\'s arrow keys move focus and only select on click/Enter; mirror\n // focus into the (single) selection so arrowing selects like Finder. Shift\n // ranges keep the focused row selected, so they pass through untouched.\n React.useEffect(() => {\n let lastFocusedPath = model.getFocusedPath()\n\n return model.subscribe(() => {\n const focusedPath = model.getFocusedPath()\n\n if (focusedPath === lastFocusedPath) return\n\n lastFocusedPath = focusedPath\n\n if (!focusedPath) return\n\n const item = model.getItem(focusedPath)\n\n if (!item || item.isSelected()) return\n\n for (const path of model.getSelectedPaths()) {\n model.getItem(path)?.deselect()\n }\n item.select()\n })\n }, [model])\n\n // Rows live in the tree\'s shadow DOM; composedPath surfaces the row\n // element behind a pointer or keyboard event so it can resolve to a\n // manifest entry.\n const entryFromEvent = (event: React.SyntheticEvent) => {\n for (const target of event.nativeEvent.composedPath()) {\n if (!(target instanceof HTMLElement)) continue\n\n const relativePath = target.dataset?.itemPath\n\n if (!relativePath) continue\n\n const absolutePath = `${currentPath}${relativePath}`\n\n return (\n index.files.get(absolutePath) ??\n index.folders.get(normalizeFolderPath(absolutePath)) ??\n null\n )\n }\n return null\n }\n\n // The tree exposes rows by relative path; directory ids may or may not\n // carry the trailing slash depending on the call site.\n const resolveTreeItem = (relativePath: string) =>\n model.getItem(relativePath) ??\n model.getItem(\n relativePath.endsWith("/")\n ? relativePath.slice(0, -1)\n : `${relativePath}/`\n )\n\n // The tree\'s rows in display order — folders first per level, recursing\n // only into expanded folders — so type-ahead cycles exactly what\'s on\n // screen. Virtualization keeps this off the DOM; the index and the item\n // handles carry the same information.\n const collectVisibleEntries = () => {\n const visibleEntries: FileSystemEntry[] = []\n const walk = (folderPath: string) => {\n const children = index.children.get(folderPath) ?? []\n\n for (const child of children) {\n if (child.kind !== "folder") continue\n\n const item = resolveTreeItem(child.path.slice(currentPath.length))\n\n if (!item) continue\n visibleEntries.push(child)\n if ("isExpanded" in item && item.isExpanded()) walk(child.path)\n }\n for (const child of children) {\n if (child.kind === "file") visibleEntries.push(child)\n }\n }\n\n walk(currentPath)\n return visibleEntries\n }\n\n const typeAhead = useEntryTypeAhead()\n\n return (\n <PierreFileTree\n model={model}\n className="block min-h-0 flex-1"\n // Finder semantics: double-clicking a folder navigates into it and\n // double-clicking a file opens it; a single click still only toggles\n // the folder\'s disclosure.\n onDoubleClick={(event) => {\n const entry = entryFromEvent(event)\n\n if (entry) onOpen(entry)\n }}\n // Enter mirrors the other views: navigate into the focused folder or\n // open the focused file. Printable keys run the shared type-ahead\n // over the visible rows.\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n const entry = entryFromEvent(event)\n\n if (entry) {\n event.preventDefault()\n onOpen(entry)\n }\n return\n }\n\n if (!isTypeAheadKey(event)) return\n\n const visibleEntries = collectVisibleEntries()\n const focusedPath = model.getFocusedPath()?.replace(/\\/$/, "") ?? null\n const focusedIndex = visibleEntries.findIndex(\n (entry) =>\n entry.path.slice(currentPath.length).replace(/\\/$/, "") ===\n focusedPath\n )\n const match = typeAhead(event, visibleEntries, focusedIndex)\n\n if (!match) return\n\n const item = resolveTreeItem(match.path.slice(currentPath.length))\n\n if (item) {\n model.scrollToPath(item.getPath())\n item.focus()\n }\n }}\n style={\n {\n "--trees-bg-override": "transparent",\n "--trees-border-color-override": "var(--color-border)",\n "--trees-fg-override": "var(--color-foreground)",\n // Match the focus-visible ring used by the tabs and the other\n // views (`ring-2 ring-ring`) instead of the tree\'s accent blue.\n "--trees-focus-ring-color-override": "var(--color-ring)",\n "--trees-focus-ring-width-override": "2px",\n "--trees-selected-bg-override": "var(--color-primary)",\n "--trees-selected-focused-border-color-override": "var(--color-ring)",\n } as React.CSSProperties\n }\n />\n )\n}\n\nfunction FileSystemColumnsView(props: FileSystemViewProps) {\n const {\n currentPath,\n index,\n loadPreviewImageUrl,\n loadingFolders,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n } = props\n const scrollContainerRef = React.useRef<HTMLDivElement | null>(null)\n const rowRefs = React.useRef(new Map<string, HTMLButtonElement>())\n\n // The selection highlight tracks every keypress; mounting the trailing\n // child column and the preview pane is deferred so holding an arrow key\n // doesn\'t pay that DOM churn per step.\n const deferredSelectedEntry = React.useDeferredValue(selectedEntry)\n const deferredSelectedPath = React.useDeferredValue(selectedPath)\n const pendingFocusPathRef = React.useRef<string | null>(null)\n const typeAhead = useEntryTypeAhead()\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (!ARROW_KEYS.has(event.key)) {\n // Type-ahead moves within the active column\'s rows, like Finder.\n const siblings =\n selectedEntry && selectedPath?.startsWith(currentPath)\n ? (index.children.get(selectedEntry.parentPath) ?? [])\n : (index.children.get(currentPath) ?? [])\n const match = typeAhead(\n event,\n siblings,\n siblings.findIndex((sibling) => sibling.path === selectedPath)\n )\n\n if (match) {\n onSelect(match)\n\n const row = rowRefs.current.get(match.path)\n\n if (row) {\n row.focus()\n } else {\n pendingFocusPathRef.current = match.path\n }\n }\n return\n }\n\n let nextEntry: FileSystemEntry | null | undefined\n\n if (!selectedEntry || !selectedPath?.startsWith(currentPath)) {\n nextEntry = index.children.get(currentPath)?.[0]\n } else if (event.key === "ArrowUp" || event.key === "ArrowDown") {\n const siblings = index.children.get(selectedEntry.parentPath) ?? []\n const currentIndex = siblings.findIndex(\n (sibling) => sibling.path === selectedEntry.path\n )\n\n nextEntry = siblings[currentIndex + (event.key === "ArrowUp" ? -1 : 1)]\n } else if (event.key === "ArrowLeft") {\n if (selectedEntry.parentPath !== currentPath) {\n nextEntry = index.folders.get(selectedEntry.parentPath)\n }\n } else if (selectedEntry.kind === "folder") {\n nextEntry = index.children.get(selectedEntry.path)?.[0]\n }\n\n if (!nextEntry) return\n\n onSelect(nextEntry)\n\n const row = rowRefs.current.get(nextEntry.path)\n\n if (row) {\n pendingFocusPathRef.current = null\n row.focus()\n } else {\n // The target row lives in a deferred column that hasn\'t mounted yet;\n // focus it from the effect below once it exists.\n pendingFocusPathRef.current = nextEntry.path\n }\n event.preventDefault()\n }\n\n React.useEffect(() => {\n const path = pendingFocusPathRef.current\n\n if (!path) return\n\n const row = rowRefs.current.get(path)\n\n if (row) {\n pendingFocusPathRef.current = null\n row.focus()\n }\n })\n\n const columnPaths = React.useMemo(() => {\n const paths = [currentPath]\n\n if (!deferredSelectedPath?.startsWith(currentPath)) return paths\n\n const targetFolder =\n deferredSelectedEntry?.kind === "folder"\n ? deferredSelectedEntry.path\n : (deferredSelectedEntry?.parentPath ?? currentPath)\n const relativePath = targetFolder.slice(currentPath.length)\n let walkedPath = currentPath\n\n for (const segment of relativePath.split("/")) {\n if (!segment) continue\n walkedPath = `${walkedPath}${segment}/`\n paths.push(walkedPath)\n }\n return paths\n }, [currentPath, deferredSelectedEntry, deferredSelectedPath])\n // Roving tabindex: all columns together form a single tab stop (the\n // selected row when its column is mounted, else the first row), so\n // Shift+Tab returns to the toolbar like in the list view.\n const tabStopPath = React.useMemo(() => {\n if (selectedPath) {\n for (const columnPath of columnPaths) {\n if (\n index.children\n .get(columnPath)\n ?.some((entry) => entry.path === selectedPath)\n ) {\n return selectedPath\n }\n }\n }\n return index.children.get(columnPaths[0] ?? "")?.[0]?.path ?? null\n }, [columnPaths, index, selectedPath])\n const selectedFile =\n deferredSelectedEntry?.kind === "file"\n ? (deferredSelectedEntry as FileEntry)\n : null\n const selectedFileSize = selectedFile\n ? formatByteSize(selectedFile.size)\n : null\n\n React.useEffect(() => {\n const container = scrollContainerRef.current\n\n if (container) container.scrollLeft = container.scrollWidth\n }, [columnPaths.length, deferredSelectedPath])\n\n return (\n <ScrollArea\n orientation="horizontal"\n viewportRef={scrollContainerRef}\n viewportClassName="overscroll-x-contain"\n >\n <div className="flex h-full w-max min-w-full" onKeyDown={handleKeyDown}>\n {columnPaths.map((columnPath, columnIndex) => (\n <FileSystemColumn\n key={columnPath || "(root)"}\n entries={index.children.get(columnPath) ?? []}\n index={index}\n isLoading={loadingFolders.has(columnPath)}\n onOpen={onOpen}\n onSelect={onSelect}\n rowRefs={rowRefs}\n // Scalar per-column props so the memoized column only\n // re-renders when its own rows change — a selection deeper in\n // the trail leaves ancestor columns untouched.\n selectedChildPath={\n selectedPath && pathParent(selectedPath) === columnPath\n ? selectedPath\n : null\n }\n tabStopChildPath={\n tabStopPath && pathParent(tabStopPath) === columnPath\n ? tabStopPath\n : null\n }\n trailChildPath={columnPaths[columnIndex + 1] ?? null}\n />\n ))}\n {selectedFile ? (\n <ScrollArea\n orientation="vertical"\n className="min-w-72 flex-1"\n viewportClassName="flex justify-center p-4"\n >\n <div className="flex w-full max-w-lg flex-col items-stretch gap-3">\n {/* Width derives from the aspect ratio so the thumbnail grows\n with the pane up to a 20rem height cap. */}\n <div\n className="mx-auto w-full shrink-0"\n style={{\n maxWidth: `min(100%, ${(selectedFile.previewAspectRatio ?? 0.78) * 20}rem)`,\n }}\n >\n <FileVisual\n file={selectedFile}\n className="w-full"\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageable\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n </div>\n <div className="text-center">\n <div className="text-sm font-semibold break-words">\n {selectedFile.name}\n </div>\n <div className="text-xs text-muted-foreground">\n {fileKindLabel(selectedFile)}\n {selectedFileSize ? ` - ${selectedFileSize}` : null}\n </div>\n </div>\n <FileSystemInformation entry={selectedFile} index={index} />\n </div>\n </ScrollArea>\n ) : null}\n </div>\n </ScrollArea>\n )\n}\n\n// Column row geometry (px at the default 16px root font size).\nconst COLUMN_PADDING = 6 // p-1.5\nconst COLUMN_ROW_HEIGHT = 28 // h-7\nconst COLUMN_ROW_GAP = 1 // gap-px\nconst COLUMN_ROW_STRIDE = COLUMN_ROW_HEIGHT + COLUMN_ROW_GAP\n\n// Memoized with scalar selection props: pressing into a deep trail only\n// re-renders the columns whose rows actually change.\nconst FileSystemColumn = React.memo(function FileSystemColumn({\n entries,\n index,\n isLoading,\n onOpen,\n onSelect,\n rowRefs,\n selectedChildPath,\n tabStopChildPath,\n trailChildPath,\n}: {\n entries: FileSystemEntry[]\n index: FileSystemIndex\n isLoading: boolean\n onOpen: (entry: FileSystemEntry) => void\n onSelect: (entry: FileSystemEntry | null) => void\n rowRefs: React.RefObject<Map<string, HTMLButtonElement>>\n selectedChildPath: string | null\n tabStopChildPath: string | null\n trailChildPath: string | null\n}) {\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const { end, start } = useVirtualWindow({\n count: entries.length,\n itemStride: COLUMN_ROW_STRIDE,\n leadingPx: COLUMN_PADDING,\n overscan: 10,\n viewportRef,\n })\n\n // Keyboard navigation can select a row this column hasn\'t mounted; scroll\n // it into the viewport so it mounts and the pending-focus effect can land.\n React.useLayoutEffect(() => {\n if (!selectedChildPath) return\n\n scrollIndexIntoView({\n index: entries.findIndex((entry) => entry.path === selectedChildPath),\n itemSize: COLUMN_ROW_HEIGHT,\n itemStride: COLUMN_ROW_STRIDE,\n leadingPx: COLUMN_PADDING,\n viewport: viewportRef.current,\n })\n }, [entries, selectedChildPath])\n\n return (\n <ScrollArea\n orientation="vertical"\n className="w-60 shrink-0 border-r"\n viewportRef={viewportRef}\n viewportClassName="p-1.5"\n viewportProps={{ "aria-label": "Files", role: "listbox" }}\n >\n {isLoading && entries.length === 0 ? (\n <div className="animate-pulse px-2 py-1.5 text-xs text-muted-foreground motion-reduce:animate-none">\n Loading…\n </div>\n ) : (\n <div\n className="relative"\n style={{\n height: entries.length\n ? entries.length * COLUMN_ROW_STRIDE - COLUMN_ROW_GAP\n : undefined,\n }}\n >\n <div\n className="absolute inset-x-0 flex flex-col gap-px"\n style={{ top: start * COLUMN_ROW_STRIDE }}\n >\n {entries.slice(start, end).map((entry) => {\n const isSelected = entry.path === selectedChildPath\n const isOnTrail =\n entry.kind === "folder" && entry.path === trailChildPath\n\n const coverUrl =\n entry.kind === "file" ? filePreviewUrls(entry)[0] : undefined\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isSelected}\n // Selected rows sit on the primary surface — the opposite\n // of the mode\'s background — so the file-type icon swaps\n // to the opposite palette.\n data-file-system-on-primary={isSelected ? "" : undefined}\n tabIndex={entry.path === tabStopChildPath ? 0 : -1}\n ref={(element) => {\n if (element) {\n rowRefs.current.set(entry.path, element)\n } else {\n rowRefs.current.delete(entry.path)\n }\n }}\n // Selecting on press (mouse only) starts mounting the\n // child column a beat before mouseup — the immediacy\n // @pierre/trees rows have. Touch keeps selection on the\n // click so scroll gestures don\'t select.\n onPointerDown={(event) => {\n if (event.pointerType === "mouse" && event.button === 0) {\n onSelect(entry)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n className={cn(\n "flex h-7 shrink-0 items-center gap-2 rounded-md px-2 py-1 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",\n isSelected\n ? "bg-primary text-primary-foreground"\n : isOnTrail\n ? "bg-accent"\n : "hover:bg-accent/50"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-3.5 w-auto shrink-0" />\n ) : coverUrl ? (\n <img\n src={coverUrl}\n alt=""\n draggable={false}\n className="size-4 shrink-0 rounded-[3px] bg-white object-cover"\n />\n ) : (\n <FileTypeIcon\n fileName={entry.name}\n className="size-4 shrink-0"\n />\n )}\n <span className="min-w-0 flex-1 truncate">{entry.name}</span>\n {entry.kind === "folder" &&\n folderHasChildren(index, entry) ? (\n <HugeiconsIcon\n icon={ArrowRight01Icon}\n className={cn(\n "size-3.5 shrink-0",\n !isSelected && "text-muted-foreground/60"\n )}\n />\n ) : null}\n </button>\n )\n })}\n </div>\n </div>\n )}\n </ScrollArea>\n )\n})\n\nfunction FileSystemInformation({\n entry,\n index,\n}: {\n entry: FileSystemEntry\n index: FileSystemIndex\n}) {\n const rows: Array<[string, string]> = []\n const created = formatTimestamp(entry.createdAt)\n const updated = formatTimestamp(entry.updatedAt)\n\n if (created) rows.push(["Created", created])\n if (updated) rows.push(["Modified", updated])\n if (entry.kind === "file") {\n const size = formatByteSize(entry.size)\n\n if (size) rows.push(["Size", size])\n } else {\n const childCount = index.children.get(entry.path)?.length\n\n if (childCount !== undefined) {\n rows.push(["Items", `${childCount}`])\n }\n }\n\n if (rows.length === 0) return null\n\n return (\n <div className="border-t pt-3">\n <div className="mb-1.5 text-xs font-semibold">Information</div>\n <dl className="space-y-1">\n {rows.map(([label, value]) => (\n <div\n key={label}\n className="flex items-baseline justify-between gap-3 text-xs"\n >\n <dt className="shrink-0 text-muted-foreground">{label}</dt>\n <dd className="text-right" suppressHydrationWarning>\n {value}\n </dd>\n </div>\n ))}\n </dl>\n </div>\n )\n}\n\n// Filmstrip geometry (px at the default 16px root font size).\nconst GALLERY_STRIP_PADDING = 8 // p-2\nconst GALLERY_TILE_SIZE = 56 // size-14\nconst GALLERY_TILE_GAP = 6 // gap-1.5\nconst GALLERY_TILE_STRIDE = GALLERY_TILE_SIZE + GALLERY_TILE_GAP\n\nfunction FileSystemGalleryView(props: FileSystemViewProps) {\n const {\n entries,\n getFileUrl,\n index,\n loadPreviewImageUrl,\n onOpen,\n onSelect,\n renderFilePreview,\n selectedEntry,\n selectedPath,\n } = props\n const stripRefs = React.useRef(new Map<string, HTMLButtonElement>())\n const stripViewportRef = React.useRef<HTMLDivElement | null>(null)\n const typeAhead = useEntryTypeAhead()\n const activeEntry =\n selectedEntry && entries.some((entry) => entry.path === selectedEntry.path)\n ? selectedEntry\n : (entries[0] ?? null)\n const activeFile = activeEntry?.kind === "file" ? activeEntry : null\n const activeViewerKind = activeFile ? viewerKindForFile(activeFile) : null\n // While arrow keys are scrubbing the strip, the center pane shows a\n // spinner; the full-size viewer (and its URL resolution) mounts once the\n // selection settles so each keystroke stays cheap.\n const settledPath = useSettledValue(activeEntry?.path ?? null, 200)\n const isSettled = settledPath === (activeEntry?.path ?? null)\n const { isResolving, url: activeFileUrl } = useResolvedFileUrl(\n isSettled ? activeFile : null,\n getFileUrl\n )\n const isStageLoading =\n activeFile !== null &&\n (!isSettled || (activeViewerKind !== null && isResolving))\n const activeFileSize = activeFile ? formatByteSize(activeFile.size) : null\n\n const handleKeyDown = (event: React.KeyboardEvent) => {\n if (entries.length === 0) return\n\n const currentIndex = activeEntry\n ? entries.findIndex((entry) => entry.path === activeEntry.path)\n : -1\n\n if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") {\n const match = typeAhead(event, entries, currentIndex)\n\n if (match) {\n onSelect(match)\n // The matched tile may be outside the strip\'s virtual window; the\n // active-tile effect scrolls it in, and focus follows once mounted.\n requestAnimationFrame(() => stripRefs.current.get(match.path)?.focus())\n }\n return\n }\n\n const nextEntry =\n entries[\n currentIndex === -1\n ? 0\n : currentIndex + (event.key === "ArrowLeft" ? -1 : 1)\n ]\n\n if (!nextEntry) return\n\n onSelect(nextEntry)\n stripRefs.current.get(nextEntry.path)?.focus()\n event.preventDefault()\n }\n\n const { end: stripEnd, start: stripStart } = useVirtualWindow({\n count: entries.length,\n horizontal: true,\n itemStride: GALLERY_TILE_STRIDE,\n leadingPx: GALLERY_STRIP_PADDING,\n overscan: 8,\n viewportRef: stripViewportRef,\n })\n\n // Keep the active tile mounted and visible while scrubbing or when the\n // selection arrives from another view.\n const activePath = activeEntry?.path ?? null\n\n React.useLayoutEffect(() => {\n if (!activePath) return\n\n scrollIndexIntoView({\n horizontal: true,\n index: entries.findIndex((entry) => entry.path === activePath),\n itemSize: GALLERY_TILE_SIZE,\n itemStride: GALLERY_TILE_STRIDE,\n leadingPx: GALLERY_STRIP_PADDING,\n viewport: stripViewportRef.current,\n })\n }, [activePath, entries])\n\n return (\n <div className="flex size-full flex-col" onKeyDown={handleKeyDown}>\n {/* The strip comes first in DOM order (rendered below via order-last)\n so the filmstrip is the view\'s single tab stop: Shift+Tab exits to\n the toolbar instead of landing inside the embedded viewers. */}\n <ScrollArea\n orientation="horizontal"\n className="order-last h-auto w-full shrink-0 border-t"\n viewportRef={stripViewportRef}\n viewportClassName="p-2"\n >\n <div\n className="relative h-14 min-w-full"\n style={{\n width: entries.length\n ? entries.length * GALLERY_TILE_STRIDE - GALLERY_TILE_GAP\n : undefined,\n }}\n >\n <div\n role="listbox"\n aria-label="Files"\n className="absolute inset-y-0 flex items-center gap-1.5"\n style={{ left: stripStart * GALLERY_TILE_STRIDE }}\n >\n {entries.slice(stripStart, stripEnd).map((entry) => {\n const isActive =\n entry.path === (activeEntry?.path ?? selectedPath)\n\n return (\n <button\n key={entry.path}\n type="button"\n role="option"\n aria-selected={isActive}\n tabIndex={isActive ? 0 : -1}\n ref={(element) => {\n if (element) {\n stripRefs.current.set(entry.path, element)\n } else {\n stripRefs.current.delete(entry.path)\n }\n }}\n onClick={() => onSelect(entry)}\n onDoubleClick={() => onOpen(entry)}\n onKeyDown={(event) => {\n if (event.key === "Enter") onOpen(entry)\n }}\n title={entry.name}\n className={cn(\n "flex size-14 shrink-0 items-center justify-center rounded-md border border-transparent p-1 outline-none focus-visible:ring-2 focus-visible:ring-ring",\n isActive && "border-ring/40 bg-accent"\n )}\n >\n {entry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-9 w-auto" />\n ) : (\n <FileVisual\n file={entry}\n className="w-9 rounded-sm"\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )}\n </button>\n )\n })}\n </div>\n </div>\n </ScrollArea>\n <div className="flex min-h-0 flex-1">\n <div className="flex min-h-0 min-w-0 flex-1 items-center justify-center p-3">\n {activeEntry ? (\n activeEntry.kind === "folder" ? (\n <FileSystemFolderGlyph className="h-40 max-h-full w-auto drop-shadow-md" />\n ) : isStageLoading ? (\n <Spinner className="size-6 text-muted-foreground" />\n ) : activeViewerKind === "image" && activeFileUrl ? (\n <img\n src={activeFileUrl}\n alt={activeEntry.name}\n className="max-h-full max-w-full rounded-lg object-contain"\n />\n ) : activeViewerKind === "pdf" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <React.Suspense fallback={<FileSystemViewerLoading />}>\n <LazyPDFViewer\n key={activeEntry.path}\n file={activeFileUrl}\n className="h-full"\n showToolbar={false}\n />\n </React.Suspense>\n </div>\n ) : activeViewerKind === "docx" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <React.Suspense fallback={<FileSystemViewerLoading />}>\n <LazyDocxViewerPreview\n key={activeEntry.path}\n src={activeFileUrl}\n fileName={activeEntry.name}\n className="h-full"\n showToolbar={false}\n />\n </React.Suspense>\n </div>\n ) : activeViewerKind === "xlsx" && activeFileUrl ? (\n <div className="size-full overflow-hidden rounded-lg border">\n <React.Suspense fallback={<FileSystemViewerLoading />}>\n <LazyXlsxViewerPreview\n key={activeEntry.path}\n src={activeFileUrl}\n fileName={activeEntry.name}\n className="h-full"\n showToolbar={false}\n />\n </React.Suspense>\n </div>\n ) : (\n <FileVisual\n file={activeEntry}\n className="w-56 max-w-full"\n loadPreviewImageUrl={loadPreviewImageUrl}\n pageable\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n )\n ) : null}\n </div>\n {activeEntry ? (\n <ScrollArea\n orientation="vertical"\n className="hidden w-64 shrink-0 border-l sm:block"\n viewportClassName="flex flex-col gap-3 p-4"\n >\n <div className="flex items-center gap-3">\n {activeFile ? (\n <FileVisual\n file={activeFile}\n className={cn(\n "shrink-0 rounded-sm",\n (activeFile.previewAspectRatio ?? 0.78) > 1.2\n ? "w-16"\n : "w-9"\n )}\n previewAspectRatio={0.78}\n renderFilePreview={renderFilePreview}\n />\n ) : (\n <FileSystemFolderGlyph className="h-8 w-auto shrink-0" />\n )}\n <div className="min-w-0 flex-1">\n <div className="text-sm font-semibold break-words">\n {activeEntry.name}\n </div>\n <div className="text-xs text-muted-foreground">\n {activeFile ? fileKindLabel(activeFile) : "Folder"}\n {activeFileSize ? ` - ${activeFileSize}` : null}\n </div>\n </div>\n </div>\n <FileSystemInformation entry={activeEntry} index={index} />\n </ScrollArea>\n ) : null}\n </div>\n </div>\n )\n}\n'export function FileSystemSourceCode() {return (diff --git a/apps/v4/components/layout-blocks-docs.tsx b/apps/v4/components/layout-blocks-docs.tsxindex dd89252..48fcc42 100644--- a/apps/v4/components/layout-blocks-docs.tsx+++ b/apps/v4/components/layout-blocks-docs.tsx@@ -8131,7 +8131,7 @@ function convertBlockToHighlightArea(block: OcrBlock): HighlightArea {}}-function BlockOverlay({+const BlockOverlay = React.memo(function BlockOverlay({block,isActive,}: {@@ -8157,9 +8157,13 @@ function BlockOverlay({}}/>)-}+})-function OcrBlockMarkdown({ text }: { text: string }) {+const OcrBlockMarkdown = React.memo(function OcrBlockMarkdown({+ text,+}: {+ text: string+}) {const markdown = text.replace(OCR_MARKDOWN_FIGURE_CAPTION_PATTERN, (tag) =>tag.startsWith("</") ? "</figcaption>" : "<figcaption>")@@ -8244,7 +8248,7 @@ function OcrBlockMarkdown({ text }: { text: string }) {</ReactMarkdown></div>)-}+})function OcrBlocksPanel({activeBlockId,@@ -8265,15 +8269,21 @@ function OcrBlocksPanel({const focusedBlockId = activeBlockId ?? localActiveBlockIdconst activeBlock =blocks.find((block) => block.id === focusedBlockId) ?? firstBlock+ const focusedBlockIdRef = React.useRef(focusedBlockId)++ React.useEffect(() => {+ focusedBlockIdRef.current = focusedBlockId+ }, [focusedBlockId])const focusBlock = React.useCallback((block: OcrBlock) => {- if (block.id === focusedBlockId) return+ if (block.id === focusedBlockIdRef.current) return+ focusedBlockIdRef.current = block.idsetLocalActiveBlockId(block.id)onBlockFocus?.(block)},- [focusedBlockId, onBlockFocus]+ [onBlockFocus])const estimateBlockSize = React.useCallback((index: number) => {@@ -8289,7 +8299,7 @@ function OcrBlocksPanel({estimateSize: estimateBlockSize,getItemKey: (index) => blocks[index]?.id ?? index,getScrollElement: () => scrollViewportRef.current,- overscan: 12,+ overscan: 6,})React.useEffect(() => {@@ -8357,7 +8367,7 @@ function OcrBlocksPanel({)}-function OcrBlockButton({+const OcrBlockButton = React.memo(function OcrBlockButton({block,isActive,onFocusBlock,@@ -8404,7 +8414,7 @@ function OcrBlockButton({</div></button>)-}+})export function OcrBlocks() {return (@@ -8455,6 +8465,21 @@ export function OcrBlocksBlock({)}, [])+ const activeOverlayBlockId = activeBlock?.id+ const renderPageOverlay = React.useCallback(+ ({ pageNumber }: { pageNumber: number }) =>+ blocks+ .filter((block) => block.page === pageNumber)+ .map((block) => (+ <BlockOverlay+ key={block.id}+ block={block}+ isActive={activeOverlayBlockId === block.id}+ />+ )),+ [activeOverlayBlockId, blocks]+ )+return (<PdfBlockResizableShellautoSaveId="pdf-block-layout-blocks"@@ -8463,17 +8488,7 @@ export function OcrBlocksBlock({ref={viewerRef}file={file}defaultZoom={defaultViewerZoom}- renderPageOverlay={({ pageNumber }) =>- blocks- .filter((block) => block.page === pageNumber)- .map((block) => (- <BlockOverlay- key={block.id}- block={block}- isActive={activeBlock?.id === block.id}- />- ))- }+ renderPageOverlay={renderPageOverlay}/>}right={@@ -8599,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\nfunction OcrBlockMarkdown({ text }: { text: string }) {\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\nfunction 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 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 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: 12,\n })\n\n const focusBlock = React.useCallback(\n (block: OcrBlock) => {\n if (block.id === focusedBlockId) return\n\n setLocalActiveBlockId(block.id)\n onBlockFocus?.(block)\n },\n [focusedBlockId, 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 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'export function OcrBlocksSource() {return (diff --git a/apps/v4/components/pdf-viewer-source-code.tsx b/apps/v4/components/pdf-viewer-source-code.tsxindex 1200891..b3416b4 100644--- a/apps/v4/components/pdf-viewer-source-code.tsx+++ b/apps/v4/components/pdf-viewer-source-code.tsx@@ -3,7 +3,7 @@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 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 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 <div className="text-sm whitespace-nowrap text-primary">\n Page {activePage} of {numPages || "-"}\n </div>\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 {showDownload ? (\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 <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\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 {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'+ '"use client"\n\nimport * as React from "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"\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>\ntype PDFPageProxy = Awaited<ReturnType<PDFDocumentProxy["getPage"]>>\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 PAGE_OVERSCAN = 8\nconst FAST_SCROLL_PAGE_OVERSCAN = 14\nconst THUMBNAIL_VIRTUALIZER_PADDING = 16\nconst THUMBNAIL_ITEM_CHROME_HEIGHT = 48\nconst THUMBNAIL_ITEM_GAP = 12\nconst THUMBNAIL_WIDTH = 92\nconst SEARCH_SCAN_BATCH_SIZE = 24\nconst INTERSECTION_THRESHOLDS = [\n 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1,\n]\n\ntype PDFSearchMatch = {\n pageNumber: number\n indexOnPage: number\n}\n\ntype PDFSearchResults = {\n query: string\n matches: PDFSearchMatch[]\n}\n\ntype PDFSearchHighlightArea = {\n id: string\n pageNumber: number\n indexOnPage: number\n left: number\n top: number\n width: number\n height: number\n}\n\nfunction extractVirtualRange(range: { startIndex: number; endIndex: number }) {\n const indexes: number[] = []\n\n for (let index = range.startIndex; index <= range.endIndex; index += 1) {\n indexes.push(index)\n }\n\n return indexes\n}\n\n// The pdf.js text layer is an invisible copy of the page text used for\n// selection, search and copy. Its glyphs only approximate the rendered\n// canvas, so they must stay transparent in every state (selection, search\n// highlights) - only the selection/highlight rectangles should show.\nconst PAGE_TEXT_LAYER_CLASSNAME = [\n "[&_.textLayer_*::selection]:bg-blue-500/30 [&_.textLayer_*::selection]:text-transparent",\n].join(" ")\n\nfunction countOccurrences(text: string, query: string) {\n if (!query) return 0\n\n let count = 0\n let index = text.indexOf(query)\n\n while (index !== -1) {\n count += 1\n index = text.indexOf(query, index + query.length)\n }\n\n return count\n}\n\nfunction getSearchHighlightAreas({\n textLayer,\n pageNumber,\n query,\n}: {\n textLayer: HTMLElement\n pageNumber: number\n query: string\n}): PDFSearchHighlightArea[] {\n if (!query) return []\n\n const walker = document.createTreeWalker(textLayer, NodeFilter.SHOW_TEXT)\n const textNodes: Text[] = []\n const textLayerRect = textLayer.getBoundingClientRect()\n const areas: PDFSearchHighlightArea[] = []\n\n while (walker.nextNode()) {\n textNodes.push(walker.currentNode as Text)\n }\n\n let matchIndexOnPage = 0\n\n textNodes.forEach((textNode) => {\n const normalizedText = textNode.data.toLowerCase()\n let matchStart = normalizedText.indexOf(query)\n\n while (matchStart !== -1) {\n const range = document.createRange()\n\n range.setStart(textNode, matchStart)\n range.setEnd(textNode, matchStart + query.length)\n\n Array.from(range.getClientRects()).forEach((rect, rectIndex) => {\n if (rect.width <= 0 || rect.height <= 0) return\n\n areas.push({\n id: `${pageNumber}-${matchIndexOnPage}-${rectIndex}`,\n pageNumber,\n indexOnPage: matchIndexOnPage,\n left: rect.left - textLayerRect.left,\n top: rect.top - textLayerRect.top,\n width: rect.width,\n height: rect.height,\n })\n })\n\n range.detach()\n matchIndexOnPage += 1\n matchStart = normalizedText.indexOf(query, matchStart + query.length)\n }\n })\n\n return areas\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\n// Mirrors react-pdf-viewer\'s render priority: the most visible unpainted\n// page first, then the page after the last visible one, then the page\n// before the first visible one.\nfunction pickNextPageToPaint({\n paintedPageNumbers,\n visibilityRatios,\n virtualPageNumbers,\n}: {\n paintedPageNumbers: Set<number>\n visibilityRatios: Map<number, number>\n virtualPageNumbers: number[]\n}) {\n let bestPage: number | undefined\n let bestRatio = 0\n\n virtualPageNumbers.forEach((pageNumber) => {\n if (paintedPageNumbers.has(pageNumber)) return\n\n const ratio = visibilityRatios.get(pageNumber) ?? 0\n\n if (ratio > bestRatio) {\n bestRatio = ratio\n bestPage = pageNumber\n }\n })\n\n if (bestPage !== undefined) return bestPage\n\n let firstVisibleIndex = -1\n let lastVisibleIndex = -1\n\n virtualPageNumbers.forEach((pageNumber, index) => {\n if ((visibilityRatios.get(pageNumber) ?? -1) < 0) return\n if (firstVisibleIndex === -1) firstVisibleIndex = index\n lastVisibleIndex = index\n })\n\n for (\n let index = lastVisibleIndex + 1;\n index < virtualPageNumbers.length;\n index += 1\n ) {\n const pageNumber = virtualPageNumbers[index]\n\n if (pageNumber !== undefined && !paintedPageNumbers.has(pageNumber)) {\n return pageNumber\n }\n }\n\n const backwardStart =\n (firstVisibleIndex === -1 ? virtualPageNumbers.length : firstVisibleIndex) -\n 1\n\n for (let index = backwardStart; index >= 0; index -= 1) {\n const pageNumber = virtualPageNumbers[index]\n\n if (pageNumber !== undefined && !paintedPageNumbers.has(pageNumber)) {\n return pageNumber\n }\n }\n\n return undefined\n}\n\nfunction getPdfWorkerUrl(pdfjsVersion: string) {\n return `https://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 arePdfDocumentOptionsEqual(\n left: ReactPdf.DocumentProps["options"] | undefined,\n right: ReactPdf.DocumentProps["options"] | undefined\n) {\n if (left === right) return true\n if (!left || !right) return false\n\n const leftKeys = Object.keys(left) as Array<keyof typeof left>\n const rightKeys = Object.keys(right) as Array<keyof typeof right>\n\n if (leftKeys.length !== rightKeys.length) return false\n\n return leftKeys.every((key) => Object.is(left[key], right[key]))\n}\n\nfunction useStablePdfDocumentOptions(\n options: ReactPdf.DocumentProps["options"] | undefined\n) {\n const [stableOptions, setStableOptions] = React.useState(options)\n\n React.useEffect(() => {\n setStableOptions((currentOptions) =>\n arePdfDocumentOptionsEqual(currentOptions, options)\n ? currentOptions\n : options\n )\n }, [options])\n\n return arePdfDocumentOptionsEqual(stableOptions, options)\n ? stableOptions\n : options\n}\n\nfunction normalizeRotation(rotation: number) {\n return (((Math.round(rotation / 90) * 90) % 360) + 360) % 360\n}\n\nfunction isQuarterTurn(rotation: number) {\n return (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\nfunction getPdfPageMetrics(page: PDFPageProxy): PDFPageMetrics {\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 onNavigate,\n activeMatchNumber,\n totalMatches,\n isScanning,\n}: {\n value: string\n onValueChange: (value: string) => void\n onApply: () => void\n onClear: () => void\n onNavigate: (delta: number) => void\n activeMatchNumber: number\n totalMatches: number | null\n isScanning: boolean\n}) {\n const hasMatches = Boolean(totalMatches)\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") return\n\n event.preventDefault()\n\n if (event.shiftKey && hasMatches) {\n onNavigate(-1)\n return\n }\n\n onApply()\n }}\n />\n {isScanning || totalMatches !== null ? (\n <div className="flex items-center justify-between gap-2">\n <div className="text-xs text-muted-foreground tabular-nums">\n {isScanning\n ? "Searching..."\n : hasMatches\n ? `${activeMatchNumber} of ${totalMatches}`\n : "No matches"}\n </div>\n <div className="flex items-center gap-1">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Previous match"\n disabled={!hasMatches}\n onClick={() => onNavigate(-1)}\n >\n <HugeiconsIcon icon={ArrowUp01Icon} className="size-4" />\n </Button>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Next match"\n disabled={!hasMatches}\n onClick={() => onNavigate(1)}\n >\n <HugeiconsIcon icon={ArrowDown01Icon} className="size-4" />\n </Button>\n </div>\n </div>\n ) : null}\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 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\nconst PDFViewerPage = React.memo(function PDFViewerPage({\n devicePixelRatioLimit,\n effectiveRotation,\n reactPdf,\n pageNumber,\n pageWidth,\n pageHeight,\n zoom,\n shouldRenderPage,\n searchHighlightAreas,\n activeSearchMatch,\n pageClassName,\n renderPageOverlay,\n onCanvasRendered,\n onTextLayerRendered,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n}: {\n devicePixelRatioLimit: number\n effectiveRotation: number\n reactPdf: ReactPdfModule\n pageNumber: number\n pageWidth: number\n pageHeight: number\n zoom: number\n shouldRenderPage: boolean\n searchHighlightAreas: PDFSearchHighlightArea[]\n activeSearchMatch: PDFSearchMatch | null\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onCanvasRendered: (pageNumber: number, devicePixelRatioLimit: number) => void\n onTextLayerRendered: (pageNumber: 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 pageStyle = { width: pageWidth, height: pageHeight }\n // react-pdf wipes and rebuilds a page\'s entire text layer (including a\n // worker round-trip) whenever any render callback changes identity, so\n // these must stay referentially stable for the lifetime of the page.\n const handleCanvasRendered = React.useCallback(\n () => onCanvasRendered(pageNumber, devicePixelRatioLimit),\n [devicePixelRatioLimit, onCanvasRendered, pageNumber]\n )\n const handleTextLayerRendered = React.useCallback(\n () => onTextLayerRendered(pageNumber),\n [onTextLayerRendered, pageNumber]\n )\n const handlePageLoadFailed = React.useCallback(() => {\n onCanvasRendered(pageNumber, devicePixelRatioLimit)\n onTextLayerRendered(pageNumber)\n }, [devicePixelRatioLimit, onCanvasRendered, onTextLayerRendered, pageNumber])\n\n return (\n <div\n data-pdf-viewer-page={pageNumber}\n className={cn(\n "relative",\n PAGE_TEXT_LAYER_CLASSNAME,\n pageClassName?.(pageNumber)\n )}\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 <reactPdf.Page\n pageNumber={pageNumber}\n width={pageWidth}\n rotate={effectiveRotation}\n className="overflow-hidden border bg-background shadow-xs"\n renderAnnotationLayer={false}\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 onLoadError={handlePageLoadFailed}\n onRenderSuccess={handleCanvasRendered}\n onRenderTextLayerSuccess={handleTextLayerRendered}\n onRenderTextLayerError={handleTextLayerRendered}\n onRenderError={handleCanvasRendered}\n />\n ) : (\n <div className="grid size-full place-items-center border bg-white shadow-xs">\n <Spinner className="size-4" />\n </div>\n )}\n {searchHighlightAreas.length ? (\n <div className="pointer-events-none absolute inset-0 z-10">\n {searchHighlightAreas.map((area) => {\n const isCurrent =\n activeSearchMatch?.pageNumber === area.pageNumber &&\n activeSearchMatch.indexOnPage === area.indexOnPage\n\n return (\n <div\n key={area.id}\n data-pdf-search-highlight-page={area.pageNumber}\n data-pdf-search-highlight-index={area.indexOnPage}\n data-current={isCurrent ? "" : undefined}\n className={cn(\n "absolute rounded-[2px] bg-yellow-300/45 mix-blend-multiply ring-1 ring-yellow-500/20 dark:bg-yellow-300/35",\n isCurrent && "bg-orange-400/80 dark:bg-orange-400/75"\n )}\n style={{\n left: area.left,\n top: area.top,\n width: area.width,\n height: area.height,\n }}\n />\n )\n })}\n </div>\n ) : null}\n {renderPageOverlay?.({\n pageNumber,\n pageWidth,\n pageHeight,\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 [searchResults, setSearchResults] =\n React.useState<PDFSearchResults | null>(null)\n const [activeSearchMatchIndex, setActiveSearchMatchIndex] =\n React.useState(0)\n const [isSearchScanning, setIsSearchScanning] = React.useState(false)\n const [isDocumentLoading, setIsDocumentLoading] = React.useState(true)\n const [isFirstPageRendering, setIsFirstPageRendering] = React.useState(true)\n const [pageVisibilityRatios, setPageVisibilityRatios] = React.useState<\n Map<number, number>\n >(() => new Map([[1, 1]]))\n const [lowResolutionPageNumbers, setLowResolutionPageNumbers] =\n React.useState<Set<number>>(() => new Set())\n const [scrollState, setScrollState] = React.useState<{\n direction: PDFViewerScrollDirection\n isFastScrolling: boolean\n }>({ direction: "none", isFastScrolling: false })\n // Render queue (react-pdf-viewer\'s model): exactly one page rasterizes\n // at a time. `renderingPageNumber` is the page whose canvas/text layers\n // are in flight; `paintedPageNumbers` are mounted pages that finished.\n const [paintedPageNumbers, setPaintedPageNumbers] = React.useState<\n Set<number>\n >(() => new Set())\n const [renderingPageNumber, setRenderingPageNumber] = React.useState<\n number | null\n >(null)\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 pendingRenderLayersRef = React.useRef(\n new Map<number, { canvas: boolean; text: boolean }>()\n )\n const pageCacheRef = React.useRef(new Map<number, Promise<PDFPageProxy>>())\n const pageSearchTextCacheRef = React.useRef(new Map<number, string[]>())\n const [searchHighlightAreasByPage, setSearchHighlightAreasByPage] =\n React.useState<Map<number, PDFSearchHighlightArea[]>>(() => new Map())\n const pendingSearchMatchRef = React.useRef<PDFSearchMatch | null>(null)\n const lastAutoJumpedSearchResultsRef =\n React.useRef<PDFSearchResults | null>(null)\n const [activeSearchMatch, setActiveSearchMatch] =\n React.useState<PDFSearchMatch | null>(null)\n const scrollTrackerRef = React.useRef({\n scrollTop: 0,\n timestamp: 0,\n })\n\n React.useEffect(() => {\n setPdfFile(file ?? "")\n }, [file])\n\n // Reset all per-document state when the displayed file changes - this\n // covers both the `file` prop and uploads.\n React.useEffect(() => {\n setLoadError(false)\n setIsDocumentLoading(Boolean(pdfFile))\n setIsFirstPageRendering(Boolean(pdfFile))\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 setPaintedPageNumbers(new Set())\n setLowResolutionPageNumbers(new Set())\n setPageVisibilityRatios(new Map([[1, 1]]))\n setScrollState({ direction: "none", isFastScrolling: false })\n setSearchDraft("")\n setSearchQuery("")\n setSearchResults(null)\n setSearchHighlightAreasByPage(new Map())\n setActiveSearchMatch(null)\n pageCacheRef.current.clear()\n pageSearchTextCacheRef.current.clear()\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [pdfFile])\n\n // A new document or zoom level invalidates every painted page; pages\n // re-enter through the render queue one at a time.\n React.useEffect(() => {\n pendingRenderLayersRef.current.clear()\n setPaintedPageNumbers(new Set())\n setRenderingPageNumber(null)\n }, [pdfDocument, zoom])\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 getEffectivePageDimensions = 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\n return {\n ...getPageDimensions(metrics, effectiveRotation),\n effectiveRotation,\n }\n },\n [getPageMetrics, pageRotationDeltas]\n )\n const getEstimatedPageSize = React.useCallback(\n (index: number) => {\n const pageNumber = renderedPageNumbers[index] ?? firstRenderedPage\n\n return getEffectivePageDimensions(pageNumber).height * zoom\n },\n [firstRenderedPage, getEffectivePageDimensions, renderedPageNumbers, zoom]\n )\n const getPageItemKey = React.useCallback(\n (index: number) => renderedPageNumbers[index] ?? index,\n [renderedPageNumbers]\n )\n const normalizedPageRenderBuffer = Math.max(0, Math.floor(pageRenderBuffer))\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 const renderRangePageNumberSet = React.useMemo(() => {\n const pageNumbersInRange = new Set<number>()\n\n renderedPageNumbers.forEach((pageNumber) => {\n if (\n pageNumber >= renderRange.startPage &&\n pageNumber <= renderRange.endPage\n ) {\n pageNumbersInRange.add(pageNumber)\n }\n })\n\n return pageNumbersInRange\n }, [renderRange.endPage, renderRange.startPage, renderedPageNumbers])\n const pageRangeExtractor = React.useCallback(\n (range: { startIndex: number; endIndex: number }) => {\n const indexes = new Set(extractVirtualRange(range))\n\n renderedPageNumbers.forEach((pageNumber, index) => {\n if (renderRangePageNumberSet.has(pageNumber)) {\n indexes.add(index)\n }\n })\n\n return Array.from(indexes).sort((left, right) => left - right)\n },\n [renderRangePageNumberSet, renderedPageNumbers]\n )\n const pageVirtualizer = useVirtualizer({\n count: renderedPageNumbers.length,\n estimateSize: getEstimatedPageSize,\n gap: PAGE_VIRTUALIZER_GAP,\n getItemKey: getPageItemKey,\n getScrollElement: () => viewportRef.current,\n overscan: scrollState.isFastScrolling\n ? FAST_SCROLL_PAGE_OVERSCAN\n : PAGE_OVERSCAN,\n paddingEnd: PAGE_VIRTUALIZER_PADDING,\n paddingStart: PAGE_VIRTUALIZER_PADDING,\n rangeExtractor: pageRangeExtractor,\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 queuedPageNumbers = React.useMemo(\n () =>\n virtualPageNumbers.filter(\n (pageNumber) =>\n pageMetrics.has(pageNumber) &&\n renderRangePageNumberSet.has(pageNumber)\n ),\n [pageMetrics, renderRangePageNumberSet, virtualPageNumbers]\n )\n React.useEffect(() => {\n const viewport = viewportRef.current\n\n if (!viewport) return\n\n const observer = new IntersectionObserver(\n (entries) => {\n setPageVisibilityRatios((currentRatios) => {\n const nextRatios = new Map(currentRatios)\n let changed = false\n\n entries.forEach((entry) => {\n const pageNumber = Number(\n (entry.target as HTMLElement).dataset.pdfViewerFrame\n )\n\n if (!pageNumber) return\n\n const ratio = entry.isIntersecting ? entry.intersectionRatio : -1\n\n if (nextRatios.get(pageNumber) !== ratio) {\n nextRatios.set(pageNumber, ratio)\n changed = true\n }\n })\n\n return changed ? nextRatios : currentRatios\n })\n },\n {\n root: viewport,\n threshold: INTERSECTION_THRESHOLDS,\n }\n )\n const observedPageNumbers = new Set<number>()\n\n virtualPageNumbers.forEach((pageNumber) => {\n const element = viewport.querySelector<HTMLElement>(\n `[data-pdf-viewer-frame="${pageNumber}"]`\n )\n\n if (!element) return\n\n observedPageNumbers.add(pageNumber)\n observer.observe(element)\n })\n\n setPageVisibilityRatios((currentRatios) => {\n let changed = false\n const nextRatios = new Map<number, number>()\n\n currentRatios.forEach((ratio, pageNumber) => {\n if (observedPageNumbers.has(pageNumber)) {\n nextRatios.set(pageNumber, ratio)\n } else {\n changed = true\n }\n })\n\n return changed ? nextRatios : currentRatios\n })\n\n return () => observer.disconnect()\n }, [virtualPageNumbers, virtualPageNumbersKey])\n\n React.useEffect(() => {\n let bestPage = activePage\n let bestRatio = -1\n\n pageVisibilityRatios.forEach((ratio, pageNumber) => {\n if (ratio > bestRatio) {\n bestRatio = ratio\n bestPage = pageNumber\n }\n })\n\n if (bestRatio < 0) {\n bestPage = firstRenderedPage\n }\n\n setActivePage((currentPage) =>\n currentPage === bestPage ? currentPage : bestPage\n )\n }, [activePage, firstRenderedPage, pageVisibilityRatios])\n\n const previousActivePageRef = React.useRef(activePage)\n\n React.useEffect(() => {\n if (previousActivePageRef.current === activePage) return\n\n previousActivePageRef.current = activePage\n onActivePageChange?.(activePage)\n }, [activePage, onActivePageChange])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !numPages) return\n\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\n scrollTrackerRef.current = {\n scrollTop: viewport.scrollTop,\n timestamp: performance.now(),\n }\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.clearTimeout(idleTimeoutId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [numPages])\n\n const maxEstimatedPageWidth = React.useMemo(() => {\n if (!renderedPageNumbers.length) return pageWidth * zoom\n\n return renderedPageNumbers.reduce(\n (maxWidth, pageNumber) =>\n Math.max(\n maxWidth,\n getEffectivePageDimensions(pageNumber).width * zoom\n ),\n 0\n )\n }, [getEffectivePageDimensions, pageWidth, renderedPageNumbers, zoom])\n const activePageIndex = React.useMemo(\n () => renderedPageNumbers.indexOf(activePage),\n [activePage, renderedPageNumbers]\n )\n const getCachedPdfPage = React.useCallback(\n (pageNumber: number) => {\n const pdf = pdfDocument\n\n if (!pdf) {\n return Promise.reject(new Error("PDF document is not loaded"))\n }\n\n const cachedPage = pageCacheRef.current.get(pageNumber)\n\n if (cachedPage) return cachedPage\n\n const pagePromise = pdf.getPage(pageNumber)\n\n pageCacheRef.current.set(pageNumber, pagePromise)\n return pagePromise\n },\n [pdfDocument]\n )\n const pageMetricsRef = React.useRef(pageMetrics)\n pageMetricsRef.current = pageMetrics\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 !pageMetricsRef.current.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 getPdfPageMetrics(await getCachedPdfPage(pageNumber)),\n ] as const\n } catch {\n return [pageNumber, defaultPageMetrics] as const\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 [defaultPageMetrics, getCachedPdfPage, 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 = useStablePdfDocumentOptions(\n documentOptions ?? defaultDocumentOptions\n )\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 // Keep the thumbnail list mounted once it has been shown: the sidebar\n // hides by sliding offscreen, and unmounting would throw away the\n // rasterized thumbnails and re-render all of them on every reopen.\n const [thumbnailSidebarMounted, setThumbnailSidebarMounted] =\n React.useState(false)\n\n React.useEffect(() => {\n if (thumbnailSidebarVisible) {\n setThumbnailSidebarMounted(true)\n }\n }, [thumbnailSidebarVisible])\n\n const getEstimatedThumbnailItemSize = React.useCallback(\n (index: number) => {\n const pageNumber = renderedPageNumbers[index] ?? firstRenderedPage\n const dimensions = getEffectivePageDimensions(pageNumber)\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 [firstRenderedPage, getEffectivePageDimensions, renderedPageNumbers]\n )\n const thumbnailVirtualizer = useVirtualizer({\n count: thumbnailSidebarMounted ? renderedPageNumbers.length : 0,\n estimateSize: getEstimatedThumbnailItemSize,\n getItemKey: getPageItemKey,\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 React.useEffect(() => {\n pageVirtualizer.measure()\n }, [pageMetrics, pageRotationDeltas, pageVirtualizer, zoom])\n\n // Forget render state for pages that left the render range; if the\n // in-flight page left, abandon it so the scheduler can pick a new one.\n React.useEffect(() => {\n const pendingLayers = pendingRenderLayersRef.current\n\n Array.from(pendingLayers.keys()).forEach((pageNumber) => {\n if (!renderRangePageNumberSet.has(pageNumber)) {\n pendingLayers.delete(pageNumber)\n }\n })\n setPaintedPageNumbers((currentPageNumbers) => {\n let changed = false\n const nextPageNumbers = new Set<number>()\n\n currentPageNumbers.forEach((pageNumber) => {\n if (renderRangePageNumberSet.has(pageNumber)) {\n nextPageNumbers.add(pageNumber)\n } else {\n changed = true\n }\n })\n\n return changed ? nextPageNumbers : currentPageNumbers\n })\n setRenderingPageNumber((currentPageNumber) =>\n currentPageNumber !== null &&\n !renderRangePageNumberSet.has(currentPageNumber)\n ? null\n : currentPageNumber\n )\n setLowResolutionPageNumbers((currentPageNumbers) => {\n let changed = false\n const nextPageNumbers = new Set(currentPageNumbers)\n\n currentPageNumbers.forEach((pageNumber) => {\n if (!renderRangePageNumberSet.has(pageNumber)) {\n nextPageNumbers.delete(pageNumber)\n changed = true\n }\n })\n\n return changed ? nextPageNumbers : currentPageNumbers\n })\n }, [renderRangePageNumberSet])\n\n // The scheduler: whenever no page is rendering, hand the slot to the\n // highest-priority unpainted page in the window.\n React.useEffect(() => {\n if (renderingPageNumber !== null) return\n\n const nextPageNumber = pickNextPageToPaint({\n paintedPageNumbers,\n visibilityRatios: pageVisibilityRatios,\n virtualPageNumbers: queuedPageNumbers,\n })\n\n if (nextPageNumber === undefined) return\n\n pendingRenderLayersRef.current.set(nextPageNumber, {\n canvas: false,\n text: false,\n })\n setRenderingPageNumber(nextPageNumber)\n }, [\n paintedPageNumbers,\n pageVisibilityRatios,\n queuedPageNumbers,\n renderingPageNumber,\n ])\n\n // A fast jump can leave the single in-flight page far outside the\n // viewport. Drop that page\'s slot so the visible page can render first.\n React.useEffect(() => {\n if (renderingPageNumber === null) return\n\n const renderingRatio = pageVisibilityRatios.get(renderingPageNumber) ?? -1\n\n if (renderingRatio > 0) return\n\n const hasVisibleUnpaintedPage = queuedPageNumbers.some(\n (pageNumber) =>\n pageNumber !== renderingPageNumber &&\n !paintedPageNumbers.has(pageNumber) &&\n (pageVisibilityRatios.get(pageNumber) ?? -1) > 0\n )\n\n if (!hasVisibleUnpaintedPage) return\n\n pendingRenderLayersRef.current.delete(renderingPageNumber)\n setRenderingPageNumber(null)\n }, [\n paintedPageNumbers,\n pageVisibilityRatios,\n queuedPageNumbers,\n renderingPageNumber,\n ])\n\n const completePageLayer = React.useCallback(\n (pageNumber: number, layer: "canvas" | "text") => {\n const pendingLayers = pendingRenderLayersRef.current.get(pageNumber)\n\n if (!pendingLayers) return\n\n pendingLayers[layer] = true\n\n if (layer !== "canvas") return\n\n pendingRenderLayersRef.current.delete(pageNumber)\n setPaintedPageNumbers((currentPageNumbers) => {\n if (currentPageNumbers.has(pageNumber)) return currentPageNumbers\n\n const nextPageNumbers = new Set(currentPageNumbers)\n nextPageNumbers.add(pageNumber)\n return nextPageNumbers\n })\n setRenderingPageNumber((currentPageNumber) =>\n currentPageNumber === pageNumber ? null : currentPageNumber\n )\n setIsFirstPageRendering(false)\n },\n []\n )\n\n const handleCanvasRendered = React.useCallback(\n (pageNumber: number, devicePixelRatioLimit: number) => {\n if (devicePixelRatioLimit < MAX_DEVICE_PIXEL_RATIO) {\n setLowResolutionPageNumbers((currentPageNumbers) => {\n if (currentPageNumbers.has(pageNumber)) return currentPageNumbers\n\n const nextPageNumbers = new Set(currentPageNumbers)\n nextPageNumbers.add(pageNumber)\n return nextPageNumbers\n })\n } else {\n setLowResolutionPageNumbers((currentPageNumbers) => {\n if (!currentPageNumbers.has(pageNumber)) return currentPageNumbers\n\n const nextPageNumbers = new Set(currentPageNumbers)\n nextPageNumbers.delete(pageNumber)\n return nextPageNumbers\n })\n }\n\n completePageLayer(pageNumber, "canvas")\n },\n [completePageLayer]\n )\n\n const pageNumbersForMetrics = React.useMemo(() => {\n const nextPageNumbers = new Set<number>([\n firstRenderedPage,\n activePage,\n ...virtualPageNumbers,\n ])\n\n renderedPageNumbers.forEach((pageNumber) => {\n if (renderRangePageNumberSet.has(pageNumber)) {\n nextPageNumbers.add(pageNumber)\n }\n })\n\n return Array.from(nextPageNumbers)\n }, [\n activePage,\n firstRenderedPage,\n renderedPageNumbers,\n renderRangePageNumberSet,\n virtualPageNumbers,\n ])\n\n React.useEffect(() => {\n void loadPageMetrics(pageNumbersForMetrics)\n }, [loadPageMetrics, pageNumbersForMetrics])\n\n const normalizedSearchQuery = searchQuery.trim().toLowerCase()\n\n React.useEffect(() => {\n pageSearchTextCacheRef.current = new Map()\n }, [pdfDocument])\n\n React.useEffect(() => {\n if (!pdfDocument || !normalizedSearchQuery) {\n setSearchResults(null)\n setActiveSearchMatchIndex(0)\n setIsSearchScanning(false)\n return\n }\n\n let cancelled = false\n const pdf = pdfDocument\n\n setIsSearchScanning(true)\n\n const scanDocumentText = async () => {\n const textCache = pageSearchTextCacheRef.current\n const pagesToScan = renderedPageNumbers.filter(\n (pageNumber) => pageNumber >= 1 && pageNumber <= pdf.numPages\n )\n\n for (\n let batchStart = 0;\n batchStart < pagesToScan.length;\n batchStart += SEARCH_SCAN_BATCH_SIZE\n ) {\n await Promise.all(\n pagesToScan\n .slice(batchStart, batchStart + SEARCH_SCAN_BATCH_SIZE)\n .filter((pageNumber) => !textCache.has(pageNumber))\n .map(async (pageNumber) => {\n try {\n const page = await getCachedPdfPage(pageNumber)\n // includeMarkedContent matches how the text layer splits\n // its spans, so match counts line up with the DOM marks.\n const textContent = await page.getTextContent({\n includeMarkedContent: true,\n })\n\n textCache.set(\n pageNumber,\n textContent.items.map((item) =>\n "str" in item ? item.str.toLowerCase() : ""\n )\n )\n } catch {\n textCache.set(pageNumber, [])\n }\n })\n )\n\n if (cancelled) return\n }\n\n const matches: PDFSearchMatch[] = []\n\n pagesToScan.forEach((pageNumber) => {\n const itemTexts = textCache.get(pageNumber) ?? []\n let pageMatchCount = 0\n\n itemTexts.forEach((itemText) => {\n pageMatchCount += countOccurrences(itemText, normalizedSearchQuery)\n })\n\n for (\n let indexOnPage = 0;\n indexOnPage < pageMatchCount;\n indexOnPage += 1\n ) {\n matches.push({ pageNumber, indexOnPage })\n }\n })\n\n if (cancelled) return\n\n setSearchResults({ query: normalizedSearchQuery, matches })\n setActiveSearchMatchIndex(0)\n setIsSearchScanning(false)\n }\n\n void scanDocumentText()\n\n return () => {\n cancelled = true\n }\n }, [\n getCachedPdfPage,\n normalizedSearchQuery,\n pdfDocument,\n renderedPageNumbers,\n ])\n\n const updateSearchHighlightsForPage = React.useCallback(\n (pageNumber: number) => {\n const textLayer = viewportRef.current?.querySelector<HTMLElement>(\n `[data-pdf-viewer-page="${pageNumber}"] .react-pdf__Page__textContent`\n )\n\n const nextAreas =\n textLayer && normalizedSearchQuery\n ? getSearchHighlightAreas({\n textLayer,\n pageNumber,\n query: normalizedSearchQuery,\n })\n : []\n\n setSearchHighlightAreasByPage((currentAreasByPage) => {\n const nextAreasByPage = new Map(currentAreasByPage)\n const currentAreas = currentAreasByPage.get(pageNumber) ?? []\n\n if (!nextAreas.length) {\n if (!currentAreas.length) return currentAreasByPage\n\n nextAreasByPage.delete(pageNumber)\n return nextAreasByPage\n }\n\n nextAreasByPage.set(pageNumber, nextAreas)\n return nextAreasByPage\n })\n },\n [normalizedSearchQuery]\n )\n\n // Highlights are rendered as a separate overlay, so applying or clearing a\n // search does not mutate pdf.js text nodes. Newly rendered text layers pick\n // up their overlay rectangles from handleTextLayerRendered below.\n React.useEffect(() => {\n setActiveSearchMatch(null)\n pendingSearchMatchRef.current = null\n\n const viewport = viewportRef.current\n\n if (!viewport || !normalizedSearchQuery) {\n setSearchHighlightAreasByPage(new Map())\n return\n }\n\n viewport\n .querySelectorAll<HTMLElement>("[data-pdf-viewer-page]")\n .forEach((pageElement) => {\n const pageNumber = Number(pageElement.dataset.pdfViewerPage)\n\n if (pageNumber) {\n updateSearchHighlightsForPage(pageNumber)\n }\n })\n }, [normalizedSearchQuery, updateSearchHighlightsForPage])\n\n // Marks the current match and centers it in the viewport. Returns false\n // when the match\'s mark is not in the DOM (page not painted yet).\n const centerSearchMatch = React.useCallback((match: PDFSearchMatch) => {\n const viewport = viewportRef.current\n const highlightElement = viewport?.querySelector<HTMLElement>(\n `[data-pdf-search-highlight-page="${match.pageNumber}"][data-pdf-search-highlight-index="${match.indexOnPage}"]`\n )\n\n if (!viewport || !highlightElement) return false\n\n const viewportRect = viewport.getBoundingClientRect()\n const highlightRect = highlightElement.getBoundingClientRect()\n const isInView =\n highlightRect.top >= viewportRect.top + 48 &&\n highlightRect.bottom <= viewportRect.bottom - 48\n\n if (!isInView) {\n viewport.scrollTo({\n top: Math.max(\n 0,\n viewport.scrollTop +\n (highlightRect.top - viewportRect.top) -\n (viewport.clientHeight - highlightRect.height) / 2\n ),\n behavior: "smooth",\n })\n }\n\n return true\n }, [])\n\n React.useEffect(() => {\n const pendingMatch = pendingSearchMatchRef.current\n\n if (!pendingMatch) return\n\n const pageAreas =\n searchHighlightAreasByPage.get(pendingMatch.pageNumber) ?? []\n const hasPendingHighlight = pageAreas.some(\n (area) => area.indexOnPage === pendingMatch.indexOnPage\n )\n\n if (!hasPendingHighlight) return\n\n pendingSearchMatchRef.current = null\n window.requestAnimationFrame(() => centerSearchMatch(pendingMatch))\n }, [centerSearchMatch, searchHighlightAreasByPage])\n\n const handleTextLayerRendered = React.useCallback(\n (pageNumber: number) => {\n completePageLayer(pageNumber, "text")\n updateSearchHighlightsForPage(pageNumber)\n },\n [completePageLayer, updateSearchHighlightsForPage]\n )\n\n const goToSearchMatch = React.useCallback(\n (matchIndex: number) => {\n const matches = searchResults?.matches\n\n if (!matches?.length) return\n\n const matchCount = matches.length\n const nextIndex = ((matchIndex % matchCount) + matchCount) % matchCount\n const match = matches[nextIndex]\n\n if (!match) return\n\n setActiveSearchMatchIndex(nextIndex)\n setActiveSearchMatch(match)\n\n if (centerSearchMatch(match)) {\n pendingSearchMatchRef.current = null\n return\n }\n\n // The page is not painted yet: jump to it and let\n // handleTextLayerRendered finish the navigation.\n pendingSearchMatchRef.current = match\n\n const pageIndex = renderedPageNumbers.indexOf(match.pageNumber)\n\n if (pageIndex !== -1) {\n pageVirtualizer.scrollToIndex(pageIndex, {\n align: "start",\n behavior: "auto",\n })\n }\n },\n [centerSearchMatch, pageVirtualizer, renderedPageNumbers, searchResults]\n )\n\n React.useEffect(() => {\n if (\n !searchResults ||\n lastAutoJumpedSearchResultsRef.current === searchResults\n ) {\n return\n }\n\n lastAutoJumpedSearchResultsRef.current = searchResults\n goToSearchMatch(0)\n }, [goToSearchMatch, searchResults])\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 })\n window.setTimeout(() => {\n window.scrollTo({ top: scrollY })\n }, 150)\n }, [])\n\n const scrollToPage = React.useCallback(\n (pageNumber: number) => {\n const windowScrollY = thumbnailClickScrollYRef.current ?? window.scrollY\n const pageIndex = renderedPageNumbers.indexOf(pageNumber)\n\n if (pageIndex !== -1) {\n pageVirtualizer.scrollToIndex(pageIndex, {\n align: "start",\n behavior: "auto",\n })\n }\n\n restoreWindowScroll(windowScrollY)\n window.setTimeout(() => {\n if (thumbnailClickScrollYRef.current === windowScrollY) {\n thumbnailClickScrollYRef.current = null\n }\n }, 350)\n },\n [pageVirtualizer, renderedPageNumbers, restoreWindowScroll]\n )\n\n // react-pdf includes onItemClick in its DocumentContext value, so an\n // unstable identity here re-renders every mounted Page and Thumbnail\n // (through context, bypassing React.memo) on each PDFViewer render.\n const handleDocumentItemClick = React.useCallback(\n ({ pageNumber }: { pageNumber: number }) => scrollToPage(pageNumber),\n [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 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 pageCacheRef.current.clear()\n setPdfDocument(pdf)\n setNumPages(nextNumPages)\n setLoadError(false)\n onDocumentLoadSuccess?.(nextNumPages)\n\n try {\n const initialPageNumber = pageNumbers?.[0] ?? 1\n const initialPagePromise = pdf.getPage(initialPageNumber)\n pageCacheRef.current.set(initialPageNumber, initialPagePromise)\n const initialMetrics = getPdfPageMetrics(await initialPagePromise)\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 [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 }, [])\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 <div className="text-sm whitespace-nowrap text-primary">\n Page {activePage} of {numPages || "-"}\n </div>\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 {showDownload ? (\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 <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\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 isScanning={isSearchScanning}\n activeMatchNumber={\n searchResults?.matches.length\n ? activeSearchMatchIndex + 1\n : 0\n }\n totalMatches={\n searchResults ? searchResults.matches.length : null\n }\n onNavigate={(delta) =>\n goToSearchMatch(activeSearchMatchIndex + delta)\n }\n onApply={() => {\n const normalizedDraft = searchDraft.trim().toLowerCase()\n\n if (\n normalizedDraft &&\n normalizedDraft === searchResults?.query\n ) {\n goToSearchMatch(activeSearchMatchIndex + 1)\n return\n }\n\n setSearchQuery(searchDraft)\n }}\n onClear={() => {\n setSearchDraft("")\n setSearchQuery("")\n }}\n />\n </PopoverContent>\n </Popover>\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 onLoadSuccess={handleLoadSuccess}\n onLoadError={handleLoadError}\n onItemClick={handleDocumentItemClick}\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 {thumbnailSidebarMounted ? (\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 dimensions = getEffectivePageDimensions(pageNumber)\n const pageWidth = dimensions.width * zoom\n const pageHeight = dimensions.height * zoom\n const devicePixelRatioLimit =\n scrollState.isFastScrolling &&\n (!paintedPageNumbers.has(pageNumber) ||\n lowResolutionPageNumbers.has(pageNumber))\n ? 1\n : MAX_DEVICE_PIXEL_RATIO\n\n return (\n <div\n key={virtualPage.key}\n data-pdf-viewer-frame={pageNumber}\n className="absolute top-0 left-1/2 [contain:layout_paint]"\n style={{\n height: pageHeight,\n transform: `translateX(-50%) translateY(${virtualPage.start}px)`,\n width: pageWidth,\n }}\n >\n <PDFViewerPage\n devicePixelRatioLimit={devicePixelRatioLimit}\n effectiveRotation={dimensions.effectiveRotation}\n reactPdf={reactPdf}\n pageNumber={pageNumber}\n pageWidth={pageWidth}\n pageHeight={pageHeight}\n zoom={zoom}\n shouldRenderPage={\n paintedPageNumbers.has(pageNumber) ||\n renderingPageNumber === pageNumber\n }\n searchHighlightAreas={\n searchHighlightAreasByPage.get(pageNumber) ?? []\n }\n activeSearchMatch={activeSearchMatch}\n pageClassName={pageClassName}\n renderPageOverlay={renderPageOverlay}\n onCanvasRendered={handleCanvasRendered}\n onTextLayerRendered={handleTextLayerRendered}\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'export function PdfViewerSourceCode() {return (diff --git a/apps/v4/components/root-components-collage.tsx b/apps/v4/components/root-components-collage.tsxindex b371b2f..6a3e083 100644--- a/apps/v4/components/root-components-collage.tsx+++ b/apps/v4/components/root-components-collage.tsx@@ -17,14 +17,8 @@ import {} from "@/components/ui/document-splits"import { SchemaBuilderPanel } from "@/components/ui/schema-builder"import { Spinner } from "@/components/ui/spinner"-import {- DocumentAwareFileThumbnail,- getFileKindLabel,- SAMPLE_FILES,-} from "@/components/file-thumbnail-docs"-import { FileUpload } from "@/components/file-upload-docs"-const ROOT_PREVIEW_LAZY_ROOT_MARGIN = "900px 0px"+const ROOT_PREVIEW_LAZY_ROOT_MARGIN = "220px 0px"const ROOT_ATTENTION_PDF_URL = withUiBasePath("/samples/attention.pdf")const ROOT_ATTENTION_THUMBNAIL_URL = withUiBasePath("/samples/attention-page-1.png"@@ -61,44 +55,6 @@ const XlsxViewerPreview = dynamic(})-const LayoutBlocksBlock = dynamic(- () =>- import("@/components/layout-blocks-docs").then((mod) => mod.OcrBlocksBlock),- {- ssr: false,- loading: () => <ViewerPreviewLoading />,- }-)--const BoundingBoxCitationsBlock = dynamic(- () =>- import("@/components/bounding-box-citations-docs").then(- (mod) => mod.HumanReviewBlock- ),- {- ssr: false,- loading: () => <ViewerPreviewLoading />,- }-)--const DocxEditorBlock = dynamic(- () =>- import("@/components/docx-editor-docs").then((mod) => mod.DocxEditorBlock),- {- ssr: false,- loading: () => <ViewerPreviewLoading />,- }-)--const ESignatureBlock = dynamic(- () =>- import("@/components/e-signature-docs").then((mod) => mod.ESignatureBlock),- {- ssr: false,- loading: () => <ViewerPreviewLoading />,- }-)-const FileSystemBlock = dynamic(() =>import("@/components/file-system-docs").then(@@ -136,6 +92,10 @@ export function MobileRootPreview() {)}+// Both responsive grids are always in the React tree; CSS shows exactly one.+// Every tile body must stay wrapped in RootPreviewLoader: IntersectionObserver+// never reports intersection inside the display:none copy, so only the visible+// grid mounts the heavy viewers (and only as they approach the viewport).export function RootComponentsCollage() {return (<>@@ -148,7 +108,6 @@ export function RootComponentsCollage() {<div className="flex flex-col gap-4"><FileSystemTile /><DocxViewerTile />- <FileThumbnailTile /><SchemaBuilderTile /></div></div>@@ -161,7 +120,6 @@ export function RootComponentsCollage() {<div className="flex flex-col gap-4"><FileSystemTile /><DocxViewerTile />- <FileThumbnailTile /></div><div className="flex flex-col gap-4"><ComponentXlsxViewerTile />@@ -172,20 +130,6 @@ export function RootComponentsCollage() {)}-export function RootBlocksShowcase() {- return (- <div className="flex w-full flex-col gap-12 py-1">- <LayoutBlocksTile />- <BoundingBoxCitationsTile />- <BlockFileSystemTile />- <BlockXlsxViewerTile />- <BlockFileUploadTile />- <DocxEditorTile />- <ESignatureTile />- </div>- )-}-function PdfViewerTile() {return (<ComponentCrop@@ -193,10 +137,12 @@ function PdfViewerTile() {viewHref="/docs/components/pdf-viewer"className="h-[560px] bg-background">- <PdfViewerPreview- file={ROOT_ATTENTION_PDF_URL}- showRotateControls={false}- />+ <RootPreviewLoader idleDelayMs={900}>+ <PdfViewerPreview+ file={ROOT_ATTENTION_PDF_URL}+ showRotateControls={false}+ />+ </RootPreviewLoader></ComponentCrop>)}@@ -209,24 +155,12 @@ function FileSystemTile() {className="h-[560px] bg-background"><RootPreviewLoader>- <FileSystemBlock />+ <FileSystemBlock heightClassName="h-full" /></RootPreviewLoader></ComponentCrop>)}-function FileThumbnailTile() {- return (- <ComponentCrop- label="File Thumbnail"- viewHref="/docs/components/file-thumbnail"- className="bg-background"- >- <RootFileThumbnailGrid />- </ComponentCrop>- )-}-function DocxViewerTile() {return (<ComponentCrop@@ -234,7 +168,9 @@ function DocxViewerTile() {viewHref="/docs/components/docx-viewer"className="h-[560px] bg-background">- <DocxViewerPreview className="h-full" src={ROOT_DOCX_URL} />+ <RootPreviewLoader idleDelayMs={1200}>+ <DocxViewerPreview className="h-full" src={ROOT_DOCX_URL} />+ </RootPreviewLoader></ComponentCrop>)}@@ -246,7 +182,9 @@ function ComponentXlsxViewerTile() {viewHref="/docs/components/xlsx-viewer"className="h-[540px] bg-background 4xl:h-[500px]">- <XlsxViewerPreview className="h-full" src={ROOT_XLSX_URL} />+ <RootPreviewLoader idleDelayMs={1500}>+ <XlsxViewerPreview className="h-full" src={ROOT_XLSX_URL} />+ </RootPreviewLoader></ComponentCrop>)}@@ -260,14 +198,16 @@ function DocumentSplitsTile() {viewHref="/docs/components/document-splits"className="h-[500px] bg-background">- <DocumentSplits- className="h-full"- splits={splits}- thumbnailImages={ROOT_DOCUMENT_SPLIT_THUMBNAILS}- withFrameDivider={false}- onSelectPage={() => {}}- onSplitsChange={setSplits}- />+ <RootPreviewLoader idleDelayMs={300}>+ <DocumentSplits+ className="h-full"+ splits={splits}+ thumbnailImages={ROOT_DOCUMENT_SPLIT_THUMBNAILS}+ withFrameDivider={false}+ onSelectPage={() => {}}+ onSplitsChange={setSplits}+ />+ </RootPreviewLoader></ComponentCrop>)}@@ -279,104 +219,8 @@ function SchemaBuilderTile() {viewHref="/docs/components/schema-builder"className="h-[560px] bg-background">- <SchemaBuilderPanel className="h-full" />- </ComponentCrop>- )-}--function LayoutBlocksTile() {- return (- <ComponentCrop- label="Layout Blocks"- viewHref="/blocks#layout-blocks"- className="h-[680px] bg-background"- >- <RootPreviewLoader>- <LayoutBlocksBlock />- </RootPreviewLoader>- </ComponentCrop>- )-}--function BoundingBoxCitationsTile() {- return (- <ComponentCrop- label="Bounding Box Citations"- viewHref="/blocks#bounding-box-citations"- className="h-[680px] bg-background"- >- <RootPreviewLoader>- <BoundingBoxCitationsBlock showExpected={false} />- </RootPreviewLoader>- </ComponentCrop>- )-}--function BlockFileUploadTile() {- return (- <ComponentCrop- label="File Upload"- viewHref="/blocks#pdf-dropzone"- className="bg-background p-3"- >- <RootPreviewLoader>- <FileUpload showFileList={false} />- </RootPreviewLoader>- </ComponentCrop>- )-}--function BlockFileSystemTile() {- return (- <ComponentCrop- label="File System"- viewHref="/blocks#file-system"- className="h-[680px] bg-background"- >- <RootPreviewLoader>- <FileSystemBlock />- </RootPreviewLoader>- </ComponentCrop>- )-}--function DocxEditorTile() {- return (- <ComponentCrop- label="DOCX Editor"- viewHref="/blocks#docx-editor-block"- className="h-[680px] bg-background"- >- <RootPreviewLoader>- <DocxEditorBlock />- </RootPreviewLoader>- </ComponentCrop>- )-}--function BlockXlsxViewerTile() {- return (- <ComponentCrop- label="XLSX Viewer"- viewHref="/blocks#excel-document-splits"- className="h-[640px] bg-background"- >- <RootPreviewLoader>- <XlsxViewerPreview className="h-full" src={ROOT_XLSX_URL} />- </RootPreviewLoader>- </ComponentCrop>- )-}--function ESignatureTile() {- return (- <ComponentCrop- label="E-Signature"- viewHref="/blocks#e-signature"- className="h-[680px] bg-background"- >- <RootPreviewLoader>- <ESignatureBlock />+ <RootPreviewLoader idleDelayMs={500}>+ <SchemaBuilderPanel className="h-full" /></RootPreviewLoader></ComponentCrop>)@@ -389,32 +233,17 @@ const ROOT_DOCUMENT_SPLIT_THUMBNAILS = Object.fromEntries(])) as Record<DocumentSplit["pages"][number], string>-function RootFileThumbnailGrid() {- return (- <div className="flex flex-wrap content-start items-start justify-center gap-3 bg-background px-3 py-4">- {SAMPLE_FILES.map((file) => (- <div- key={file.name}- className="min-w-0 basis-[calc(50%-0.375rem)] space-y-1.5 sm:max-w-[7.5rem]"- >- <div className="text-xs font-medium">{getFileKindLabel(file)}</div>- <DocumentAwareFileThumbnail file={file} className="w-full" />- </div>- ))}- </div>- )-}-function useLazyRootPreview() {const [node, setNode] = React.useState<HTMLDivElement | null>(null)+ const [hasIntersected, setHasIntersected] = React.useState(false)const [shouldMountPreview, setShouldMountPreview] = React.useState(false)React.useEffect(() => {- if (shouldMountPreview) return+ if (hasIntersected) returnif (!node) returnif (!("IntersectionObserver" in window)) {- setShouldMountPreview(true)+ setHasIntersected(true)return}@@ -422,7 +251,7 @@ function useLazyRootPreview() {([entry]) => {if (!entry?.isIntersecting) return- setShouldMountPreview(true)+ setHasIntersected(true)observer.disconnect()},{ rootMargin: ROOT_PREVIEW_LAZY_ROOT_MARGIN }@@ -431,13 +260,71 @@ function useLazyRootPreview() {observer.observe(node)return () => observer.disconnect()- }, [node, shouldMountPreview])+ }, [hasIntersected, node])++ return [+ setNode,+ hasIntersected,+ shouldMountPreview,+ setShouldMountPreview,+ ] as const+}- return [setNode, shouldMountPreview] as const+function useIdleRootPreviewMount({+ idleDelayMs = 0,+ isReady,+ setShouldMountPreview,+}: {+ idleDelayMs?: number+ isReady: boolean+ setShouldMountPreview: React.Dispatch<React.SetStateAction<boolean>>+}) {+ React.useEffect(() => {+ if (!isReady) return++ let idleCallbackId: number | null = null+ let timeoutId: number | null = window.setTimeout(() => {+ timeoutId = null++ const mountPreview = () => {+ React.startTransition(() => setShouldMountPreview(true))+ }++ if ("requestIdleCallback" in window) {+ idleCallbackId = window.requestIdleCallback(mountPreview)+ } else {+ mountPreview()+ }+ }, idleDelayMs)++ return () => {+ if (timeoutId !== null) window.clearTimeout(timeoutId)+ if (idleCallbackId !== null && "cancelIdleCallback" in window) {+ window.cancelIdleCallback(idleCallbackId)+ }+ }+ }, [idleDelayMs, isReady, setShouldMountPreview])}-function RootPreviewLoader({ children }: { children: React.ReactNode }) {- const [previewRef, shouldMountPreview] = useLazyRootPreview()+function RootPreviewLoader({+ children,+ idleDelayMs,+}: {+ children: React.ReactNode+ idleDelayMs?: number+}) {+ const [+ previewRef,+ hasIntersected,+ shouldMountPreview,+ setShouldMountPreview,+ ] = useLazyRootPreview()++ useIdleRootPreviewMount({+ idleDelayMs,+ isReady: hasIntersected && !shouldMountPreview,+ setShouldMountPreview,+ })return (<div ref={previewRef} className="h-full min-h-0">@@ -479,7 +366,14 @@ function ComponentCrop({<HugeiconsIcon icon={ArrowRight01Icon} className="size-3" /></Button></div>- <div className={cn("overflow-hidden", className)}>{children}</div>+ <div+ className={cn(+ "overflow-hidden [contain:layout_paint_size] [contain-intrinsic-size:560px] [content-visibility:auto]",+ className+ )}+ >+ {children}+ </div></div>)}diff --git a/apps/v4/components/site-config.tsx b/apps/v4/components/site-config.tsxdeleted file mode 100644index ddcb710..0000000--- a/apps/v4/components/site-config.tsx+++ /dev/null@@ -1,34 +0,0 @@-"use client"--import * as React from "react"-import { LayoutTwoColumnIcon } from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"--import { trackEvent } from "@/lib/events"-import { cn } from "@/lib/utils"-import { useLayout } from "@/hooks/use-layout"-import { Button } from "@/components/ui/button"--export function SiteConfig({ className }: React.ComponentProps<typeof Button>) {- const { layout, setLayout } = useLayout()-- return (- <Button- variant="ghost"- size="icon"- onClick={() => {- const newLayout = layout === "fixed" ? "full" : "fixed"- setLayout(newLayout)- trackEvent({- name: "set_layout",- properties: { layout: newLayout },- })- }}- className={cn("size-8", className)}- title="Toggle layout"- >- <span className="sr-only">Toggle layout</span>- <HugeiconsIcon icon={LayoutTwoColumnIcon} />- </Button>- )-}diff --git a/apps/v4/components/site-header.tsx b/apps/v4/components/site-header.tsxindex 589d1db..71bf3ee 100644--- a/apps/v4/components/site-header.tsx+++ b/apps/v4/components/site-header.tsx@@ -11,7 +11,6 @@ import { Icons } from "@/components/icons"import { MainNav } from "@/components/main-nav"import { MobileNav } from "@/components/mobile-nav"import { ModeSwitcher } from "@/components/mode-switcher"-import { SiteConfig } from "@/components/site-config"import { Separator } from "@/components/ui/separator"export function SiteHeader() {@@ -70,11 +69,6 @@ export function SiteHeader() {className="ml-2 hidden h-4 self-center lg:block"/><GitHubLink />- <Separator- orientation="vertical"- className="hidden h-4 self-center group-has-data-[slot=designer]/layout:hidden 3xl:flex"- />- <SiteConfig className="hidden 3xl:flex 3xl:group-has-data-[slot=designer]/layout:hidden" /><Separator orientation="vertical" className="h-4 self-center" /><ModeSwitcher /></div>diff --git a/apps/v4/components/ui/file-system.tsx b/apps/v4/components/ui/file-system.tsxindex 16c20c2..c369932 100644--- a/apps/v4/components/ui/file-system.tsx+++ b/apps/v4/components/ui/file-system.tsx@@ -2,30 +2,67 @@import * as React from "react"import {+ ArrowDown01Icon,ArrowLeft01Icon,ArrowRight01Icon,+ ArrowUp01Icon,+ ArrowUpDownIcon,+ Calendar03Icon,Cancel01Icon,File01Icon,+ FilterIcon,GalleryThumbnailsIcon,GridViewIcon,LayoutThreeColumnIcon,LeftToRightListBulletIcon,+ Search01Icon,+ Tick02Icon,} from "@hugeicons/core-free-icons"import { HugeiconsIcon } from "@hugeicons/react"-import { prepareFileTreeInput } from "@pierre/trees"+import {+ createFileTreeIconResolver,+ getBuiltInSpriteSheet,+ prepareFileTreeInput,+ type FileTreeSortComparator,+ type FileTreeSortEntry,+} from "@pierre/trees"import { FileTree as PierreFileTree, useFileTree } from "@pierre/trees/react"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from "@/components/ui/command"import {Dialog,DialogClose,DialogContent,+ DialogFooter,+ DialogHeader,+ DialogPanel,DialogTitle,} from "@/components/ui/dialog"-import { DocxViewerPreview } from "@/components/ui/docx-viewer"+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu"import { FileThumbnail } from "@/components/ui/file-thumbnail"-import { PDFViewer } from "@/components/ui/pdf-viewer"+import { Input } from "@/components/ui/input"+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover"import { ScrollArea } from "@/components/ui/scroll-area"import {Select,@@ -36,7 +73,22 @@ import {} from "@/components/ui/select"import { Spinner } from "@/components/ui/spinner"import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"-import { XlsxViewerPreview } from "@/components/ui/xlsx-viewer"++const LazyPDFViewer = React.lazy(() =>+ import("@/components/ui/pdf-viewer").then((mod) => ({+ default: mod.PDFViewer,+ }))+)+const LazyDocxViewerPreview = React.lazy(() =>+ import("@/components/ui/docx-viewer").then((mod) => ({+ default: mod.DocxViewerPreview,+ }))+)+const LazyXlsxViewerPreview = React.lazy(() =>+ import("@/components/ui/xlsx-viewer").then((mod) => ({+ default: mod.XlsxViewerPreview,+ }))+)export type FileSystemView = "icons" | "list" | "columns" | "gallery"@@ -203,6 +255,89 @@ function fileKindLabel(file: FileEntry) {return file.contentType ?? "Document"}+// MIME types inferred from the extension when a file carries no+// `contentType`, so the file-type filter can classify every manifest entry.+const EXTENSION_MIME_TYPES: Record<string, string> = {+ css: "text/css",+ csv: "text/csv",+ doc: "application/msword",+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ gif: "image/gif",+ go: "text/x-go",+ jpeg: "image/jpeg",+ jpg: "image/jpeg",+ js: "text/javascript",+ json: "application/json",+ jsx: "text/jsx",+ md: "text/markdown",+ mdx: "text/mdx",+ pdf: "application/pdf",+ png: "image/png",+ ppt: "application/vnd.ms-powerpoint",+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",+ py: "text/x-python",+ rs: "text/x-rust",+ sh: "application/x-sh",+ sql: "application/sql",+ svg: "image/svg+xml",+ ts: "text/x-typescript",+ tsv: "text/tab-separated-values",+ tsx: "text/x-typescript",+ txt: "text/plain",+ webp: "image/webp",+ xls: "application/vnd.ms-excel",+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ yaml: "text/yaml",+ yml: "text/yaml",+ zip: "application/zip",+}++const FALLBACK_MIME_TYPE = "application/octet-stream"++const MIME_TYPE_LABELS: Record<string, string> = {+ [FALLBACK_MIME_TYPE]: "Binary",+ "application/json": "JSON",+ "application/msword": "Word document (legacy)",+ "application/pdf": "PDF",+ "application/sql": "SQL",+ "application/vnd.ms-excel": "Excel workbook (legacy)",+ "application/vnd.ms-powerpoint": "PowerPoint (legacy)",+ "application/vnd.openxmlformats-officedocument.presentationml.presentation":+ "PowerPoint",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":+ "Excel workbook",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document":+ "Word document",+ "application/x-sh": "Shell script",+ "application/zip": "ZIP archive",+ "image/gif": "GIF image",+ "image/jpeg": "JPEG image",+ "image/png": "PNG image",+ "image/svg+xml": "SVG image",+ "image/webp": "WebP image",+ "text/css": "CSS",+ "text/csv": "CSV",+ "text/javascript": "JavaScript",+ "text/jsx": "JSX",+ "text/markdown": "Markdown",+ "text/mdx": "MDX",+ "text/plain": "Plain text",+ "text/tab-separated-values": "TSV",+ "text/x-go": "Go",+ "text/x-python": "Python",+ "text/x-rust": "Rust",+ "text/x-typescript": "TypeScript",+ "text/yaml": "YAML",+}++function mimeTypeForFile(file: FileEntry) {+ return (+ file.contentType ??+ EXTENSION_MIME_TYPES[fileExtension(file.name)] ??+ FALLBACK_MIME_TYPE+ )+}+export type FileSystemViewerKind = "docx" | "image" | "pdf" | "xlsx"function viewerKindForFile(@@ -230,6 +365,14 @@ const VIEWER_DIALOG_CLASSNAMES: Record<FileSystemViewerKind, string> = {xlsx: "h-[85vh] w-[min(96vw,100rem)] max-w-none",}+function FileSystemViewerLoading() {+ return (+ <div className="grid h-full min-h-48 flex-1 place-items-center bg-background">+ <Spinner className="size-4 text-muted-foreground" />+ </div>+ )+}+function formatByteSize(size: number | undefined) {if (size === undefined) return nullif (size < 1000) return `${size} bytes`@@ -267,6 +410,243 @@ function formatTimestamp(value: string | undefined) {return `${day} at ${time}`}+// Every directory prefix appearing in the given relative file paths.+function directoryPathsOf(paths: readonly string[]) {+ const directoryPaths = new Set<string>()++ for (const relativePath of paths) {+ let slashIndex = relativePath.indexOf("/")++ while (slashIndex !== -1) {+ directoryPaths.add(relativePath.slice(0, slashIndex))+ slashIndex = relativePath.indexOf("/", slashIndex + 1)+ }+ }+ return directoryPaths+}++function compareEntryNames(left: { name: string }, right: { name: string }) {+ return left.name.localeCompare(right.name, undefined, {+ numeric: true,+ sensitivity: "base",+ })+}++export type FileSystemSortKey = "createdAt" | "name" | "size" | "updatedAt"++type FileSystemSortState = {+ direction: "asc" | "desc"+ key: FileSystemSortKey+}++const SORT_OPTIONS: Array<{+ defaultDirection: "asc" | "desc"+ key: FileSystemSortKey+ label: string+ /** Shorter label so the toolbar trigger stays narrow. */+ triggerLabel: string+}> = [+ { defaultDirection: "asc", key: "name", label: "Name", triggerLabel: "Name" },+ {+ defaultDirection: "desc",+ key: "createdAt",+ label: "Date created",+ triggerLabel: "Created",+ },+ {+ defaultDirection: "desc",+ key: "updatedAt",+ label: "Date modified",+ triggerLabel: "Modified",+ },+ {+ defaultDirection: "desc",+ key: "size",+ label: "Size",+ triggerLabel: "Size",+ },+]++const DEFAULT_SORT: FileSystemSortState = { direction: "asc", key: "name" }++function defaultSortDirection(key: FileSystemSortKey) {+ return (+ SORT_OPTIONS.find((option) => option.key === key)?.defaultDirection ?? "asc"+ )+}++function entrySortTimestamp(+ entry: FileSystemEntry,+ key: "createdAt" | "updatedAt"+) {+ const value = entry[key]+ const time = value ? Date.parse(value) : Number.NaN++ return Number.isNaN(time) ? 0 : time+}++// Primary key per the active sort; ties (and missing metadata) fall back to+// the name order so results stay stable. The name tiebreak ignores the+// direction, like Finder.+function compareEntriesBySort(+ left: FileSystemEntry,+ right: FileSystemEntry,+ sort: FileSystemSortState+) {+ let result = 0++ if (sort.key === "name") {+ result = compareEntryNames(left, right)+ } else if (sort.key === "size") {+ // Folders have no byte size; group them at the small end.+ const leftSize = left.kind === "file" ? (left.size ?? 0) : -1+ const rightSize = right.kind === "file" ? (right.size ?? 0) : -1++ result = leftSize - rightSize+ } else {+ result =+ entrySortTimestamp(left, sort.key) - entrySortTimestamp(right, sort.key)+ }++ if (result === 0) return compareEntryNames(left, right)+ return sort.direction === "asc" ? (result < 0 ? -1 : 1) : result < 0 ? 1 : -1+}++export type FileSystemFilterType = "dateCreated" | "dateModified" | "fileType"++type FileSystemDateFilterType = Exclude<FileSystemFilterType, "fileType">++type FileSystemFilterOperator =+ | "after"+ | "before"+ | "in-range"+ | "is"+ | "is-any-of"+ | "is-not"+ | "not-in-range"++type FileSystemFilter = {+ id: string+ operator: FileSystemFilterOperator+ type: FileSystemFilterType+ value: string[]+}++type FileTypeFilterOption = {+ /** Sample file name so the option icon reuses the file-type sprite. */+ iconFileName: string+ label: string+ mime: string+}++const FILTER_TYPE_LABELS: Record<FileSystemFilterType, string> = {+ dateCreated: "Date created",+ dateModified: "Date modified",+ fileType: "File type",+}++const FILTER_OPERATOR_LABELS: Record<FileSystemFilterOperator, string> = {+ after: "after",+ before: "before",+ "in-range": "in range",+ is: "is",+ "is-any-of": "is any of",+ "is-not": "is not",+ "not-in-range": "not in range",+}++// Relative cutoffs for the date filters, mirroring Extend's table filters.+const DATE_FILTER_PRESETS = [+ "1 day ago",+ "3 days ago",+ "1 week ago",+ "1 month ago",+ "3 months ago",+ "6 months ago",+ "1 year ago",+]++function dateFilterPresetCutoff(preset: string) {+ const date = new Date()++ switch (preset) {+ case "1 day ago":+ date.setDate(date.getDate() - 1)+ break+ case "3 days ago":+ date.setDate(date.getDate() - 3)+ break+ case "1 week ago":+ date.setDate(date.getDate() - 7)+ break+ case "1 month ago":+ date.setMonth(date.getMonth() - 1)+ break+ case "3 months ago":+ date.setMonth(date.getMonth() - 3)+ break+ case "6 months ago":+ date.setMonth(date.getMonth() - 6)+ break+ case "1 year ago":+ date.setFullYear(date.getFullYear() - 1)+ break+ default: {+ const parsed = Date.parse(preset)++ if (!Number.isNaN(parsed)) return new Date(parsed)+ }+ }+ return date+}++// Custom ranges store two ISO timestamps instead of a relative preset.+function isCustomDateRangeValue(value: string[]) {+ return (+ value.length === 2 &&+ value.every(+ (entry) =>+ !DATE_FILTER_PRESETS.includes(entry) && !Number.isNaN(Date.parse(entry))+ )+ )+}++function filterOperatorChoices(+ filter: FileSystemFilter+): FileSystemFilterOperator[] {+ if (filter.type === "fileType") {+ return filter.value.length > 1 ? ["is-any-of", "is-not"] : ["is", "is-not"]+ }+ if (isCustomDateRangeValue(filter.value)) return ["in-range", "not-in-range"]+ return ["before", "after"]+}++function fileMatchesFilter(file: FileEntry, filter: FileSystemFilter) {+ if (filter.value.length === 0) return true+ if (filter.type === "fileType") {+ const matches = filter.value.includes(mimeTypeForFile(file))++ return filter.operator === "is-not" ? !matches : matches+ }++ const timestamp =+ filter.type === "dateCreated" ? file.createdAt : file.updatedAt+ const time = timestamp ? Date.parse(timestamp) : Number.NaN++ if (Number.isNaN(time)) return false+ if (filter.operator === "in-range" || filter.operator === "not-in-range") {+ const from = Date.parse(filter.value[0])+ const to = Date.parse(filter.value[1] ?? filter.value[0])+ const isInRange = time >= from && time <= to++ return filter.operator === "not-in-range" ? !isInRange : isInRange+ }++ const cutoff = dateFilterPresetCutoff(filter.value[0]).getTime()++ return filter.operator === "before" ? time <= cutoff : time >= cutoff+}+function buildFileSystemIndex(items: FileSystemItem[]): FileSystemIndex {const folders = new Map<string, FolderEntry>()const files = new Map<string, FileEntry>()@@ -327,12 +707,7 @@ function buildFileSystemIndex(items: FileSystemItem[]): FileSystemIndex {for (const folder of folders.values()) pushChild(folder)for (const file of files.values()) pushChild(file)for (const siblings of children.values()) {- siblings.sort((left, right) =>- left.name.localeCompare(right.name, undefined, {- numeric: true,- sensitivity: "base",- })- )+ siblings.sort(compareEntryNames)}return { children, files, folders }@@ -371,12 +746,146 @@ function escapeXmlAttribute(value: string) {.replaceAll('"', """)}+// The @pierre/trees "complete" set — the full, colored suite with brand and+// framework glyphs — ships as an SVG sprite. The list view tree consumes it+// natively inside its shadow DOM; the icon, column, and gallery views render+// the same sprite from the light DOM so every view falls back to the same+// file-type icon when a file has no thumbnail.+const FILE_ICON_SPRITE_SHEET = getBuiltInSpriteSheet("complete")++const { resolveIcon: resolveFileIcon } = createFileTreeIconResolver({+ colored: true,+ set: "complete",+})++// Per-token light/dark colors mirroring the palette the tree applies inside+// its shadow DOM. Tokens without an entry (font, nextjs, stylelint) stay+// muted-foreground there too.+const FILE_ICON_COLORS: Record<string, [light: string, dark: string]> = {+ astro: ["#a631be", "#d568ea"],+ babel: ["#d5a910", "#ffd452"],+ bash: ["#199f43", "#5ecc71"],+ biome: ["#1a85d4", "#69b1ff"],+ bootstrap: ["#693acf", "#9d6afb"],+ browserslist: ["#d5a910", "#ffd452"],+ bun: ["#594c5b", "#79697b"],+ c: ["#1a85d4", "#69b1ff"],+ claude: ["#d47628", "#ffa359"],+ cpp: ["#1a85d4", "#69b1ff"],+ css: ["#693acf", "#9d6afb"],+ database: ["#a631be", "#d568ea"],+ default: ["#84848a", "#adadb1"],+ docker: ["#1a85d4", "#69b1ff"],+ eslint: ["#693acf", "#9d6afb"],+ git: ["#ff8c5b", "#d5512f"],+ go: ["#1ca1c7", "#68cdf2"],+ graphql: ["#d32a61", "#ff678d"],+ html: ["#d47628", "#ffa359"],+ image: ["#d32a61", "#ff678d"],+ javascript: ["#d5a910", "#ffd452"],+ json: ["#d47628", "#ffa359"],+ markdown: ["#199f43", "#5ecc71"],+ mcp: ["#17a5af", "#64d1db"],+ npm: ["#d52c36", "#ff6762"],+ oxc: ["#1ca1c7", "#68cdf2"],+ postcss: ["#d52c36", "#ff6762"],+ prettier: ["#17a5af", "#64d1db"],+ python: ["#1a85d4", "#69b1ff"],+ react: ["#1ca1c7", "#68cdf2"],+ ruby: ["#d52c36", "#ff6762"],+ rust: ["#d47628", "#ffa359"],+ sass: ["#d32a61", "#ff678d"],+ svelte: ["#d52c36", "#ff6762"],+ svg: ["#d47628", "#ffa359"],+ svgo: ["#199f43", "#5ecc71"],+ swift: ["#d47628", "#ffa359"],+ table: ["#17a5af", "#64d1db"],+ tailwind: ["#1ca1c7", "#68cdf2"],+ terraform: ["#693acf", "#9d6afb"],+ text: ["#84848a", "#adadb1"],+ typescript: ["#1a85d4", "#69b1ff"],+ vite: ["#a631be", "#d568ea"],+ vscode: ["#1a85d4", "#69b1ff"],+ vue: ["#199f43", "#5ecc71"],+ wasm: ["#693acf", "#9d6afb"],+ webpack: ["#1a85d4", "#69b1ff"],+ yml: ["#d52c36", "#ff6762"],+ zig: ["#d47628", "#ffa359"],+ zip: ["#d47628", "#ffa359"],+}++function fileIconColorVariables(mode: 0 | 1) {+ return Object.entries(FILE_ICON_COLORS)+ .map(([token, colors]) => `--fs-file-icon-${token}: ${colors[mode]};`)+ .join(" ")+}++// The variables live on :root rather than the component root because the+// filter menus and dialogs portal outside it; the --fs-file-icon-*+// namespace keeps them collision-free. Thumbnail tiles keep a light+// (paper) surface in dark mode, so icons inside them revert to the light+// palette ([data-file-system-on-light]); selected rows sit on the primary+// surface — the opposite of the mode's background — so icons there swap to+// the opposite palette ([data-file-system-on-primary] in the light DOM,+// --fs-selected-color-scheme for the tree's light-dark() colors inside its+// shadow DOM).+const FILE_ICON_COLOR_CSS = `+:root { ${fileIconColorVariables(0)} --fs-selected-color-scheme: dark; }+.dark { ${fileIconColorVariables(1)} --fs-selected-color-scheme: light; }+.dark [data-file-system-on-light] { ${fileIconColorVariables(0)} }+[data-file-system-on-primary] { ${fileIconColorVariables(1)} }+.dark [data-file-system-on-primary] { ${fileIconColorVariables(0)} }+`++function FileSystemIconSpriteSheet() {+ return (+ <>+ <span+ aria-hidden="true"+ className="hidden"+ dangerouslySetInnerHTML={{ __html: FILE_ICON_SPRITE_SHEET }}+ />+ <style>{FILE_ICON_COLOR_CSS}</style>+ </>+ )+}++function FileTypeIcon({+ fileName,+ className,+}: {+ fileName: string+ className?: string+}) {+ const icon = resolveFileIcon("file-tree-icon-file", fileName)++ return (+ <svg+ aria-hidden="true"+ viewBox={icon.viewBox ?? "0 0 16 16"}+ className={cn("shrink-0 text-muted-foreground", className)}+ style={+ icon.token+ ? {+ color: `var(--fs-file-icon-${icon.token}, var(--color-muted-foreground))`,+ }+ : undefined+ }+ >+ <use href={`#${icon.name}`} />+ </svg>+ )+}+function FileGenericPreview({ file }: { file: FileEntry }) {const extension = fileExtension(file.name)return (- <div className="flex size-full flex-col items-center justify-center gap-1.5 bg-white text-neutral-400 dark:bg-neutral-100">- <HugeiconsIcon icon={File01Icon} className="size-1/3 min-h-4 min-w-4" />+ <div+ data-file-system-on-light=""+ className="flex size-full flex-col items-center justify-center gap-1.5 bg-white text-neutral-400 dark:bg-neutral-100"+ >+ <FileTypeIcon fileName={file.name} className="size-1/3 min-h-4 min-w-4" />{extension ? (<span className="text-[min(0.625rem,18cqw)] font-semibold tracking-wide uppercase">{extension}@@ -391,14 +900,128 @@ function filePreviewUrls(file: FileSystemFileItem) {return file.previewImageUrl ? [file.previewImageUrl] : []}-// djb2 — cheap stable hash for remount keys derived from path lists.-function hashString(value: string) {- let hash = 5381+// Mirrors @pierre/trees' query normalization so the toolbar search filters+// the icon, column, and gallery views exactly like the list view tree:+// trimmed, backslashes to slashes, lowercased, substring match on the path.+function normalizeSearchQuery(value: string) {+ const trimmed = value.trim()++ if (!trimmed) return ""+ return trimmed.replaceAll("\\", "/").toLowerCase()+}++// Windowed rendering, the approach @pierre/trees uses for the list view:+// with a fixed item stride only the items intersecting the viewport — plus+// `overscan` on each side — are mounted, so views stay flat-cost at+// thousands of entries. The window keeps a one-item margin before+// recomputing (scrolling doesn't re-render per item) and that margin also+// guarantees single-step keyboard moves land on a mounted neighbor.+function useVirtualWindow({+ count,+ horizontal = false,+ itemStride,+ leadingPx = 0,+ overscan = 8,+ viewportRef,+}: {+ count: number+ horizontal?: boolean+ itemStride: number+ leadingPx?: number+ overscan?: number+ viewportRef: React.RefObject<HTMLDivElement | null>+}) {+ const [window_, setWindow] = React.useState(() => ({+ end: Math.min(count, overscan * 2),+ start: 0,+ }))++ React.useLayoutEffect(() => {+ const viewport = viewportRef.current++ if (!viewport || itemStride <= 0) return++ const update = () => {+ const scrollStart =+ (horizontal ? viewport.scrollLeft : viewport.scrollTop) - leadingPx+ const viewportSize = horizontal+ ? viewport.clientWidth+ : viewport.clientHeight+ const firstVisible = Math.max(0, Math.floor(scrollStart / itemStride))+ const lastVisible = Math.min(+ count,+ Math.ceil((scrollStart + viewportSize) / itemStride)+ )++ setWindow((previous) => {+ if (+ previous.end <= count &&+ previous.start <= Math.max(0, firstVisible - 1) &&+ previous.end >= Math.min(count, lastVisible + 1)+ ) {+ return previous+ }+ return {+ end: Math.min(count, lastVisible + overscan),+ start: Math.max(0, firstVisible - overscan),+ }+ })+ }++ update()+ viewport.addEventListener("scroll", update, { passive: true })++ const observer =+ typeof ResizeObserver === "undefined" ? null : new ResizeObserver(update)++ observer?.observe(viewport)+ return () => {+ viewport.removeEventListener("scroll", update)+ observer?.disconnect()+ }+ }, [count, horizontal, itemStride, leadingPx, overscan, viewportRef])++ return window_+}++// Scrolls the item at `index` into the viewport when it sits outside it —+// virtualized views need this because off-window items have no DOM node to+// call scrollIntoView on.+function scrollIndexIntoView({+ horizontal = false,+ index,+ itemSize,+ itemStride,+ leadingPx = 0,+ viewport,+}: {+ horizontal?: boolean+ index: number+ itemSize: number+ itemStride: number+ leadingPx?: number+ viewport: HTMLDivElement | null+}) {+ if (!viewport || index < 0) return++ const start = leadingPx + index * itemStride+ const end = start + itemSize+ const scrollStart = horizontal ? viewport.scrollLeft : viewport.scrollTop+ const viewportSize = horizontal ? viewport.clientWidth : viewport.clientHeight++ let nextScrollStart: number | null = null- for (let index = 0; index < value.length; index += 1) {- hash = ((hash << 5) + hash + value.charCodeAt(index)) | 0+ if (start < scrollStart) {+ nextScrollStart = start+ } else if (end > scrollStart + viewportSize) {+ nextScrollStart = end - viewportSize+ }+ if (nextScrollStart === null) return+ if (horizontal) {+ viewport.scrollLeft = nextScrollStart+ } else {+ viewport.scrollTop = nextScrollStart}- return hash}function FileVisual({@@ -594,17 +1217,270 @@ export function FileSystem({)}, [index, selectedPath])+ const [searchInput, setSearchInput] = React.useState("")+ const searchInputRef = React.useRef<HTMLInputElement | null>(null)+ const [isSearchExpanded, setIsSearchExpanded] = React.useState(false)+ const searchQuery = normalizeSearchQuery(searchInput)+ const isSearching = searchQuery.length > 0++ const [sort, setSort] = React.useState(DEFAULT_SORT)+ const [filters, setFilters] = React.useState<FileSystemFilter[]>([])+ const hasActiveFilters = filters.length > 0++ // Files must pass every active filter; folders stay visible through+ // matching descendants, so the predicate only ever sees files.+ const fileFilter = React.useMemo(() => {+ if (filters.length === 0) return null+ return (file: FileEntry) =>+ filters.every((filter) => fileMatchesFilter(file, filter))+ }, [filters])++ // Paths that stay visible while searching or filtering: every file whose+ // currentPath-relative path contains the query — the list view tree's+ // hide-non-matches semantics — and that passes the filters, plus the+ // ancestor folders leading to it. Folder names participate in search+ // matches only when no filters are active; with filters, a folder is only+ // as visible as the files inside it.+ const visiblePaths = React.useMemo(() => {+ if (!isSearching && !fileFilter) return null++ const visible = new Set<string>()+ const markVisible = (path: string) => {+ while (path && path !== currentPath && !visible.has(path)) {+ visible.add(path)+ path = pathParent(path)+ }+ }+ const matchesQuery = (path: string) =>+ !isSearching ||+ path.slice(currentPath.length).toLowerCase().includes(searchQuery)++ for (const [path, file] of index.files) {+ if (path === currentPath) continue+ if (currentPath && !path.startsWith(currentPath)) continue+ if (!matchesQuery(path)) continue+ if (fileFilter && !fileFilter(file)) continue+ markVisible(path)+ }+ if (!fileFilter) {+ for (const path of index.folders.keys()) {+ if (path === currentPath) continue+ if (currentPath && !path.startsWith(currentPath)) continue+ if (matchesQuery(path)) markVisible(path)+ }+ }+ return visible+ }, [currentPath, fileFilter, index, isSearching, searchQuery])++ const visibleIndex = React.useMemo(() => {+ if (!visiblePaths) return index++ const children = new Map<string, FileSystemEntry[]>()++ for (const [parentPath, parentChildren] of index.children) {+ const visibleChildren = parentChildren.filter((entry) =>+ visiblePaths.has(entry.path)+ )++ if (visibleChildren.length) children.set(parentPath, visibleChildren)+ }+ return { ...index, children }+ }, [index, visiblePaths])++ // Children re-sorted per the active sort; the default (name ascending)+ // reuses the index's pre-sorted arrays untouched.+ const sortedIndex = React.useMemo(() => {+ if (+ sort.key === DEFAULT_SORT.key &&+ sort.direction === DEFAULT_SORT.direction+ ) {+ return visibleIndex+ }++ const children = new Map<string, FileSystemEntry[]>()++ for (const [parentPath, parentChildren] of visibleIndex.children) {+ children.set(+ parentPath,+ [...parentChildren].sort((left, right) =>+ compareEntriesBySort(left, right, sort)+ )+ )+ }+ return { ...visibleIndex, children }+ }, [sort, visibleIndex])++ // The ref mirrors the state so re-selecting the same entry (e.g. the+ // pointerdown + click pair the columns view emits per press) stays a+ // no-op without widening the callback's dependencies.+ const selectedPathRef = React.useRef<string | null>(null)const selectEntry = React.useCallback((entry: FileSystemEntry | null) => {- setSelectedPath(entry?.path ?? null)+ const path = entry?.path ?? null++ if (selectedPathRef.current === path) return+ selectedPathRef.current = path+ setSelectedPath(path)onSelectionChange?.(entry)},[onSelectionChange])- // Below 480px the tabs view switcher no longer fits in the toolbar and- // collapses into a select; below 360px the select label and the folder- // name are dropped too, leaving icons only.+ // A query or filter change can hide the selected entry out from under the+ // views.+ React.useEffect(() => {+ if (!visiblePaths || !selectedPath) return+ if (!visiblePaths.has(selectedPath)) selectEntry(null)+ }, [selectEntry, selectedPath, visiblePaths])++ const applySortKey = React.useCallback((key: FileSystemSortKey) => {+ setSort((previous) =>+ previous.key === key+ ? previous+ : { direction: defaultSortDirection(key), key }+ )+ }, [])++ // Column headers toggle the direction when the column is already active,+ // like Finder.+ const toggleSortColumn = React.useCallback((key: FileSystemSortKey) => {+ setSort((previous) =>+ previous.key === key+ ? { direction: previous.direction === "asc" ? "desc" : "asc", key }+ : { direction: defaultSortDirection(key), key }+ )+ }, [])++ // Distinct MIME types across the loaded manifest, labeled for the filter+ // menu; the first file seen per type lends its name to the option icon.+ const fileTypeOptions = React.useMemo(() => {+ const byMime = new Map<string, FileTypeFilterOption>()++ for (const file of index.files.values()) {+ const mime = mimeTypeForFile(file)++ if (!byMime.has(mime)) {+ byMime.set(mime, {+ iconFileName: file.name,+ label: MIME_TYPE_LABELS[mime] ?? mime,+ mime,+ })+ }+ }+ return [...byMime.values()].sort((left, right) =>+ left.label.localeCompare(right.label)+ )+ }, [index])++ const filterIdRef = React.useRef(0)+ const [dateRangeDialog, setDateRangeDialog] = React.useState<{+ initialRange?: { from: Date; to: Date }+ type: FileSystemDateFilterType+ } | null>(null)++ const toggleFileTypeFilterValue = React.useCallback(+ (mime: string, checked: boolean) => {+ const id = `filter-${++filterIdRef.current}`++ setFilters((previous) => {+ const existing = previous.find((filter) => filter.type === "fileType")++ if (!existing) {+ if (!checked) return previous+ return [+ ...previous,+ {+ id,+ operator: "is" as const,+ type: "fileType" as const,+ value: [mime],+ },+ ]+ }++ const value = checked+ ? [...new Set([...existing.value, mime])]+ : existing.value.filter((entry) => entry !== mime)++ if (value.length === 0) {+ return previous.filter((filter) => filter !== existing)+ }++ // "is" and "is any of" track the value count; "is not" is unaffected.+ const operator =+ existing.operator === "is" || existing.operator === "is-any-of"+ ? value.length > 1+ ? ("is-any-of" as const)+ : ("is" as const)+ : existing.operator++ return previous.map((filter) =>+ filter === existing ? { ...filter, operator, value } : filter+ )+ })+ },+ []+ )++ const setDatePresetFilter = React.useCallback(+ (type: FileSystemDateFilterType, preset: string) => {+ const id = `filter-${++filterIdRef.current}`++ setFilters((previous) => [+ ...previous.filter((filter) => filter.type !== type),+ { id, operator: "after", type, value: [preset] },+ ])+ },+ []+ )++ // Editing an existing custom range seeds the dialog with its bounds.+ const openDateRangeDialog = React.useCallback(+ (type: FileSystemDateFilterType) => {+ const existing = filters.find((filter) => filter.type === type)++ setDateRangeDialog({+ initialRange:+ existing && isCustomDateRangeValue(existing.value)+ ? {+ from: new Date(existing.value[0]),+ to: new Date(existing.value[1]),+ }+ : undefined,+ type,+ })+ },+ [filters]+ )++ const applyCustomDateRange = React.useCallback(+ (type: FileSystemDateFilterType, from: Date, to: Date) => {+ const id = `filter-${++filterIdRef.current}`++ setFilters((previous) => {+ const existing = previous.find((filter) => filter.type === type)++ return [+ ...previous.filter((filter) => filter.type !== type),+ {+ id,+ operator:+ existing?.operator === "not-in-range"+ ? ("not-in-range" as const)+ : ("in-range" as const),+ type,+ value: [from.toISOString(), to.toISOString()],+ },+ ]+ })+ },+ []+ )++ // Below 560px the tabs view switcher no longer fits in the toolbar and+ // collapses into a select while the search input collapses into a popover;+ // below 360px the select labels and the folder name are dropped too,+ // leaving icons only.const rootRef = React.useRef<HTMLDivElement | null>(null)const [headerLayout, setHeaderLayout] = React.useState<"full" | "compact" | "minimal"@@ -615,16 +1491,20 @@ export function FileSystem({if (!root || typeof ResizeObserver === "undefined") return- const observer = new ResizeObserver((observerEntries) => {- const width = observerEntries[0]?.contentRect.width-+ const applyWidth = (width: number | undefined) => {if (width === undefined) returnsetHeaderLayout(- width < 360 ? "minimal" : width < 480 ? "compact" : "full"+ width < 360 ? "minimal" : width < 560 ? "compact" : "full")- })+ }+ const observer = new ResizeObserver((observerEntries) =>+ applyWidth(observerEntries[0]?.contentRect.width)+ )+ // Measure synchronously so the first painted layout is already correct;+ // the observer then tracks resizes.+ applyWidth(root.clientWidth)observer.observe(root)return () => observer.disconnect()}, [])@@ -684,6 +1564,8 @@ export function FileSystem({return { index: stack.length - 1, stack }})+ // Navigation exits search, like Finder.+ setSearchInput("")selectEntry(null)ensureChildren(path)},@@ -771,6 +1653,7 @@ export function FileSystem({...previous,index: Math.max(0, previous.index - 1),}))+ setSearchInput("")selectEntry(null)}, [selectEntry])@@ -779,26 +1662,37 @@ export function FileSystem({...previous,index: Math.min(previous.stack.length - 1, previous.index + 1),}))+ setSearchInput("")selectEntry(null)}, [selectEntry])- const currentEntries = index.children.get(currentPath) ?? []+ const currentEntries = sortedIndex.children.get(currentPath) ?? []const currentFolderName =currentPath === "" ? title : pathName(currentPath) || titleconst isLoadingCurrentFolder = loadingFolders.has(currentPath)+ // The list view tree saves its expanded folders here when it unmounts+ // (view switches, navigation) so returning to the list view — or to a+ // previously visited folder — restores the same disclosure state.+ const treeExpansionRef = React.useRef(new Map<string, readonly string[]>())+const viewProps: FileSystemViewProps = {currentPath,entries: currentEntries,+ fileFilter,getFileUrl,- index,+ index: sortedIndex,loadPreviewImageUrl,loadingFolders,onOpen: openEntry,onSelect: selectAndPrefetchEntry,+ onSortColumnClick: toggleSortColumn,renderFilePreview,+ searchQuery,selectedEntry,selectedPath,+ sort,+ treeExpansionRef,}const openedFileName = openedFile@@ -818,12 +1712,22 @@ export function FileSystem({<divref={rootRef}tabIndex={-1}+ data-slot="file-system"+ onKeyDown={(event) => {+ // ⌘F focuses the toolbar search while focus is inside the component.+ if ((event.metaKey || event.ctrlKey) && event.key === "f") {+ event.preventDefault()+ setIsSearchExpanded(true)+ searchInputRef.current?.focus()+ }+ }}className={cn("flex h-[480px] min-h-0 flex-col overflow-hidden rounded-xl border bg-background text-foreground outline-none",className)}>- <div className="grid h-12 shrink-0 grid-cols-[1fr_auto_1fr] items-center gap-2 border-b bg-muted/40 px-2">+ <FileSystemIconSpriteSheet />+ <div className="relative grid h-12 shrink-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-2 border-b bg-muted/40 px-2"><div className="flex min-w-0 items-center gap-0.5"><buttontype="button"@@ -859,17 +1763,16 @@ export function FileSystem({<SelectTriggersize="sm"aria-label="View"- className={cn(headerLayout !== "minimal" && "min-w-32")}+ // Icon-only like the sort select: sheds the base min-width to+ // hug icon + chevron at the filter button's 28px height.+ className="h-7 min-h-7 w-auto min-w-0 [&_svg]:size-4"><SelectValue>{activeViewOption ? (- <span className="flex items-center gap-2">- <HugeiconsIcon- icon={activeViewOption.icon}- className="size-4"- />- {headerLayout !== "minimal" ? activeViewOption.label : null}- </span>+ <HugeiconsIcon+ icon={activeViewOption.icon}+ className="size-4"+ />) : null}</SelectValue></SelectTrigger>@@ -905,13 +1808,101 @@ export function FileSystem({</TabsList></Tabs>)}- <div />+ <div className="flex min-w-0 items-center justify-end gap-1">+ <FileSystemSortSelect+ layout={headerLayout}+ onKeyChange={applySortKey}+ sort={sort}+ />+ <FileSystemFilterMenu+ fileTypeOptions={fileTypeOptions}+ filters={filters}+ onOpenCustomRange={openDateRangeDialog}+ onSelectDatePreset={setDatePresetFilter}+ onToggleFileType={toggleFileTypeFilterValue}+ />+ <FileSystemSearchField+ inputRef={searchInputRef}+ isExpanded={isSearchExpanded}+ layout={headerLayout}+ onExpandedChange={setIsSearchExpanded}+ onValueChange={setSearchInput}+ value={searchInput}+ />+ </div></div>+ {hasActiveFilters ? (+ <div className="flex shrink-0 flex-wrap items-center gap-1 border-b bg-muted/20 px-2 py-1.5 text-xs text-muted-foreground">+ {filters.map((filter) => {+ const dateFilterType =+ filter.type === "fileType" ? null : filter.type++ return (+ <FileSystemFilterPill+ key={filter.id}+ fileTypeOptions={fileTypeOptions}+ filter={filter}+ onOpenCustomRange={+ dateFilterType+ ? () => openDateRangeDialog(dateFilterType)+ : undefined+ }+ onOperatorChange={(operator) =>+ setFilters((previous) =>+ previous.map((entry) =>+ entry.id === filter.id ? { ...entry, operator } : entry+ )+ )+ }+ onRemove={() =>+ setFilters((previous) =>+ previous.filter((entry) => entry.id !== filter.id)+ )+ }+ onSelectDatePreset={(preset) =>+ setFilters((previous) =>+ previous.map((entry) =>+ entry.id === filter.id+ ? {+ ...entry,+ operator:+ entry.operator === "before" ||+ entry.operator === "after"+ ? entry.operator+ : "after",+ value: [preset],+ }+ : entry+ )+ )+ }+ onToggleFileType={toggleFileTypeFilterValue}+ />+ )+ })}+ <button+ type="button"+ onClick={() => setFilters([])}+ className="rounded-md px-1.5 py-0.5 transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"+ >+ Clear+ </button>+ </div>+ ) : null}<div className="relative min-h-0 flex-1">{isLoadingCurrentFolder && currentEntries.length === 0 ? (<FileSystemEmptyState label="Loading…" isLoading />- ) : currentEntries.length === 0 && view !== "columns" ? (- <FileSystemEmptyState label="This folder is empty" />+ ) : currentEntries.length === 0 &&+ (view !== "columns" || isSearching || hasActiveFilters) ? (+ <FileSystemEmptyState+ label={+ isSearching+ ? `No results for “${searchInput.trim()}”`+ : hasActiveFilters+ ? "No items match the active filters"+ : "This folder is empty"+ }+ />) : view === "icons" ? (<FileSystemIconsView {...viewProps} />) : view === "list" ? (@@ -928,7 +1919,13 @@ export function FileSystem({><span>{currentEntries.length}{" "}- {currentEntries.length === 1 ? "item" : "items"}+ {isSearching+ ? currentEntries.length === 1+ ? "result"+ : "results"+ : currentEntries.length === 1+ ? "item"+ : "items"}</span>{selectedEntry ? <span>· “{selectedEntry.name}” selected</span> : null}</div>@@ -948,31 +1945,37 @@ export function FileSystem({><DialogTitle className="sr-only">{openedFileName}</DialogTitle>{openedFile.kind === "pdf" ? (- <PDFViewer- file={openedFile.url}- className="h-full min-h-0 flex-1 overflow-hidden rounded-2xl"- downloadFileName={openedFileName}- showUpload={false}- toolbarActions={viewerCloseToolbarAction}- />+ <React.Suspense fallback={<FileSystemViewerLoading />}>+ <LazyPDFViewer+ file={openedFile.url}+ className="h-full min-h-0 flex-1 overflow-hidden rounded-2xl"+ downloadFileName={openedFileName}+ showUpload={false}+ toolbarActions={viewerCloseToolbarAction}+ />+ </React.Suspense>) : openedFile.kind === "docx" ? (- <DocxViewerPreview- src={openedFile.url}- fileName={openedFileName}- className="h-full min-h-0 flex-1"- rounded- showUpload={false}- toolbarActions={viewerCloseToolbarAction}- />+ <React.Suspense fallback={<FileSystemViewerLoading />}>+ <LazyDocxViewerPreview+ src={openedFile.url}+ fileName={openedFileName}+ className="h-full min-h-0 flex-1"+ rounded+ showUpload={false}+ toolbarActions={viewerCloseToolbarAction}+ />+ </React.Suspense>) : openedFile.kind === "xlsx" ? (- <XlsxViewerPreview- src={openedFile.url}- fileName={openedFileName}- className="h-full min-h-0 flex-1"- rounded- showUpload={false}- toolbarActions={viewerCloseToolbarAction}- />+ <React.Suspense fallback={<FileSystemViewerLoading />}>+ <LazyXlsxViewerPreview+ src={openedFile.url}+ fileName={openedFileName}+ className="h-full min-h-0 flex-1"+ rounded+ showUpload={false}+ toolbarActions={viewerCloseToolbarAction}+ />+ </React.Suspense>) : (<imgsrc={openedFile.url}@@ -983,25 +1986,841 @@ export function FileSystem({</DialogContent>) : null}</Dialog>+ {dateRangeDialog ? (+ <FileSystemDateRangeDialog+ initialRange={dateRangeDialog.initialRange}+ onApply={(from, to) => {+ applyCustomDateRange(dateRangeDialog.type, from, to)+ setDateRangeDialog(null)+ }}+ onClose={() => setDateRangeDialog(null)}+ />+ ) : null}</div>)}-type FileSystemViewProps = {- currentPath: string- entries: FileSystemEntry[]- getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>- index: FileSystemIndex- loadPreviewImageUrl?: (- file: FileSystemFileItem,- pageIndex: number- ) => Promise<string | null>- loadingFolders: Set<string>- onOpen: (entry: FileSystemEntry) => void+// Shared style for the ghost icon buttons in the toolbar.+const TOOLBAR_ICON_BUTTON_CLASSNAME =+ "flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"++// macOS Finder-style toolbar search. At the full layout it sits inline in+// the header's right column; at compact widths it collapses into a ghost+// icon button that opens the input in a popover (a dot marks the button+// while a query keeps filtering the views).+function FileSystemSearchField({+ inputRef,+ isExpanded,+ layout,+ onExpandedChange,+ onValueChange,+ value,+}: {+ inputRef: React.RefObject<HTMLInputElement | null>+ isExpanded: boolean+ layout: "full" | "compact" | "minimal"+ onExpandedChange: (isExpanded: boolean) => void+ onValueChange: (value: string) => void+ value: string+}) {+ const isInline = layout === "full"++ React.useEffect(() => {+ if (!isInline && isExpanded) inputRef.current?.focus()+ }, [inputRef, isExpanded, isInline])++ const input = (+ <div+ className={cn(+ "relative flex h-7 min-w-0 flex-1 items-center rounded-lg border border-input bg-popover text-sm text-foreground shadow-xs/5 transition-shadow outline-none not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-focus-within:before:shadow-[0_1px_--theme(--color-black/4%)] focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-1 focus-within:ring-offset-background dark:bg-input/32 dark:not-focus-within:before:shadow-[0_-1px_--theme(--color-white/6%)]",+ isInline && "max-w-44"+ )}+ >+ <HugeiconsIcon+ icon={Search01Icon}+ className="pointer-events-none absolute left-2 size-3.5 text-muted-foreground"+ />+ <input+ ref={inputRef}+ type="text"+ role="searchbox"+ aria-label="Search files"+ placeholder="Search"+ value={value}+ onChange={(event) => onValueChange(event.target.value)}+ onKeyDown={(event) => {+ if (event.key !== "Escape") return+ event.preventDefault()+ event.stopPropagation()+ if (value) {+ onValueChange("")+ } else {+ onExpandedChange(false)+ event.currentTarget.blur()+ }+ }}+ className="h-full w-full min-w-0 rounded-[inherit] bg-transparent pr-6 pl-7 outline-none placeholder:text-muted-foreground"+ />+ {value ? (+ <button+ type="button"+ aria-label="Clear search"+ onClick={() => {+ onValueChange("")+ inputRef.current?.focus()+ }}+ className="absolute right-1 flex size-5 items-center justify-center rounded-sm text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"+ >+ <HugeiconsIcon icon={Cancel01Icon} className="size-3" />+ </button>+ ) : null}+ </div>+ )++ if (isInline) {+ // A fixed basis (not flex-1) keeps the whole toolbar cluster packed+ // against the header's right edge; the input shrinks first when the+ // header tightens.+ return <div className="flex w-44 min-w-9 items-center">{input}</div>+ }++ return (+ <Popover open={isExpanded} onOpenChange={onExpandedChange}>+ <PopoverTrigger+ render={+ <button+ type="button"+ aria-label="Search"+ title="Search"+ className={cn(TOOLBAR_ICON_BUTTON_CLASSNAME, "relative")}+ />+ }+ >+ <HugeiconsIcon icon={Search01Icon} className="size-4" />+ {value ? (+ <span className="absolute top-1 right-1 size-1.5 rounded-full bg-primary" />+ ) : null}+ </PopoverTrigger>+ <PopoverContent align="end" sideOffset={6} className="w-64 p-1">+ {input}+ </PopoverContent>+ </Popover>+ )+}++// Toolbar "sort by" select. The full layout shows the active key's label; at+// compact widths the trigger collapses to the sort glyph + chevron.+function FileSystemSortSelect({+ layout,+ onKeyChange,+ sort,+}: {+ layout: "full" | "compact" | "minimal"+ onKeyChange: (key: FileSystemSortKey) => void+ sort: FileSystemSortState+}) {+ const activeOption = SORT_OPTIONS.find((option) => option.key === sort.key)++ return (+ <Select+ value={sort.key}+ onValueChange={(value) => onKeyChange(value as FileSystemSortKey)}+ >+ <SelectTrigger+ size="sm"+ aria-label="Sort by"+ title="Sort by"+ className="h-7 min-h-7 w-auto min-w-0 shrink-0 [&_svg]:size-4"+ >+ <SelectValue>+ <span className="flex items-center gap-1.5">+ <HugeiconsIcon icon={ArrowUpDownIcon} className="size-4" />+ {layout === "full" ? activeOption?.triggerLabel : null}+ </span>+ </SelectValue>+ </SelectTrigger>+ <SelectContent align="end" alignItemWithTrigger={false}>+ {SORT_OPTIONS.map((option) => (+ <SelectItem key={option.key} value={option.key}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )+}++// Searchable file-type list (cmdk) rendered inside a menu popup, so the+// long MIME list can be filtered by typing. Selection toggles stay open for+// multi-select; ArrowUp/Down and Enter come from cmdk's combobox semantics.+function FileSystemFileTypeCommand({+ checkedMimes,+ onToggle,+ options,+}: {+ checkedMimes: string[]+ onToggle: (mime: string, checked: boolean) => void+ options: FileTypeFilterOption[]+}) {+ const inputRef = React.useRef<HTMLInputElement | null>(null)++ // The menu focuses its popup when it opens; pull focus into the search+ // field so typing filters immediately.+ React.useEffect(() => {+ const frame = requestAnimationFrame(() => inputRef.current?.focus())++ return () => cancelAnimationFrame(frame)+ }, [])++ return (+ <Command+ // -m-1 spans the menu viewport's built-in padding so the search+ // field's bottom border runs edge to edge.+ className="-m-1 w-[calc(100%+--spacing(2))] bg-transparent"+ // cmdk owns the keyboard while focus is in the list; only Escape+ // (close the menu) and Tab continue outward.+ onKeyDown={(event) => {+ if (event.key !== "Escape" && event.key !== "Tab") {+ event.stopPropagation()+ }+ }}+ >+ <CommandInput+ ref={inputRef}+ placeholder="Search file types…"+ className="h-9"+ />+ <CommandList className="max-h-none">+ <CommandEmpty>No file types found.</CommandEmpty>+ <ScrollArea orientation="vertical" className="h-auto max-h-64">+ <CommandGroup>+ {options.map((option) => {+ const isChecked = checkedMimes.includes(option.mime)++ return (+ <CommandItem+ key={option.mime}+ value={option.label}+ keywords={[option.mime]}+ onSelect={() => onToggle(option.mime, !isChecked)}+ >+ <HugeiconsIcon+ icon={Tick02Icon}+ className={cn(+ "size-4 text-foreground",+ !isChecked && "opacity-0"+ )}+ />+ <FileTypeIcon+ fileName={option.iconFileName}+ className="size-4"+ />+ {option.label}+ </CommandItem>+ )+ })}+ </CommandGroup>+ </ScrollArea>+ </CommandList>+ </Command>+ )+}++// Toolbar filter menu: file types as a searchable checklist, dates as+// single-select presets plus a custom range, mirroring Extend's table+// filters.+function FileSystemFilterMenu({+ fileTypeOptions,+ filters,+ onOpenCustomRange,+ onSelectDatePreset,+ onToggleFileType,+}: {+ fileTypeOptions: FileTypeFilterOption[]+ filters: FileSystemFilter[]+ onOpenCustomRange: (type: FileSystemDateFilterType) => void+ onSelectDatePreset: (type: FileSystemDateFilterType, preset: string) => void+ onToggleFileType: (mime: string, checked: boolean) => void+}) {+ const fileTypeFilter = filters.find((filter) => filter.type === "fileType")++ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ type="button"+ variant="outline"+ size="icon-sm"+ aria-label="Filter"+ title="Filter"+ className="relative size-7 sm:size-7"+ />+ }+ >+ <HugeiconsIcon icon={FilterIcon} className="size-4" />+ {filters.length > 0 ? (+ <span className="absolute top-1 right-1 size-1.5 rounded-full bg-primary" />+ ) : null}+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="min-w-44">+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <HugeiconsIcon+ icon={File01Icon}+ className="size-4 text-muted-foreground"+ />+ File type+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="w-60">+ <FileSystemFileTypeCommand+ checkedMimes={fileTypeFilter?.value ?? []}+ onToggle={onToggleFileType}+ options={fileTypeOptions}+ />+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ {(["dateModified", "dateCreated"] as const).map((type) => (+ <DropdownMenuSub key={type}>+ <DropdownMenuSubTrigger>+ <HugeiconsIcon+ icon={Calendar03Icon}+ className="size-4 text-muted-foreground"+ />+ {FILTER_TYPE_LABELS[type]}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ <ScrollArea orientation="vertical" className="h-auto max-h-72">+ {DATE_FILTER_PRESETS.map((preset) => (+ <DropdownMenuItem+ key={preset}+ onClick={() => onSelectDatePreset(type, preset)}+ >+ {preset}+ </DropdownMenuItem>+ ))}+ <DropdownMenuItem onClick={() => onOpenCustomRange(type)}>+ Custom date range…+ </DropdownMenuItem>+ </ScrollArea>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ )+}++const FILTER_PILL_SEGMENT_CLASSNAME =+ "flex h-5 items-center gap-1 border border-l-0 bg-background px-1.5 whitespace-nowrap text-foreground"++const FILTER_PILL_BUTTON_CLASSNAME = cn(+ FILTER_PILL_SEGMENT_CLASSNAME,+ "transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"+)++// One applied filter, rendered as a segmented pill in the status bar:+// type · operator · value · remove, each segment interactive like Extend's+// table filter pills.+function FileSystemFilterPill({+ fileTypeOptions,+ filter,+ onOpenCustomRange,+ onOperatorChange,+ onRemove,+ onSelectDatePreset,+ onToggleFileType,+}: {+ fileTypeOptions: FileTypeFilterOption[]+ filter: FileSystemFilter+ onOpenCustomRange?: () => void+ onOperatorChange: (operator: FileSystemFilterOperator) => void+ onRemove: () => void+ onSelectDatePreset: (preset: string) => void+ onToggleFileType: (mime: string, checked: boolean) => void+}) {+ const isCustomRange =+ filter.type !== "fileType" && isCustomDateRangeValue(filter.value)+ const selectedTypeLabels =+ filter.type === "fileType"+ ? filter.value.map(+ (mime) =>+ fileTypeOptions.find((option) => option.mime === mime)?.label ??+ mime+ )+ : []++ return (+ <div className="flex items-center text-xs">+ <span+ className={cn(+ FILTER_PILL_SEGMENT_CLASSNAME,+ "rounded-l-md border-l text-primary"+ )}+ >+ <HugeiconsIcon+ icon={filter.type === "fileType" ? File01Icon : Calendar03Icon}+ className="size-3"+ />+ {FILTER_TYPE_LABELS[filter.type]}+ </span>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ type="button"+ className={cn(FILTER_PILL_BUTTON_CLASSNAME, "text-primary")}+ />+ }+ >+ {FILTER_OPERATOR_LABELS[filter.operator]}+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="min-w-28">+ {filterOperatorChoices(filter).map((operator) => (+ <DropdownMenuItem+ key={operator}+ onClick={() => onOperatorChange(operator)}+ >+ {FILTER_OPERATOR_LABELS[operator]}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ {filter.type === "fileType" ? (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ type="button"+ title={selectedTypeLabels.join(", ")}+ className={FILTER_PILL_BUTTON_CLASSNAME}+ />+ }+ >+ {filter.value.length === 1+ ? selectedTypeLabels[0]+ : `${filter.value.length} selected`}+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-60">+ <FileSystemFileTypeCommand+ checkedMimes={filter.value}+ onToggle={onToggleFileType}+ options={fileTypeOptions}+ />+ </DropdownMenuContent>+ </DropdownMenu>+ ) : isCustomRange ? (+ <button+ type="button"+ onClick={onOpenCustomRange}+ className={FILTER_PILL_BUTTON_CLASSNAME}+ >+ {filter.value+ .map((value) => new Date(value).toLocaleDateString("en-US"))+ .join(" – ")}+ </button>+ ) : (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button type="button" className={FILTER_PILL_BUTTON_CLASSNAME} />+ }+ >+ {filter.value[0]}+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start">+ <ScrollArea orientation="vertical" className="h-auto max-h-72">+ {DATE_FILTER_PRESETS.map((preset) => (+ <DropdownMenuItem+ key={preset}+ onClick={() => onSelectDatePreset(preset)}+ >+ {preset}+ </DropdownMenuItem>+ ))}+ <DropdownMenuItem onClick={onOpenCustomRange}>+ Custom date range…+ </DropdownMenuItem>+ </ScrollArea>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ <button+ type="button"+ aria-label={`Remove ${FILTER_TYPE_LABELS[filter.type]} filter`}+ onClick={onRemove}+ className={cn(+ FILTER_PILL_BUTTON_CLASSNAME,+ "rounded-r-md px-1 text-muted-foreground hover:text-foreground"+ )}+ >+ <HugeiconsIcon icon={Cancel01Icon} className="size-3" />+ </button>+ </div>+ )+}++function formatDateInputValue(date: Date | undefined) {+ if (!date) return ""++ const pad = (value: number) => String(value).padStart(2, "0")++ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`+}++function parseDateInputValue(value: string) {+ const trimmed = value.trim()++ if (!trimmed) return undefined++ const isoMatch = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(trimmed)++ if (isoMatch) {+ const date = new Date(+ Number(isoMatch[1]),+ Number(isoMatch[2]) - 1,+ Number(isoMatch[3])+ )++ return Number.isNaN(date.getTime()) ? undefined : date+ }++ const parsed = Date.parse(trimmed)++ return Number.isNaN(parsed) ? undefined : new Date(parsed)+}++const DATE_RANGE_DIALOG_PRESETS = [+ "Last 7 days",+ "This month",+ "Last 1 month",+ "Last 3 months",+ "This year",+ "Last 12 months",+]++function dateRangePresetRange(preset: string) {+ const from = new Date()+ const to = new Date()++ from.setHours(0, 0, 0, 0)+ to.setHours(23, 59, 59, 999)++ switch (preset) {+ case "Last 7 days":+ from.setDate(from.getDate() - 6)+ break+ case "This month":+ from.setDate(1)+ break+ case "Last 1 month":+ from.setMonth(from.getMonth() - 1)+ break+ case "Last 3 months":+ from.setMonth(from.getMonth() - 3)+ break+ case "This year":+ from.setMonth(0, 1)+ break+ case "Last 12 months":+ from.setFullYear(from.getFullYear() - 1)+ break+ }+ return { from, to }+}++const WEEKDAY_LABELS = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]++function calendarDayKey(date: Date) {+ return date.getFullYear() * 10_000 + date.getMonth() * 100 + date.getDate()+}++// Two-month range calendar for the custom date range dialog (one month at+// phone widths). Clicking sets the start, then the end; clicking before the+// start swaps the ends, and a third click restarts the range.+function FileSystemRangeCalendar({+ onSelect,+ range,+}: {+ onSelect: (range: { from?: Date; to?: Date }) => void+ range: { from?: Date; to?: Date }+}) {+ const [viewMonth, setViewMonth] = React.useState(() => {+ const base = range.from ?? new Date()++ return new Date(base.getFullYear(), base.getMonth(), 1)+ })+ const months = [+ viewMonth,+ new Date(viewMonth.getFullYear(), viewMonth.getMonth() + 1, 1),+ ]+ const fromKey = range.from ? calendarDayKey(range.from) : null+ const toKey = range.to ? calendarDayKey(range.to) : null+ const todayKey = calendarDayKey(new Date())++ const handleDayClick = (day: Date) => {+ if (!range.from || range.to) {+ onSelect({ from: day })+ } else if (calendarDayKey(day) < calendarDayKey(range.from)) {+ onSelect({ from: day, to: range.from })+ } else {+ onSelect({ from: range.from, to: day })+ }+ }++ return (+ <div className="relative">+ <button+ type="button"+ aria-label="Previous month"+ onClick={() =>+ setViewMonth(+ (previous) =>+ new Date(previous.getFullYear(), previous.getMonth() - 1, 1)+ )+ }+ className="absolute top-0 left-0 flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"+ >+ <HugeiconsIcon icon={ArrowLeft01Icon} className="size-4" />+ </button>+ <button+ type="button"+ aria-label="Next month"+ onClick={() =>+ setViewMonth(+ (previous) =>+ new Date(previous.getFullYear(), previous.getMonth() + 1, 1)+ )+ }+ className="absolute top-0 right-0 flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"+ >+ <HugeiconsIcon icon={ArrowRight01Icon} className="size-4" />+ </button>+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">+ {months.map((month, monthIndex) => {+ const firstWeekday = month.getDay()+ const dayCount = new Date(+ month.getFullYear(),+ month.getMonth() + 1,+ 0+ ).getDate()+ const cells = [+ ...Array.from({ length: firstWeekday }, () => null),+ ...Array.from(+ { length: dayCount },+ (_, index) =>+ new Date(month.getFullYear(), month.getMonth(), index + 1)+ ),+ ]++ return (+ <div+ key={`${month.getFullYear()}-${month.getMonth()}`}+ className={cn(monthIndex === 1 && "max-sm:hidden")}+ >+ <div className="text-center text-sm leading-6 font-medium">+ {month.toLocaleDateString("en-US", {+ month: "long",+ year: "numeric",+ })}+ </div>+ <div className="mt-1 grid grid-cols-7 text-center text-xs text-muted-foreground">+ {WEEKDAY_LABELS.map((weekday) => (+ <span key={weekday} className="h-6 leading-6">+ {weekday}+ </span>+ ))}+ </div>+ <div className="grid grid-cols-7 gap-y-px">+ {cells.map((day, cellIndex) => {+ if (!day) return <span key={cellIndex} />++ const dayKey = calendarDayKey(day)+ const isFrom = dayKey === fromKey+ const isTo = dayKey === toKey+ const isWithinRange =+ fromKey !== null &&+ toKey !== null &&+ dayKey > fromKey &&+ dayKey < toKey++ return (+ <button+ key={cellIndex}+ type="button"+ onClick={() => handleDayClick(day)}+ className={cn(+ "flex h-7 items-center justify-center rounded-md text-xs tabular-nums transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",+ isWithinRange && "rounded-none bg-accent",+ (isFrom || isTo) &&+ "bg-primary text-primary-foreground hover:bg-primary",+ isFrom &&+ toKey !== null &&+ fromKey !== toKey &&+ "rounded-r-none",+ isTo && fromKey !== toKey && "rounded-l-none",+ dayKey === todayKey &&+ !isFrom &&+ !isTo &&+ "font-semibold text-primary"+ )}+ >+ {day.getDate()}+ </button>+ )+ })}+ </div>+ </div>+ )+ })}+ </div>+ </div>+ )+}++// Custom date range dialog mirroring Extend's table filters: From/To inputs,+// a two-month range calendar, and quick presets. Applied ranges span from+// the start of the first day to the end of the last.+function FileSystemDateRangeDialog({+ initialRange,+ onApply,+ onClose,+}: {+ initialRange?: { from: Date; to: Date }+ onApply: (from: Date, to: Date) => void+ onClose: () => void+}) {+ const [range, setRange] = React.useState<{ from?: Date; to?: Date }>(+ () => initialRange ?? {}+ )+ const [fromInput, setFromInput] = React.useState(() =>+ formatDateInputValue(initialRange?.from)+ )+ const [toInput, setToInput] = React.useState(() =>+ formatDateInputValue(initialRange?.to)+ )++ const selectRange = (next: { from?: Date; to?: Date }) => {+ setRange(next)+ if (next.from) setFromInput(formatDateInputValue(next.from))+ if (next.to) setToInput(formatDateInputValue(next.to))+ }++ const dateField = (+ label: string,+ value: string,+ onChange: (value: string) => void+ ) => (+ <div className="flex flex-1 flex-col gap-1.5">+ <span className="text-xs font-medium">{label}</span>+ <div className="relative flex items-center">+ <HugeiconsIcon+ icon={Calendar03Icon}+ className="pointer-events-none absolute left-2.5 size-3.5 text-muted-foreground"+ />+ <Input+ type="text"+ value={value}+ placeholder="YYYY-MM-DD"+ aria-label={`${label} date`}+ onChange={(event) => onChange(event.target.value)}+ className="h-8 pl-8 sm:h-8"+ />+ </div>+ </div>+ )++ return (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open) onClose()+ }}+ >+ <DialogContent className="w-[30rem] max-w-[calc(100vw-2rem)]">+ <DialogHeader>+ <DialogTitle>Custom date range</DialogTitle>+ </DialogHeader>+ <DialogPanel className="flex flex-col gap-4">+ <div className="flex gap-3">+ {dateField("From", fromInput, (value) => {+ setFromInput(value)++ const parsed = parseDateInputValue(value)++ if (parsed)+ setRange((previous) => ({ ...previous, from: parsed }))+ })}+ {dateField("To", toInput, (value) => {+ setToInput(value)++ const parsed = parseDateInputValue(value)++ if (parsed) setRange((previous) => ({ ...previous, to: parsed }))+ })}+ </div>+ <FileSystemRangeCalendar range={range} onSelect={selectRange} />+ <div className="grid grid-cols-3 gap-2">+ {DATE_RANGE_DIALOG_PRESETS.map((preset) => (+ <Button+ key={preset}+ type="button"+ variant="outline"+ size="sm"+ onClick={() => selectRange(dateRangePresetRange(preset))}+ >+ {preset}+ </Button>+ ))}+ </div>+ </DialogPanel>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={onClose}>+ Cancel+ </Button>+ <Button+ type="button"+ disabled={!range.from || !range.to}+ onClick={() => {+ if (!range.from || !range.to) return++ const from = new Date(range.from)+ const to = new Date(range.to)++ from.setHours(0, 0, 0, 0)+ to.setHours(23, 59, 59, 999)+ onApply(from, to)+ }}+ >+ Apply+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++type FileSystemViewProps = {+ currentPath: string+ entries: FileSystemEntry[]+ fileFilter: ((file: FileEntry) => boolean) | null+ getFileUrl?: (file: FileSystemFileItem) => string | Promise<string>+ index: FileSystemIndex+ loadPreviewImageUrl?: (+ file: FileSystemFileItem,+ pageIndex: number+ ) => Promise<string | null>+ loadingFolders: Set<string>+ onOpen: (entry: FileSystemEntry) => voidonSelect: (entry: FileSystemEntry | null) => void+ onSortColumnClick: (key: FileSystemSortKey) => voidrenderFilePreview?: (file: FileSystemFileItem) => React.ReactNode+ searchQuery: stringselectedEntry: FileSystemEntry | nullselectedPath: string | null+ sort: FileSystemSortState+ /** Expanded tree folders per folder path, surviving view switches. */+ treeExpansionRef: React.RefObject<Map<string, readonly string[]>>}// Resolves a display URL for a file: its own `url`, else via `getFileUrl`.@@ -1089,6 +2908,86 @@ function FileSystemEmptyState({const ARROW_KEYS = new Set(["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"])+// Type-ahead buffers reset after this idle period, like Finder.+const TYPE_AHEAD_RESET_MS = 700++// Letters and digits only — the same key test the tree uses — so shortcuts+// and whitespace scrolling stay untouched.+function isTypeAheadKey(event: React.KeyboardEvent) {+ return (+ event.key.length === 1 &&+ /^[\p{L}\p{N}]$/u.test(event.key) &&+ !event.altKey &&+ !event.ctrlKey &&+ !event.metaKey+ )+}++// Shared Finder-style type-ahead used by every view: printable keys+// accumulate a buffer that jumps to the next entry whose name starts with+// it, and repeating a single letter cycles through entries with that+// prefix. Each view passes its own display-ordered candidate list, so the+// same keystrokes land on the same file everywhere.+function useEntryTypeAhead() {+ const stateRef = React.useRef({ buffer: "", timeout: 0 })++ React.useEffect(() => {+ const state = stateRef.current++ return () => window.clearTimeout(state.timeout)+ }, [])++ return React.useCallback(+ (+ event: React.KeyboardEvent,+ entries: readonly FileSystemEntry[],+ currentIndex: number+ ) => {+ if (!isTypeAheadKey(event) || entries.length === 0) return null++ // Embedded viewers (and any future inputs) keep their keystrokes.+ const target = event.target++ if (+ target instanceof HTMLElement &&+ (target.isContentEditable ||+ target.tagName === "INPUT" ||+ target.tagName === "TEXTAREA" ||+ target.tagName === "SELECT")+ ) {+ return null+ }++ const state = stateRef.current++ window.clearTimeout(state.timeout)+ state.timeout = window.setTimeout(() => {+ state.buffer = ""+ }, TYPE_AHEAD_RESET_MS)+ state.buffer += event.key.toLowerCase()++ // A repeated single letter advances past the current entry; a longer+ // buffer refines the match in place.+ const startIndex =+ currentIndex < 0+ ? 0+ : currentIndex + (state.buffer.length === 1 ? 1 : 0)++ for (let step = 0; step < entries.length; step += 1) {+ const entry = entries[(startIndex + step) % entries.length]++ if (entry.name.toLowerCase().startsWith(state.buffer)) {+ event.preventDefault()+ return entry+ }+ }+ event.preventDefault()+ return null+ },+ []+ )+}+// Selects (and focuses) the entry reached by an arrow key. Up/down use row// geometry so navigation follows the rendered auto-fill grid.function moveGridSelection({@@ -1151,6 +3050,16 @@ function moveGridSelection({return true}+// Icon grid geometry (px at the default 16px root font size). Tiles have a+// fixed height — a 4rem glyph box plus a reserved two-line label — so rows+// share one stride and the grid can window cleanly.+const ICON_GRID_PADDING = 12 // p-3+const ICON_MIN_TILE_WIDTH = 104 // 6.5rem+const ICON_TILE_GAP_X = 4 // gap-x-1+const ICON_TILE_HEIGHT = 102 // h-16 glyph box + gap-1.5 + two text-xs lines+const ICON_ROW_GAP = 12 // gap-y-3+const ICON_ROW_STRIDE = ICON_TILE_HEIGHT + ICON_ROW_GAP+function FileSystemIconsView({entries,onOpen,@@ -1159,15 +3068,84 @@ function FileSystemIconsView({selectedPath,}: FileSystemViewProps) {const itemRefs = React.useRef(new Map<string, HTMLButtonElement>())- // Roving tabindex: the grid is a single tab stop (the selected tile, or the- // first one), so Shift+Tab returns to the toolbar like in the list view.- const tabStopPath = entries.some((entry) => entry.path === selectedPath)+ const viewportRef = React.useRef<HTMLDivElement | null>(null)+ const typeAhead = useEntryTypeAhead()+ // The column count mirrors what `repeat(auto-fill, minmax(6.5rem, 1fr))`+ // produces (the CSS owns the actual layout) so item indices map to grid+ // rows — the windowing below depends on that mapping. It stays null until+ // the first client measure; server markup must not guess.+ const [columnCount, setColumnCount] = React.useState<number | null>(null)++ React.useLayoutEffect(() => {+ const viewport = viewportRef.current++ if (!viewport || typeof ResizeObserver === "undefined") return++ const update = () => {+ const available = viewport.clientWidth - ICON_GRID_PADDING * 2++ setColumnCount(+ Math.max(+ 1,+ Math.floor(+ (available + ICON_TILE_GAP_X) /+ (ICON_MIN_TILE_WIDTH + ICON_TILE_GAP_X)+ )+ )+ )+ }+ const observer = new ResizeObserver(update)++ update()+ observer.observe(viewport)+ return () => observer.disconnect()+ }, [])++ const resolvedColumnCount = columnCount ?? 1+ const rowCount = Math.ceil(entries.length / resolvedColumnCount)+ const { end, start } = useVirtualWindow({+ count: rowCount,+ itemStride: ICON_ROW_STRIDE,+ leadingPx: ICON_GRID_PADDING,+ overscan: 4,+ viewportRef,+ })+ const visibleEntries = entries.slice(+ start * resolvedColumnCount,+ end * resolvedColumnCount+ )++ // Selection can land outside the window (view switches, shrinking results);+ // bring its row back into the viewport so the tile mounts and is focusable.+ React.useLayoutEffect(() => {+ if (!selectedPath) return++ const entryIndex = entries.findIndex((entry) => entry.path === selectedPath)++ if (entryIndex === -1) return++ scrollIndexIntoView({+ index: Math.floor(entryIndex / resolvedColumnCount),+ itemSize: ICON_TILE_HEIGHT,+ itemStride: ICON_ROW_STRIDE,+ leadingPx: ICON_GRID_PADDING,+ viewport: viewportRef.current,+ })+ }, [entries, resolvedColumnCount, selectedPath])++ // Roving tabindex: the grid is a single tab stop (the selected tile when+ // rendered, else the first rendered one), so Shift+Tab returns to the+ // toolbar like in the list view.+ const tabStopPath = visibleEntries.some(+ (entry) => entry.path === selectedPath+ )? selectedPath- : (entries[0]?.path ?? null)+ : (visibleEntries[0]?.path ?? null)return (<ScrollAreaorientation="vertical"+ viewportRef={viewportRef}viewportClassName="p-3"viewportProps={{onClick: (event) => {@@ -1176,118 +3154,208 @@ function FileSystemIconsView({}}><div- role="listbox"- aria-label="Files"- className="grid grid-cols-[repeat(auto-fill,minmax(6.5rem,1fr))] gap-x-1 gap-y-3"- onKeyDown={(event) => {- if (!ARROW_KEYS.has(event.key)) return- if (- moveGridSelection({- entries,- itemRefs: itemRefs.current,- key: event.key,- onSelect,- selectedPath,- })- ) {- event.preventDefault()- }+ className="relative"+ // The scroll-height spacer needs the measured column count; until+ // then the absolutely positioned grid alone defines the scrollable+ // overflow, so the server-rendered frame doesn't flash an+ // oversized scroll range.+ style={{+ height:+ columnCount !== null && rowCount+ ? rowCount * ICON_ROW_STRIDE - ICON_ROW_GAP+ : undefined,}}>- {entries.map((entry) => {- const isSelected = entry.path === selectedPath-- return (- <button- key={entry.path}- type="button"- role="option"- aria-selected={isSelected}- tabIndex={entry.path === tabStopPath ? 0 : -1}- ref={(element) => {- if (element) {- itemRefs.current.set(entry.path, element)- } else {- itemRefs.current.delete(entry.path)- }- }}- onClick={() => onSelect(entry)}- onDoubleClick={() => onOpen(entry)}- onKeyDown={(event) => {- if (event.key === "Enter") onOpen(entry)- }}- className="group flex flex-col items-center gap-1.5 outline-none"- >- <span- className={cn(- "flex h-16 w-20 items-center justify-center rounded-lg p-1 transition-colors group-focus-visible:ring-2 group-focus-visible:ring-ring",- isSelected && "bg-accent"- )}- >- {entry.kind === "folder" ? (- <FileSystemFolderGlyph className="h-13 w-auto drop-shadow-sm" />- ) : (- <FileVisual- file={entry}- className={cn(- "rounded-sm shadow-xs",- // Landscape thumbnails get extra width so they fill- // the tile instead of rendering as a short sliver.- (entry.previewAspectRatio ?? 0.78) > 1.2- ? "w-[4.75rem]"- : "w-12"- )}- previewAspectRatio={0.78}- renderFilePreview={renderFilePreview}- />- )}- </span>- <span- className={cn(- "max-w-full rounded-sm px-1.5 py-px text-center text-xs leading-tight break-words",- isSelected- ? "bg-primary text-primary-foreground"- : "text-foreground"- )}+ <div+ role="listbox"+ aria-label="Files"+ className="absolute inset-x-0 grid gap-x-1 gap-y-3"+ // The auto-fill expression produces the same column count the+ // ResizeObserver measures (the measurement exists only for the+ // windowing math), so the server-rendered first paint is already+ // a grid instead of flashing a single stacked column until the+ // first client measure.+ style={{+ gridTemplateColumns: "repeat(auto-fill, minmax(6.5rem, 1fr))",+ top: start * ICON_ROW_STRIDE,+ }}+ onKeyDown={(event) => {+ if (!ARROW_KEYS.has(event.key)) {+ const match = typeAhead(+ event,+ entries,+ entries.findIndex((entry) => entry.path === selectedPath)+ )++ if (match) {+ onSelect(match)+ // The matched tile may be outside the virtual window; the+ // selection effect scrolls it in, and focus follows once it+ // has mounted.+ requestAnimationFrame(() =>+ itemRefs.current.get(match.path)?.focus()+ )+ }+ return+ }+ if (+ moveGridSelection({+ entries,+ itemRefs: itemRefs.current,+ key: event.key,+ onSelect,+ selectedPath,+ })+ ) {+ event.preventDefault()+ }+ }}+ >+ {visibleEntries.map((entry) => {+ const isSelected = entry.path === selectedPath++ return (+ <button+ key={entry.path}+ type="button"+ role="option"+ aria-selected={isSelected}+ tabIndex={entry.path === tabStopPath ? 0 : -1}+ ref={(element) => {+ if (element) {+ itemRefs.current.set(entry.path, element)+ } else {+ itemRefs.current.delete(entry.path)+ }+ }}+ onClick={() => onSelect(entry)}+ onDoubleClick={() => onOpen(entry)}+ onKeyDown={(event) => {+ if (event.key === "Enter") onOpen(entry)+ }}+ className="group flex h-[6.375rem] flex-col items-center gap-1.5 outline-none">- <span className="line-clamp-2">{entry.name}</span>- </span>- </button>- )- })}+ <span+ className={cn(+ "flex h-16 w-20 shrink-0 items-center justify-center rounded-lg p-1 transition-colors group-focus-visible:ring-2 group-focus-visible:ring-ring",+ isSelected && "bg-accent"+ )}+ >+ {entry.kind === "folder" ? (+ <FileSystemFolderGlyph className="h-13 w-auto drop-shadow-sm" />+ ) : (+ <FileVisual+ file={entry}+ className={cn(+ "rounded-sm shadow-xs",+ // Landscape thumbnails get extra width so they fill+ // the tile instead of rendering as a short sliver.+ (entry.previewAspectRatio ?? 0.78) > 1.2+ ? "w-[4.75rem]"+ : "w-12"+ )}+ previewAspectRatio={0.78}+ renderFilePreview={renderFilePreview}+ />+ )}+ </span>+ <span+ className={cn(+ "max-w-full rounded-sm px-1.5 py-px text-center text-xs leading-tight break-words",+ isSelected+ ? "bg-primary text-primary-foreground"+ : "text-foreground"+ )}+ >+ <span className="line-clamp-2">{entry.name}</span>+ </span>+ </button>+ )+ })}+ </div></div></ScrollArea>)}+// One sortable column header for the list view; the active column shows the+// direction chevron on its right.+function FileSystemListColumnHeader({+ className,+ label,+ onClick,+ sort,+ sortKey,+}: {+ className?: string+ label: string+ onClick: (key: FileSystemSortKey) => void+ sort: FileSystemSortState+ sortKey: FileSystemSortKey+}) {+ const isActive = sort.key === sortKey++ return (+ <button+ type="button"+ onClick={() => onClick(sortKey)}+ className={cn(+ "flex items-center gap-0.5 rounded-sm py-0.5 transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",+ isActive && "text-foreground",+ className+ )}+ >+ {label}+ {isActive ? (+ <HugeiconsIcon+ icon={sort.direction === "asc" ? ArrowUp01Icon : ArrowDown01Icon}+ className="size-3 shrink-0"+ />+ ) : null}+ </button>+ )+}+function FileSystemListView({currentPath,+ fileFilter,index,onOpen,onSelect,+ onSortColumnClick,+ searchQuery,selectedPath,+ sort,+ treeExpansionRef,}: FileSystemViewProps) {+ // Filters narrow the path list handed to the tree; the search query stays+ // out of it so the tree's own search session (with match highlighting)+ // keeps handling it without remounts per keystroke.const relativePaths = React.useMemo(() => {const paths: string[] = []- for (const path of index.files.keys()) {+ for (const [path, file] of index.files) {if (currentPath === "" || path.startsWith(currentPath)) {const relativePath = path.slice(currentPath.length)- if (relativePath) paths.push(relativePath)+ if (!relativePath) continue+ if (fileFilter && !fileFilter(file)) continue+ paths.push(relativePath)}}return paths.sort()- }, [currentPath, index])- // Content-derived key: the tree only remounts when the path set actually- // changes (a bare length check misses same-count replacements).- const treeKey = React.useMemo(- () => hashString(relativePaths.join("\n")),- [relativePaths]- )+ }, [currentPath, fileFilter, index])if (relativePaths.length === 0) {- return <FileSystemEmptyState label="This folder is empty" />+ return (+ <FileSystemEmptyState+ label={+ fileFilter+ ? "No items match the active filters"+ : "This folder is empty"+ }+ />+ )}return (@@ -1295,14 +3363,36 @@ function FileSystemListView({{/* Paddings match the tree's row geometry: name text starts 46px in(16px tree padding + 30px icon lane), metadata ends 24px from theright (16px tree padding + 8px decoration inset). */}- <div className="flex shrink-0 items-center border-b py-1.5 pr-6 pl-[46px] text-xs font-medium text-muted-foreground">- <span className="flex-1">Name</span>- <span className="w-44 text-right">Date Modified</span>- <span className="w-20 text-right">Size</span>+ <div className="flex shrink-0 items-center border-b py-1 pr-6 pl-[46px] text-xs font-medium text-muted-foreground">+ <FileSystemListColumnHeader+ className="flex-1 justify-start"+ label="Name"+ onClick={onSortColumnClick}+ sort={sort}+ sortKey="name"+ />+ <FileSystemListColumnHeader+ className="w-44 justify-end"+ label="Date Modified"+ onClick={onSortColumnClick}+ sort={sort}+ sortKey="updatedAt"+ />+ <FileSystemListColumnHeader+ className="w-20 justify-end"+ label="Size"+ onClick={onSortColumnClick}+ sort={sort}+ sortKey="size"+ /></div>+ {/* Keyed by folder only: navigation remounts the tree, while filter,+ sort, and manifest changes update the mounted model in place so+ folder disclosure state survives them. */}<FileSystemPierreTree- key={`${currentPath}::${treeKey}`}+ key={currentPath}currentPath={currentPath}+ hasActiveFilters={fileFilter !== null}index={index}initialSelectedPath={selectedPath?.startsWith(currentPath)@@ -1312,32 +3402,105 @@ function FileSystemListView({onOpen={onOpen}onSelect={onSelect}relativePaths={relativePaths}+ searchQuery={searchQuery}+ sort={sort}+ treeExpansionRef={treeExpansionRef}/></div>)}+// Embedded thumbnail symbols grow the sprite injected into the tree's shadow+// DOM (data-URL covers can run hundreds of KB each); past this many the+// remaining files fall back to the built-in file-type icons alone.+const TREE_THUMBNAIL_SPRITE_LIMIT = 400+function FileSystemPierreTree({currentPath,+ hasActiveFilters,index,initialSelectedPath,onOpen,onSelect,relativePaths,+ searchQuery,+ sort,+ treeExpansionRef,}: {currentPath: string+ hasActiveFilters: booleanindex: FileSystemIndexinitialSelectedPath: string | nullonOpen: (entry: FileSystemEntry) => voidonSelect: (entry: FileSystemEntry | null) => voidrelativePaths: string[]+ searchQuery: string+ sort: FileSystemSortState+ treeExpansionRef: React.RefObject<Map<string, readonly string[]>>}) {+ // The tree's comparator receives whole paths, not siblings, so it walks+ // the shared segments and applies the active sort at the first level the+ // two paths diverge — keeping directories first per level, the tree's+ // default convention. Lookups go through the index maps, which are stable+ // across search keystrokes.+ const indexFiles = index.files+ const indexFolders = index.folders+ const sortComparator = React.useMemo<+ "default" | FileTreeSortComparator+ >(() => {+ if (+ sort.key === DEFAULT_SORT.key &&+ sort.direction === DEFAULT_SORT.direction+ ) {+ return "default"+ }++ const entryAtDepth = (sortEntry: FileTreeSortEntry, depth: number) => {+ const isDirectory =+ depth < sortEntry.segments.length - 1 || sortEntry.isDirectory+ const absolutePath = `${currentPath}${sortEntry.segments+ .slice(0, depth + 1)+ .join("/")}${isDirectory ? "/" : ""}`++ return isDirectory+ ? indexFolders.get(absolutePath)+ : indexFiles.get(absolutePath)+ }++ return (left, right) => {+ const sharedDepth = Math.min(left.segments.length, right.segments.length)++ for (let depth = 0; depth < sharedDepth; depth += 1) {+ if (left.segments[depth] === right.segments[depth]) continue++ const leftIsDirectory =+ depth < left.segments.length - 1 || left.isDirectory+ const rightIsDirectory =+ depth < right.segments.length - 1 || right.isDirectory++ if (leftIsDirectory !== rightIsDirectory) {+ return leftIsDirectory ? -1 : 1+ }++ const leftEntry = entryAtDepth(left, depth)+ const rightEntry = entryAtDepth(right, depth)++ if (leftEntry && rightEntry) {+ return compareEntriesBySort(leftEntry, rightEntry, sort)+ }+ return left.segments[depth] < right.segments[depth] ? -1 : 1+ }+ return left.segments.length - right.segments.length+ }+ }, [currentPath, indexFiles, indexFolders, sort])const preparedInput = React.useMemo(- () => prepareFileTreeInput(relativePaths, { sort: "default" }),- [relativePaths]+ () => prepareFileTreeInput(relativePaths, { sort: sortComparator }),+ [relativePaths, sortComparator])// Inject per-file thumbnails into the tree's shadow DOM as sprite symbols- // wrapping an <image>, remapped onto rows by file basename. The chevron is+ // wrapping an <image>, remapped onto rows by file basename. Files without+ // a thumbnail resolve through the built-in complete icon set instead — the+ // same colored file-type icons the other views use. The chevron is// remapped to the Hugeicons arrow so it matches the rest of the component;// the tree's rotation CSS keys off data-icon-name, which remapping keeps.const icons = React.useMemo(() => {@@ -1346,7 +3509,11 @@ function FileSystemPierreTree({`<symbol id="file-system-chevron" viewBox="0 0 24 24"><path d="M18 9.00005C18 9.00005 13.5811 15 12 15C10.4188 15 6 9 6 9" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/></symbol>`,]+ let thumbnailCount = 0+for (const relativePath of relativePaths) {+ if (thumbnailCount >= TREE_THUMBNAIL_SPRITE_LIMIT) break+const file = index.files.get(`${currentPath}${relativePath}`)const coverUrl = file ? filePreviewUrls(file)[0] : undefined@@ -1362,16 +3529,19 @@ function FileSystemPierreTree({`<symbol id="${symbolId}" viewBox="0 0 16 16"><clipPath id="${symbolId}-clip"><rect width="16" height="16" rx="2.5"/></clipPath><image href="${escapeXmlAttribute(coverUrl)}" width="16" height="16" preserveAspectRatio="xMidYMid slice" clip-path="url(#${symbolId}-clip)"/></symbol>`)byFileName[baseName] = { name: symbolId, viewBox: "0 0 16 16" }+ thumbnailCount += 1}return {byFileName,+ colored: true,remap: {"file-tree-icon-chevron": {name: "file-system-chevron",viewBox: "0 0 24 24",},},+ set: "complete" as const,spriteSheet: `<svg data-icon-sprite aria-hidden="true" width="0" height="0">${symbols.join("")}</svg>`,}}, [currentPath, index, relativePaths])@@ -1379,6 +3549,8 @@ function FileSystemPierreTree({flattenEmptyDirectories: false,icons,initialExpansion: "closed",+ // Remounts (folder changes, manifest updates) keep the active filter.+ initialSearchQuery: searchQuery || null,initialSelectedPaths: initialSelectedPath ? [initialSelectedPath] : [],itemHeight: 28,overscan: 12,@@ -1417,10 +3589,14 @@ function FileSystemPierreTree({button[data-type='item'][data-item-selected] {background: var(--color-primary);color: var(--color-primary-foreground);+ /* The primary surface is the opposite of the mode's background, so+ the row's light-dark() icon colors resolve against the opposite+ scheme — light-palette icons on the light pill in dark mode and+ vice versa. */+ color-scheme: var(--fs-selected-color-scheme, normal);}- button[data-type='item'][data-item-selected] *,- button[data-type='item'][data-item-selected] [data-item-section]::before,- button[data-type='item'][data-item-selected] svg {+ button[data-type='item'][data-item-selected] *:not([data-icon-token]):not([data-icon-token] *),+ button[data-type='item'][data-item-selected] [data-item-section]::before {color: var(--color-primary-foreground) !important;}[data-item-section='decoration'] > span {@@ -1470,6 +3646,138 @@ function FileSystemPierreTree({model.setIcons(icons)}, [icons, model])+ // The folders currently expanded in the mounted model, derived from the+ // given path list (the model knows the rows; the paths name the+ // directories to ask about).+ const collectExpandedDirectories = React.useCallback(+ (paths: readonly string[]) => {+ const expandedPaths: string[] = []++ for (const directoryPath of directoryPathsOf(paths)) {+ const item =+ model.getItem(directoryPath) ?? model.getItem(`${directoryPath}/`)++ if (item && "isExpanded" in item && item.isExpanded()) {+ expandedPaths.push(directoryPath)+ }+ }+ return expandedPaths+ },+ [model]+ )++ // Opens every given folder on the mounted model (no-ops on the already+ // open ones).+ const expandDirectories = React.useCallback(+ (directoryPaths: Iterable<string>) => {+ for (const directoryPath of directoryPaths) {+ const item =+ model.getItem(directoryPath) ?? model.getItem(`${directoryPath}/`)++ if (item && "isExpanded" in item && !item.isExpanded()) {+ item.toggle()+ }+ }+ },+ [model]+ )++ // Sort and filter changes swap the prepared input in place — remounting+ // would reset every folder's disclosure. The folders expanded in the+ // outgoing path list, the selection, and the active search query are+ // captured first and handed back to the reset.+ const appliedPreparedInputRef = React.useRef(preparedInput)+ // Filter bookkeeping: the latest prop (for unmount-time decisions), the+ // state at the last applied reset (for transition detection), and the+ // disclosure to restore once the filters clear.+ const hasActiveFiltersRef = React.useRef(hasActiveFilters)+ const filteredAtLastResetRef = React.useRef(hasActiveFilters)+ const preFilterExpansionRef = React.useRef<readonly string[] | null>(null)++ React.useEffect(() => {+ hasActiveFiltersRef.current = hasActiveFilters+ })++ React.useEffect(() => {+ const previousPreparedInput = appliedPreparedInputRef.current++ if (previousPreparedInput === preparedInput) return+ appliedPreparedInputRef.current = preparedInput++ const wasFiltered = filteredAtLastResetRef.current++ filteredAtLastResetRef.current = hasActiveFilters++ // Filters reveal their matches the way the search session does: every+ // folder on the way to a match opens. The disclosure from just before+ // filtering is kept aside and comes back when the filters clear.+ let expandedPaths: readonly string[]++ if (hasActiveFilters) {+ if (!wasFiltered) {+ preFilterExpansionRef.current = collectExpandedDirectories(+ previousPreparedInput.paths+ )+ }+ expandedPaths = [...directoryPathsOf(preparedInput.paths)]+ } else if (wasFiltered) {+ expandedPaths = preFilterExpansionRef.current ?? []+ preFilterExpansionRef.current = null+ } else {+ expandedPaths = collectExpandedDirectories(previousPreparedInput.paths)+ }++ const searchValue = model.getSearchValue()++ // The `paths` argument must stay unset: when both are given, resetPaths+ // re-prepares the paths with the comparator the model was CREATED with+ // and rejects the differently-ordered prepared input. Passing only the+ // prepared input makes the reset adopt its path list as-is, and the+ // reset itself carries the selection over.+ model.resetPaths(undefined as unknown as readonly string[], {+ initialExpandedPaths: expandedPaths,+ preparedInput,+ })+ if (searchValue) model.setSearch(searchValue)+ }, [collectExpandedDirectories, hasActiveFilters, model, preparedInput])++ // View switches and navigation unmount the tree; remember which folders+ // were left expanded and reopen them on the next mount of this folder+ // (before paint, so the restored disclosure never flashes closed). While+ // filters are active their matches are revealed instead, and the+ // remembered disclosure is the pre-filter one.+ React.useLayoutEffect(() => {+ const expansionStore = treeExpansionRef.current+ const savedExpansion = expansionStore.get(currentPath) ?? []++ if (hasActiveFiltersRef.current) {+ preFilterExpansionRef.current = savedExpansion+ expandDirectories(directoryPathsOf(appliedPreparedInputRef.current.paths))+ } else {+ expandDirectories(savedExpansion)+ }++ return () => {+ expansionStore.set(+ currentPath,+ hasActiveFiltersRef.current+ ? (preFilterExpansionRef.current ?? [])+ : collectExpandedDirectories(appliedPreparedInputRef.current.paths)+ )+ }+ }, [+ collectExpandedDirectories,+ currentPath,+ expandDirectories,+ treeExpansionRef,+ ])++ // The toolbar search drives the tree's own search session, which filters+ // rows with hide-non-matches semantics and highlights the matched text.+ React.useEffect(() => {+ model.setSearch(searchQuery || null)+ }, [model, searchQuery])+// The tree's arrow keys move focus and only select on click/Enter; mirror// focus into the (single) selection so arrowing selects like Finder. Shift// ranges keep the focused row selected, so they pass through untouched.@@ -1496,23 +3804,112 @@ function FileSystemPierreTree({})}, [model])+ // Rows live in the tree's shadow DOM; composedPath surfaces the row+ // element behind a pointer or keyboard event so it can resolve to a+ // manifest entry.+ const entryFromEvent = (event: React.SyntheticEvent) => {+ for (const target of event.nativeEvent.composedPath()) {+ if (!(target instanceof HTMLElement)) continue++ const relativePath = target.dataset?.itemPath++ if (!relativePath) continue++ const absolutePath = `${currentPath}${relativePath}`++ return (+ index.files.get(absolutePath) ??+ index.folders.get(normalizeFolderPath(absolutePath)) ??+ null+ )+ }+ return null+ }++ // The tree exposes rows by relative path; directory ids may or may not+ // carry the trailing slash depending on the call site.+ const resolveTreeItem = (relativePath: string) =>+ model.getItem(relativePath) ??+ model.getItem(+ relativePath.endsWith("/")+ ? relativePath.slice(0, -1)+ : `${relativePath}/`+ )++ // The tree's rows in display order — folders first per level, recursing+ // only into expanded folders — so type-ahead cycles exactly what's on+ // screen. Virtualization keeps this off the DOM; the index and the item+ // handles carry the same information.+ const collectVisibleEntries = () => {+ const visibleEntries: FileSystemEntry[] = []+ const walk = (folderPath: string) => {+ const children = index.children.get(folderPath) ?? []++ for (const child of children) {+ if (child.kind !== "folder") continue++ const item = resolveTreeItem(child.path.slice(currentPath.length))++ if (!item) continue+ visibleEntries.push(child)+ if ("isExpanded" in item && item.isExpanded()) walk(child.path)+ }+ for (const child of children) {+ if (child.kind === "file") visibleEntries.push(child)+ }+ }++ walk(currentPath)+ return visibleEntries+ }++ const typeAhead = useEntryTypeAhead()+return (<PierreFileTreemodel={model}className="block min-h-0 flex-1"+ // Finder semantics: double-clicking a folder navigates into it and+ // double-clicking a file opens it; a single click still only toggles+ // the folder's disclosure.onDoubleClick={(event) => {- // Rows live in the tree's shadow DOM; composedPath surfaces the row- // element so double-clicked files open like in the other views.- for (const target of event.nativeEvent.composedPath()) {- if (!(target instanceof HTMLElement)) continue- const relativePath = target.dataset?.itemPath- if (!relativePath) continue-- const file = index.files.get(`${currentPath}${relativePath}`)+ const entry = entryFromEvent(event)- if (file) onOpen(file)+ if (entry) onOpen(entry)+ }}+ // Enter mirrors the other views: navigate into the focused folder or+ // open the focused file. Printable keys run the shared type-ahead+ // over the visible rows.+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ const entry = entryFromEvent(event)++ if (entry) {+ event.preventDefault()+ onOpen(entry)+ }return}++ if (!isTypeAheadKey(event)) return++ const visibleEntries = collectVisibleEntries()+ const focusedPath = model.getFocusedPath()?.replace(/\/$/, "") ?? null+ const focusedIndex = visibleEntries.findIndex(+ (entry) =>+ entry.path.slice(currentPath.length).replace(/\/$/, "") ===+ focusedPath+ )+ const match = typeAhead(event, visibleEntries, focusedIndex)++ if (!match) return++ const item = resolveTreeItem(match.path.slice(currentPath.length))++ if (item) {+ model.scrollToPath(item.getPath())+ item.focus()+ }}}style={{@@ -1552,9 +3949,34 @@ function FileSystemColumnsView(props: FileSystemViewProps) {const deferredSelectedEntry = React.useDeferredValue(selectedEntry)const deferredSelectedPath = React.useDeferredValue(selectedPath)const pendingFocusPathRef = React.useRef<string | null>(null)+ const typeAhead = useEntryTypeAhead()const handleKeyDown = (event: React.KeyboardEvent) => {- if (!ARROW_KEYS.has(event.key)) return+ if (!ARROW_KEYS.has(event.key)) {+ // Type-ahead moves within the active column's rows, like Finder.+ const siblings =+ selectedEntry && selectedPath?.startsWith(currentPath)+ ? (index.children.get(selectedEntry.parentPath) ?? [])+ : (index.children.get(currentPath) ?? [])+ const match = typeAhead(+ event,+ siblings,+ siblings.findIndex((sibling) => sibling.path === selectedPath)+ )++ if (match) {+ onSelect(match)++ const row = rowRefs.current.get(match.path)++ if (row) {+ row.focus()+ } else {+ pendingFocusPathRef.current = match.path+ }+ }+ return+ }let nextEntry: FileSystemEntry | null | undefined@@ -1624,7 +4046,6 @@ function FileSystemColumnsView(props: FileSystemViewProps) {}return paths}, [currentPath, deferredSelectedEntry, deferredSelectedPath])- const columnPathSet = React.useMemo(() => new Set(columnPaths), [columnPaths])// Roving tabindex: all columns together form a single tab stop (the// selected row when its column is mounted, else the first row), so// Shift+Tab returns to the toolbar like in the list view.@@ -1663,92 +4084,30 @@ function FileSystemColumnsView(props: FileSystemViewProps) {viewportClassName="overscroll-x-contain"><div className="flex h-full w-max min-w-full" onKeyDown={handleKeyDown}>- {columnPaths.map((columnPath) => (- <ScrollArea+ {columnPaths.map((columnPath, columnIndex) => (+ <FileSystemColumnkey={columnPath || "(root)"}- orientation="vertical"- className="w-60 shrink-0 border-r"- viewportClassName="flex flex-col gap-px p-1.5"- viewportProps={{ "aria-label": "Files", role: "listbox" }}- >- {loadingFolders.has(columnPath) &&- !index.children.get(columnPath)?.length ? (- <div className="animate-pulse px-2 py-1.5 text-xs text-muted-foreground motion-reduce:animate-none">- Loading…- </div>- ) : (- (index.children.get(columnPath) ?? []).map((entry) => {- const isSelected = entry.path === selectedPath- const isOnTrail =- entry.kind === "folder" && columnPathSet.has(entry.path)-- const coverUrl =- entry.kind === "file" ? filePreviewUrls(entry)[0] : undefined-- return (- <button- key={entry.path}- type="button"- role="option"- aria-selected={isSelected}- tabIndex={entry.path === tabStopPath ? 0 : -1}- ref={(element) => {- if (element) {- rowRefs.current.set(entry.path, element)- } else {- rowRefs.current.delete(entry.path)- }- }}- onClick={() => onSelect(entry)}- onDoubleClick={() => onOpen(entry)}- onKeyDown={(event) => {- if (event.key === "Enter") onOpen(entry)- }}- className={cn(- "flex shrink-0 items-center gap-2 rounded-md px-2 py-1 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",- isSelected- ? "bg-primary text-primary-foreground"- : isOnTrail- ? "bg-accent"- : "hover:bg-accent/50"- )}- >- {entry.kind === "folder" ? (- <FileSystemFolderGlyph className="h-3.5 w-auto shrink-0" />- ) : coverUrl ? (- <img- src={coverUrl}- alt=""- draggable={false}- className="size-4 shrink-0 rounded-[3px] bg-white object-cover"- />- ) : (- <HugeiconsIcon- icon={File01Icon}- className={cn(- "size-4 shrink-0",- !isSelected && "text-muted-foreground"- )}- />- )}- <span className="min-w-0 flex-1 truncate">- {entry.name}- </span>- {entry.kind === "folder" &&- folderHasChildren(index, entry) ? (- <HugeiconsIcon- icon={ArrowRight01Icon}- className={cn(- "size-3.5 shrink-0",- !isSelected && "text-muted-foreground/60"- )}- />- ) : null}- </button>- )- })- )}- </ScrollArea>+ entries={index.children.get(columnPath) ?? []}+ index={index}+ isLoading={loadingFolders.has(columnPath)}+ onOpen={onOpen}+ onSelect={onSelect}+ rowRefs={rowRefs}+ // Scalar per-column props so the memoized column only+ // re-renders when its own rows change — a selection deeper in+ // the trail leaves ancestor columns untouched.+ selectedChildPath={+ selectedPath && pathParent(selectedPath) === columnPath+ ? selectedPath+ : null+ }+ tabStopChildPath={+ tabStopPath && pathParent(tabStopPath) === columnPath+ ? tabStopPath+ : null+ }+ trailChildPath={columnPaths[columnIndex + 1] ?? null}+ />))}{selectedFile ? (<ScrollArea@@ -1792,6 +4151,168 @@ function FileSystemColumnsView(props: FileSystemViewProps) {)}+// Column row geometry (px at the default 16px root font size).+const COLUMN_PADDING = 6 // p-1.5+const COLUMN_ROW_HEIGHT = 28 // h-7+const COLUMN_ROW_GAP = 1 // gap-px+const COLUMN_ROW_STRIDE = COLUMN_ROW_HEIGHT + COLUMN_ROW_GAP++// Memoized with scalar selection props: pressing into a deep trail only+// re-renders the columns whose rows actually change.+const FileSystemColumn = React.memo(function FileSystemColumn({+ entries,+ index,+ isLoading,+ onOpen,+ onSelect,+ rowRefs,+ selectedChildPath,+ tabStopChildPath,+ trailChildPath,+}: {+ entries: FileSystemEntry[]+ index: FileSystemIndex+ isLoading: boolean+ onOpen: (entry: FileSystemEntry) => void+ onSelect: (entry: FileSystemEntry | null) => void+ rowRefs: React.RefObject<Map<string, HTMLButtonElement>>+ selectedChildPath: string | null+ tabStopChildPath: string | null+ trailChildPath: string | null+}) {+ const viewportRef = React.useRef<HTMLDivElement | null>(null)+ const { end, start } = useVirtualWindow({+ count: entries.length,+ itemStride: COLUMN_ROW_STRIDE,+ leadingPx: COLUMN_PADDING,+ overscan: 10,+ viewportRef,+ })++ // Keyboard navigation can select a row this column hasn't mounted; scroll+ // it into the viewport so it mounts and the pending-focus effect can land.+ React.useLayoutEffect(() => {+ if (!selectedChildPath) return++ scrollIndexIntoView({+ index: entries.findIndex((entry) => entry.path === selectedChildPath),+ itemSize: COLUMN_ROW_HEIGHT,+ itemStride: COLUMN_ROW_STRIDE,+ leadingPx: COLUMN_PADDING,+ viewport: viewportRef.current,+ })+ }, [entries, selectedChildPath])++ return (+ <ScrollArea+ orientation="vertical"+ className="w-60 shrink-0 border-r"+ viewportRef={viewportRef}+ viewportClassName="p-1.5"+ viewportProps={{ "aria-label": "Files", role: "listbox" }}+ >+ {isLoading && entries.length === 0 ? (+ <div className="animate-pulse px-2 py-1.5 text-xs text-muted-foreground motion-reduce:animate-none">+ Loading…+ </div>+ ) : (+ <div+ className="relative"+ style={{+ height: entries.length+ ? entries.length * COLUMN_ROW_STRIDE - COLUMN_ROW_GAP+ : undefined,+ }}+ >+ <div+ className="absolute inset-x-0 flex flex-col gap-px"+ style={{ top: start * COLUMN_ROW_STRIDE }}+ >+ {entries.slice(start, end).map((entry) => {+ const isSelected = entry.path === selectedChildPath+ const isOnTrail =+ entry.kind === "folder" && entry.path === trailChildPath++ const coverUrl =+ entry.kind === "file" ? filePreviewUrls(entry)[0] : undefined++ return (+ <button+ key={entry.path}+ type="button"+ role="option"+ aria-selected={isSelected}+ // Selected rows sit on the primary surface — the opposite+ // of the mode's background — so the file-type icon swaps+ // to the opposite palette.+ data-file-system-on-primary={isSelected ? "" : undefined}+ tabIndex={entry.path === tabStopChildPath ? 0 : -1}+ ref={(element) => {+ if (element) {+ rowRefs.current.set(entry.path, element)+ } else {+ rowRefs.current.delete(entry.path)+ }+ }}+ // Selecting on press (mouse only) starts mounting the+ // child column a beat before mouseup — the immediacy+ // @pierre/trees rows have. Touch keeps selection on the+ // click so scroll gestures don't select.+ onPointerDown={(event) => {+ if (event.pointerType === "mouse" && event.button === 0) {+ onSelect(entry)+ }+ }}+ onClick={() => onSelect(entry)}+ onDoubleClick={() => onOpen(entry)}+ onKeyDown={(event) => {+ if (event.key === "Enter") onOpen(entry)+ }}+ className={cn(+ "flex h-7 shrink-0 items-center gap-2 rounded-md px-2 py-1 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",+ isSelected+ ? "bg-primary text-primary-foreground"+ : isOnTrail+ ? "bg-accent"+ : "hover:bg-accent/50"+ )}+ >+ {entry.kind === "folder" ? (+ <FileSystemFolderGlyph className="h-3.5 w-auto shrink-0" />+ ) : coverUrl ? (+ <img+ src={coverUrl}+ alt=""+ draggable={false}+ className="size-4 shrink-0 rounded-[3px] bg-white object-cover"+ />+ ) : (+ <FileTypeIcon+ fileName={entry.name}+ className="size-4 shrink-0"+ />+ )}+ <span className="min-w-0 flex-1 truncate">{entry.name}</span>+ {entry.kind === "folder" &&+ folderHasChildren(index, entry) ? (+ <HugeiconsIcon+ icon={ArrowRight01Icon}+ className={cn(+ "size-3.5 shrink-0",+ !isSelected && "text-muted-foreground/60"+ )}+ />+ ) : null}+ </button>+ )+ })}+ </div>+ </div>+ )}+ </ScrollArea>+ )+})+function FileSystemInformation({entry,index,@@ -1839,6 +4360,12 @@ function FileSystemInformation({)}+// Filmstrip geometry (px at the default 16px root font size).+const GALLERY_STRIP_PADDING = 8 // p-2+const GALLERY_TILE_SIZE = 56 // size-14+const GALLERY_TILE_GAP = 6 // gap-1.5+const GALLERY_TILE_STRIDE = GALLERY_TILE_SIZE + GALLERY_TILE_GAP+function FileSystemGalleryView(props: FileSystemViewProps) {const {entries,@@ -1852,6 +4379,8 @@ function FileSystemGalleryView(props: FileSystemViewProps) {selectedPath,} = propsconst stripRefs = React.useRef(new Map<string, HTMLButtonElement>())+ const stripViewportRef = React.useRef<HTMLDivElement | null>(null)+ const typeAhead = useEntryTypeAhead()const activeEntry =selectedEntry && entries.some((entry) => entry.path === selectedEntry.path)? selectedEntry@@ -1873,12 +4402,24 @@ function FileSystemGalleryView(props: FileSystemViewProps) {const activeFileSize = activeFile ? formatByteSize(activeFile.size) : nullconst handleKeyDown = (event: React.KeyboardEvent) => {- if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") returnif (entries.length === 0) returnconst currentIndex = activeEntry? entries.findIndex((entry) => entry.path === activeEntry.path): -1++ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") {+ const match = typeAhead(event, entries, currentIndex)++ if (match) {+ onSelect(match)+ // The matched tile may be outside the strip's virtual window; the+ // active-tile effect scrolls it in, and focus follows once mounted.+ requestAnimationFrame(() => stripRefs.current.get(match.path)?.focus())+ }+ return+ }+const nextEntry =entries[currentIndex === -1@@ -1893,6 +4434,32 @@ function FileSystemGalleryView(props: FileSystemViewProps) {event.preventDefault()}+ const { end: stripEnd, start: stripStart } = useVirtualWindow({+ count: entries.length,+ horizontal: true,+ itemStride: GALLERY_TILE_STRIDE,+ leadingPx: GALLERY_STRIP_PADDING,+ overscan: 8,+ viewportRef: stripViewportRef,+ })++ // Keep the active tile mounted and visible while scrubbing or when the+ // selection arrives from another view.+ const activePath = activeEntry?.path ?? null++ React.useLayoutEffect(() => {+ if (!activePath) return++ scrollIndexIntoView({+ horizontal: true,+ index: entries.findIndex((entry) => entry.path === activePath),+ itemSize: GALLERY_TILE_SIZE,+ itemStride: GALLERY_TILE_STRIDE,+ leadingPx: GALLERY_STRIP_PADDING,+ viewport: stripViewportRef.current,+ })+ }, [activePath, entries])+return (<div className="flex size-full flex-col" onKeyDown={handleKeyDown}>{/* The strip comes first in DOM order (rendered below via order-last)@@ -1901,53 +4468,66 @@ function FileSystemGalleryView(props: FileSystemViewProps) {<ScrollAreaorientation="horizontal"className="order-last h-auto w-full shrink-0 border-t"+ viewportRef={stripViewportRef}+ viewportClassName="p-2"><div- role="listbox"- aria-label="Files"- className="flex w-max min-w-full items-center gap-1.5 p-2"+ className="relative h-14 min-w-full"+ style={{+ width: entries.length+ ? entries.length * GALLERY_TILE_STRIDE - GALLERY_TILE_GAP+ : undefined,+ }}>- {entries.map((entry) => {- const isActive = entry.path === (activeEntry?.path ?? selectedPath)-- return (- <button- key={entry.path}- type="button"- role="option"- aria-selected={isActive}- tabIndex={isActive ? 0 : -1}- ref={(element) => {- if (element) {- stripRefs.current.set(entry.path, element)- } else {- stripRefs.current.delete(entry.path)- }- }}- onClick={() => onSelect(entry)}- onDoubleClick={() => onOpen(entry)}- onKeyDown={(event) => {- if (event.key === "Enter") onOpen(entry)- }}- title={entry.name}- className={cn(- "flex size-14 shrink-0 items-center justify-center rounded-md border border-transparent p-1 outline-none focus-visible:ring-2 focus-visible:ring-ring",- isActive && "border-ring/40 bg-accent"- )}- >- {entry.kind === "folder" ? (- <FileSystemFolderGlyph className="h-9 w-auto" />- ) : (- <FileVisual- file={entry}- className="w-9 rounded-sm"- previewAspectRatio={0.78}- renderFilePreview={renderFilePreview}- />- )}- </button>- )- })}+ <div+ role="listbox"+ aria-label="Files"+ className="absolute inset-y-0 flex items-center gap-1.5"+ style={{ left: stripStart * GALLERY_TILE_STRIDE }}+ >+ {entries.slice(stripStart, stripEnd).map((entry) => {+ const isActive =+ entry.path === (activeEntry?.path ?? selectedPath)++ return (+ <button+ key={entry.path}+ type="button"+ role="option"+ aria-selected={isActive}+ tabIndex={isActive ? 0 : -1}+ ref={(element) => {+ if (element) {+ stripRefs.current.set(entry.path, element)+ } else {+ stripRefs.current.delete(entry.path)+ }+ }}+ onClick={() => onSelect(entry)}+ onDoubleClick={() => onOpen(entry)}+ onKeyDown={(event) => {+ if (event.key === "Enter") onOpen(entry)+ }}+ title={entry.name}+ className={cn(+ "flex size-14 shrink-0 items-center justify-center rounded-md border border-transparent p-1 outline-none focus-visible:ring-2 focus-visible:ring-ring",+ isActive && "border-ring/40 bg-accent"+ )}+ >+ {entry.kind === "folder" ? (+ <FileSystemFolderGlyph className="h-9 w-auto" />+ ) : (+ <FileVisual+ file={entry}+ className="w-9 rounded-sm"+ previewAspectRatio={0.78}+ renderFilePreview={renderFilePreview}+ />+ )}+ </button>+ )+ })}+ </div></div></ScrollArea><div className="flex min-h-0 flex-1">@@ -1965,32 +4545,38 @@ function FileSystemGalleryView(props: FileSystemViewProps) {/>) : activeViewerKind === "pdf" && activeFileUrl ? (<div className="size-full overflow-hidden rounded-lg border">- <PDFViewer- key={activeEntry.path}- file={activeFileUrl}- className="h-full"- showToolbar={false}- />+ <React.Suspense fallback={<FileSystemViewerLoading />}>+ <LazyPDFViewer+ key={activeEntry.path}+ file={activeFileUrl}+ className="h-full"+ showToolbar={false}+ />+ </React.Suspense></div>) : activeViewerKind === "docx" && activeFileUrl ? (<div className="size-full overflow-hidden rounded-lg border">- <DocxViewerPreview- key={activeEntry.path}- src={activeFileUrl}- fileName={activeEntry.name}- className="h-full"- showToolbar={false}- />+ <React.Suspense fallback={<FileSystemViewerLoading />}>+ <LazyDocxViewerPreview+ key={activeEntry.path}+ src={activeFileUrl}+ fileName={activeEntry.name}+ className="h-full"+ showToolbar={false}+ />+ </React.Suspense></div>) : activeViewerKind === "xlsx" && activeFileUrl ? (<div className="size-full overflow-hidden rounded-lg border">- <XlsxViewerPreview- key={activeEntry.path}- src={activeFileUrl}- fileName={activeEntry.name}- className="h-full"- showToolbar={false}- />+ <React.Suspense fallback={<FileSystemViewerLoading />}>+ <LazyXlsxViewerPreview+ key={activeEntry.path}+ src={activeFileUrl}+ fileName={activeEntry.name}+ className="h-full"+ showToolbar={false}+ />+ </React.Suspense></div>) : (<FileVisualdiff --git a/apps/v4/components/ui/pdf-viewer.tsx b/apps/v4/components/ui/pdf-viewer.tsxindex 9b3e1cf..2b5fe55 100644--- a/apps/v4/components/ui/pdf-viewer.tsx+++ b/apps/v4/components/ui/pdf-viewer.tsx@@ -2032,4 +2032,4 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(</div>)}-)+)\ No newline at end of filediff --git a/apps/v4/hooks/use-layout.tsx b/apps/v4/hooks/use-layout.tsxdeleted file mode 100644index fd30f9f..0000000--- a/apps/v4/hooks/use-layout.tsx+++ /dev/null@@ -1,163 +0,0 @@-"use client"--import * as React from "react"--type Layout = "fixed" | "full"--interface LayoutProviderProps {- children: React.ReactNode- defaultLayout?: Layout- forcedLayout?: Layout- storageKey?: string- attribute?: string | string[]- value?: Record<string, string>-}--interface LayoutProviderState {- layout: Layout- setLayout: (layout: Layout | ((prev: Layout) => Layout)) => void- forcedLayout?: Layout-}--const isServer = typeof window === "undefined"-const LayoutContext = React.createContext<LayoutProviderState | undefined>(- undefined-)--const saveToLS = (storageKey: string, value: string) => {- try {- localStorage.setItem(storageKey, value)- } catch {- // Unsupported- }-}--const useLayout = () => {- const context = React.useContext(LayoutContext)- if (context === undefined) {- throw new Error("useLayout must be used within a LayoutProvider")- }- return context-}--const Layout = ({- forcedLayout,- storageKey = "layout",- defaultLayout = "full",- attribute = "class",- value,- children,-}: LayoutProviderProps) => {- const [layout, setLayoutState] = React.useState<Layout>(() => {- if (isServer) return defaultLayout- try {- const saved = localStorage.getItem(storageKey)- if (saved === "fixed" || saved === "full") {- return saved- }- return defaultLayout- } catch {- return defaultLayout- }- })-- const attrs = React.useMemo(- () => (!value ? ["layout-fixed", "layout-full"] : Object.values(value)),- [value]- )-- const applyLayout = React.useCallback(- (layout: Layout) => {- if (!layout) return-- const name = value ? value[layout] : `layout-${layout}`- const d = document.documentElement-- const handleAttribute = (attr: string) => {- if (attr === "class") {- d.classList.remove(...attrs)- if (name) d.classList.add(name)- } else if (attr.startsWith("data-")) {- if (name) {- d.setAttribute(attr, name)- } else {- d.removeAttribute(attr)- }- }- }-- if (Array.isArray(attribute)) attribute.forEach(handleAttribute)- else handleAttribute(attribute)- },- [attrs, attribute, value]- )-- const setLayout = React.useCallback(- (value: Layout | ((prev: Layout) => Layout)) => {- if (typeof value === "function") {- setLayoutState((prevLayout) => {- const newLayout = value(prevLayout)- saveToLS(storageKey, newLayout)- return newLayout- })- } else {- setLayoutState(value)- saveToLS(storageKey, value)- }- },- [storageKey]- )-- // localStorage event handling- React.useEffect(() => {- const handleStorage = (e: StorageEvent) => {- if (e.key !== storageKey) return-- if (!e.newValue) {- setLayout(defaultLayout)- } else if (e.newValue === "fixed" || e.newValue === "full") {- setLayoutState(e.newValue)- }- }-- window.addEventListener("storage", handleStorage)- return () => window.removeEventListener("storage", handleStorage)- }, [setLayout, storageKey, defaultLayout])-- // Apply layout on mount and when it changes- React.useEffect(() => {- const currentLayout = forcedLayout ?? layout- applyLayout(currentLayout)- }, [forcedLayout, layout, applyLayout])-- // Prevent layout changes during hydration- const [isHydrated, setIsHydrated] = React.useState(false)- React.useEffect(() => {- setIsHydrated(true)- }, [])-- const providerValue = React.useMemo(- () => ({- layout: isHydrated ? layout : defaultLayout,- setLayout,- forcedLayout,- }),- [layout, setLayout, forcedLayout, isHydrated, defaultLayout]- )-- return (- <LayoutContext.Provider value={providerValue}>- {children}- </LayoutContext.Provider>- )-}--const LayoutProvider = (props: LayoutProviderProps) => {- const context = React.useContext(LayoutContext)-- // Ignore nested context providers, just passthrough children- if (context) return <>{props.children}</>- return <Layout {...props} />-}--export { useLayout, LayoutProvider }diff --git a/apps/v4/lib/events.ts b/apps/v4/lib/events.tsindex 40f866d..a297549 100644--- a/apps/v4/lib/events.ts+++ b/apps/v4/lib/events.ts@@ -14,7 +14,6 @@ const eventSchema = z.object({"copy_chart_theme","copy_chart_data","copy_color",- "set_layout","search_query","create_app","copy_create_share_url",diff --git a/apps/v4/next.config.mjs b/apps/v4/next.config.mjsindex 40a85ee..0a99d1a 100644--- a/apps/v4/next.config.mjs+++ b/apps/v4/next.config.mjs@@ -9,6 +9,7 @@ const nextConfig = {basePath,assetPrefix,devIndicators: false,+ reactCompiler: true,typescript: {ignoreBuildErrors: true,},diff --git a/apps/v4/package.json b/apps/v4/package.jsonindex dc157a5..1ac4d96 100644--- a/apps/v4/package.json+++ b/apps/v4/package.json@@ -73,6 +73,7 @@"@types/papaparse": "^5.5.2","@types/react": "19.2.2","@types/react-dom": "19.2.2",+ "babel-plugin-react-compiler": "^1.0.0","eslint": "^9","eslint-config-next": "16.2.9","prettier": "^3.4.2",diff --git a/apps/v4/registry.json b/apps/v4/registry.jsonindex e6bddea..1daedd5 100644--- a/apps/v4/registry.json+++ b/apps/v4/registry.json@@ -558,12 +558,17 @@],"registryDependencies": ["button",+ "command","dialog","@extend/docx-viewer",+ "dropdown-menu","@extend/file-thumbnail",+ "input","@extend/pdf-viewer",+ "popover","scroll-area","select",+ "spinner","tabs","utils","@extend/xlsx-viewer"diff --git a/apps/v4/registry/new-york-v4/blocks/layout-blocks-block.tsx b/apps/v4/registry/new-york-v4/blocks/layout-blocks-block.tsxindex 694d372..85e674a 100644--- a/apps/v4/registry/new-york-v4/blocks/layout-blocks-block.tsx+++ b/apps/v4/registry/new-york-v4/blocks/layout-blocks-block.tsx@@ -59,6 +59,21 @@ export function OcrBlocksBlock({)}, [])+ const activeOverlayBlockId = activeBlock?.id+ const renderPageOverlay = React.useCallback(+ ({ pageNumber }: { pageNumber: number }) =>+ blocks+ .filter((block) => block.page === pageNumber)+ .map((block) => (+ <OcrBlockOverlay+ key={block.id}+ block={block}+ isActive={block.id === activeOverlayBlockId}+ />+ )),+ [activeOverlayBlockId, blocks]+ )+return (<PdfBlockResizableShellautoSaveId="pdf-block-ocr"@@ -67,17 +82,7 @@ export function OcrBlocksBlock({ref={viewerRef}file={file}defaultZoom={1}- renderPageOverlay={({ pageNumber }) =>- blocks- .filter((block) => block.page === pageNumber)- .map((block) => (- <OcrBlockOverlay- key={block.id}- block={block}- isActive={block.id === activeBlock?.id}- />- ))- }+ renderPageOverlay={renderPageOverlay}/>}right={diff --git a/apps/v4/registry/new-york-v4/ui/input.tsx b/apps/v4/registry/new-york-v4/ui/input.tsxindex 5769242..2e04873 100644--- a/apps/v4/registry/new-york-v4/ui/input.tsx+++ b/apps/v4/registry/new-york-v4/ui/input.tsx@@ -38,7 +38,7 @@ export function Input({className={cn(!unstyled &&- "relative inline-flex w-full rounded-lg border border-input bg-background text-base text-foreground shadow-xs/5 ring-ring/24 transition-shadow not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-has-disabled:not-has-focus-visible:not-has-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] has-autofill:bg-foreground/4 has-focus-visible:border-ring has-focus-visible:ring-[3px] has-disabled:opacity-64 has-aria-invalid:border-destructive/36 has-focus-visible:has-aria-invalid:border-destructive/64 has-focus-visible:has-aria-invalid:ring-destructive/16 has-[:disabled,:focus-visible,[aria-invalid]]:shadow-none sm:text-sm dark:bg-input/32 dark:not-has-disabled:not-has-focus-visible:not-has-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)] dark:has-autofill:bg-foreground/8 dark:has-aria-invalid:ring-destructive/24",+ "relative inline-flex w-full rounded-lg border border-input bg-popover text-base text-foreground shadow-xs/5 ring-ring/24 transition-shadow not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-has-disabled:not-has-focus-visible:not-has-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] has-autofill:bg-foreground/4 has-focus-visible:border-ring has-focus-visible:ring-[3px] has-disabled:opacity-64 has-aria-invalid:border-destructive/36 has-focus-visible:has-aria-invalid:border-destructive/64 has-focus-visible:has-aria-invalid:ring-destructive/16 has-[:disabled,:focus-visible,[aria-invalid]]:shadow-none sm:text-sm dark:bg-input/32 dark:not-has-disabled:not-has-focus-visible:not-has-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)] dark:has-autofill:bg-foreground/8 dark:has-aria-invalid:ring-destructive/24",className) || undefined}diff --git a/apps/v4/registry/new-york-v4/ui/layout-blocks.tsx b/apps/v4/registry/new-york-v4/ui/layout-blocks.tsxindex 6e33524..4d7be90 100644--- a/apps/v4/registry/new-york-v4/ui/layout-blocks.tsx+++ b/apps/v4/registry/new-york-v4/ui/layout-blocks.tsx@@ -8106,7 +8106,11 @@ export function blockToArea(block: OcrBlock): React.CSSProperties {}}-function OcrBlockMarkdown({ text }: { text: string }) {+const OcrBlockMarkdown = React.memo(function OcrBlockMarkdown({+ text,+}: {+ text: string+}) {const markdown = text.replace(OCR_MARKDOWN_FIGURE_CAPTION_PATTERN, (tag) =>tag.startsWith("</") ? "</figcaption>" : "<figcaption>")@@ -8164,9 +8168,9 @@ function OcrBlockMarkdown({ text }: { text: string }) {</ReactMarkdown></div>)-}+})-function OcrBlockButton({+const OcrBlockButton = React.memo(function OcrBlockButton({block,isActive,onFocusBlock,@@ -8213,9 +8217,9 @@ function OcrBlockButton({</div></button>)-}+})-export function OcrBlockOverlay({+export const OcrBlockOverlay = React.memo(function OcrBlockOverlay({block,isActive,}: {@@ -8233,7 +8237,7 @@ export function OcrBlockOverlay({style={blockToArea(block)}/>)-}+})export function OcrBlocksPanel({activeBlockId,@@ -8254,6 +8258,12 @@ export function OcrBlocksPanel({const focusedBlockId = activeBlockId ?? localActiveBlockIdconst activeBlock =blocks.find((block) => block.id === focusedBlockId) ?? firstBlock+ const focusedBlockIdRef = React.useRef(focusedBlockId)++ React.useEffect(() => {+ focusedBlockIdRef.current = focusedBlockId+ }, [focusedBlockId])+const estimateBlockSize = React.useCallback((index: number) => {const block = blocks[index]@@ -8268,17 +8278,18 @@ export function OcrBlocksPanel({estimateSize: estimateBlockSize,getItemKey: (index) => blocks[index]?.id ?? index,getScrollElement: () => scrollViewportRef.current,- overscan: 12,+ overscan: 6,})const focusBlock = React.useCallback((block: OcrBlock) => {- if (block.id === focusedBlockId) return+ if (block.id === focusedBlockIdRef.current) return+ focusedBlockIdRef.current = block.idsetLocalActiveBlockId(block.id)onBlockFocus?.(block)},- [focusedBlockId, onBlockFocus]+ [onBlockFocus])React.useEffect(() => {diff --git a/apps/v4/registry/new-york-v4/ui/schema-builder.tsx b/apps/v4/registry/new-york-v4/ui/schema-builder.tsxindex 14367ed..eb0cf6d 100644--- a/apps/v4/registry/new-york-v4/ui/schema-builder.tsx+++ b/apps/v4/registry/new-york-v4/ui/schema-builder.tsx@@ -1121,6 +1121,24 @@ function useSchemaBuilderSensors() {)}+function useStableCallback<Args extends unknown[], Result>(+ callback: (...args: Args) => Result+) {+ const callbackRef = React.useRef(callback)++ React.useInsertionEffect(() => {+ callbackRef.current = callback+ })++ return React.useCallback((...args: Args) => callbackRef.current(...args), [])+}++function useStableIds(ids: string[]) {+ const idsKey = JSON.stringify(ids)++ return React.useMemo(() => JSON.parse(idsKey) as string[], [idsKey])+}+function getTypeStyleKey(property: SchemaBuilderProperty): SchemaBuilderTypeStyleKey {@@ -1383,18 +1401,14 @@ function EnumEditor({}) {const sensors = useSchemaBuilderSensors()const dndContextId = React.useId()- const sortableItems = React.useMemo(- () => values.map((value) => value.id),- [values]- )- const updateValue = React.useCallback(+ const sortableItems = useStableIds(values.map((value) => value.id))+ const updateValue = useStableCallback((id: string,update: (value: SchemaBuilderEnumValue) => SchemaBuilderEnumValue) => {onChange(values.map((value) => (value.id === id ? update(value) : value)))- },- [onChange, values]+ })const handleDragEnd = React.useCallback((event: DragEndEvent) => {@@ -1461,7 +1475,7 @@ function EnumEditor({)}-function SortableEnumRow({+const SortableEnumRow = React.memo(function SortableEnumRow({value,onValueChange,}: {@@ -1537,7 +1551,7 @@ function SortableEnumRow({</td></tr>)-}+})function ArrayItemsEditor({property,@@ -1674,18 +1688,13 @@ function SchemaBuilderTable({containerId,},})- const sortableItems = React.useMemo(- () => properties.map((property) => property.id),- [properties]- )- const updateProperty = React.useCallback(- (- id: string,- update: (property: SchemaBuilderProperty) => SchemaBuilderProperty- ) => {- onPropertiesChange(updatePropertyById(properties, id, update))- },- [onPropertiesChange, properties]+ const sortableItems = useStableIds(properties.map((property) => property.id))+ const updateProperty = useStableCallback(+ (id: string, nextProperty: SchemaBuilderProperty) => {+ onPropertiesChange(+ updatePropertyById(properties, id, () => nextProperty)+ )+ })const addProperty = React.useCallback(() => {@@ -1731,9 +1740,7 @@ function SchemaBuilderTable({dropPreview={dropPreview}nestedEditorOpenByPropertyId={nestedEditorOpenByPropertyId}onNestedEditorOpenChange={onNestedEditorOpenChange}- onPropertyChange={(nextProperty) =>- updateProperty(property.id, () => nextProperty)- }+ onPropertyChange={updateProperty}/></React.Fragment>))}@@ -1762,7 +1769,7 @@ function SchemaBuilderTable({)}-function SortablePropertyRows({+const SortablePropertyRows = React.memo(function SortablePropertyRows({property,depth,dropPreview,@@ -1775,7 +1782,7 @@ function SortablePropertyRows({dropPreview: PropertyMovePreview | nullnestedEditorOpenByPropertyId: Record<string, boolean>onNestedEditorOpenChange: (propertyId: string, open: boolean) => void- onPropertyChange: (property: SchemaBuilderProperty) => void+ onPropertyChange: (id: string, property: SchemaBuilderProperty) => void}) {const {attributes,@@ -1790,6 +1797,12 @@ function SortablePropertyRows({type: SCHEMA_PROPERTY_DRAG_TYPE,},})+ const handlePropertyChange = React.useCallback(+ (nextProperty: SchemaBuilderProperty) => {+ onPropertyChange(nextProperty.id, nextProperty)+ },+ [onPropertyChange]+ )const hasNestedEditor = propertyHasNestedEditor(property)const isNestedEditorOpen = nestedEditorOpenByPropertyId[property.id] ?? trueconst nestedEditorLabel = getNestedEditorLabel(property)@@ -1831,7 +1844,7 @@ function SortablePropertyRows({className="font-mono"spellCheck={false}onChange={(event) =>- onPropertyChange({+ handlePropertyChange({...property,key: event.target.value,})@@ -1840,14 +1853,17 @@ function SortablePropertyRows({</div></td><td className="border-l p-1 align-top">- <SchemaTypeMenu property={property} onChange={onPropertyChange} />+ <SchemaTypeMenu+ property={property}+ onChange={handlePropertyChange}+ /></td><td className="border-l p-0 align-top"><InlineTextInputvalue={property.description}placeholder="Describe what this field should extract."onChange={(event) =>- onPropertyChange({+ handlePropertyChange({...property,description: event.target.value,})@@ -1882,7 +1898,7 @@ function SortablePropertyRows({<div className="flex h-full shrink-0 items-center px-2"><ArrayItemTypeMenuproperty={property}- onChange={onPropertyChange}+ onChange={handlePropertyChange}/></div>) : null}@@ -1904,7 +1920,7 @@ function SortablePropertyRows({dropPreview={dropPreview}nestedEditorOpenByPropertyId={nestedEditorOpenByPropertyId}onNestedEditorOpenChange={onNestedEditorOpenChange}- onChange={onPropertyChange}+ onChange={handlePropertyChange}/></div></CollapsiblePanel>@@ -1914,7 +1930,7 @@ function SortablePropertyRows({) : null}</tbody>)-}+})function SchemaPropertyDropPreviewRows({property,@@ -2146,7 +2162,7 @@ function SchemaPropertiesPreview({)}-export function SchemaJsonView({+export const SchemaJsonView = React.memo(function SchemaJsonView({scrollResetKey = 0,schema,theme,@@ -2201,7 +2217,7 @@ export function SchemaJsonView({</WorkerPoolContextProvider></div>)-}+})export function SchemaBuilderPanel({className,@@ -2232,6 +2248,15 @@ export function SchemaBuilderPanel({const [uncontrolledSchema, setUncontrolledSchema] =React.useState(defaultSchema)const schema = controlledSchema ?? uncontrolledSchema+ // The JSON tab stays mounted, so feed it a schema frozen while it is+ // hidden; otherwise every form keystroke re-serializes and re-highlights+ // the code view. Syncing during render keeps it fresh once visible.+ const [jsonViewSchema, setJsonViewSchema] = React.useState(schema)++ if (activeTab === "json" && jsonViewSchema !== schema) {+ setJsonViewSchema(schema)+ }+const dropPreview = React.useMemo(() => {if (!activeSchemaDrag?.overId) return null@@ -2539,7 +2564,7 @@ export function SchemaBuilderPanel({<TabsContent value="json" keepMounted className="min-h-0 flex-1"><SchemaJsonViewscrollResetKey={jsonScrollResetKey}- schema={schema}+ schema={jsonViewSchema}theme={theme}/></TabsContent>diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c9e1fcb..7787011 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -62,7 +62,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])+ version: 2.0.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])border-beam:specifier: ^1.0.1@@ -77,10 +77,10 @@ importers:version: 1.1.1(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])fumadocs-core:specifier: 16.0.5- version: 16.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 16.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])fumadocs-mdx:specifier: 13.0.2- version: 13.0.2([email protected](@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 13.0.2([email protected](@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))jotai:specifier: ^2.15.0version: 2.15.0(@babel/[email protected])(@babel/[email protected])(@types/[email protected])([email protected])@@ -95,13 +95,13 @@ importers:version: 16.4.2next:specifier: 16.2.9- version: 16.2.9(@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ version: 16.2.9(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])next-themes:specifier: 0.4.6nuqs:specifier: ^2.8.9- version: 2.8.9([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 2.8.9([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])papaparse:specifier: ^5.5.3version: 5.5.3@@ -178,6 +178,9 @@ importers:'@types/react-dom':specifier: 19.2.2version: 19.2.2(@types/[email protected])+ babel-plugin-react-compiler:+ specifier: ^1.0.0+ version: 1.0.0eslint:specifier: ^9version: 9.26.0([email protected])([email protected])@@ -410,10 +413,6 @@ packages:resolution: {integrity: sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ==}engines: {node: '>=6.9.0'}- '@babel/[email protected]':- resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==}- engines: {node: '>=6.9.0'}-'@babel/[email protected]':resolution: {integrity: sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==}engines: {node: '>=6.9.0'}@@ -2231,6 +2230,9 @@ packages:resolution: {integrity: sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-Ixm8tFfoKKIPYdCCKYTsqv+Fd4IJ0DQqMyEimo+pxUOMUR9cVPlwTrFt9Avu+3cb6Zp3mAzl+t1MrG2fxxKsxw==}+resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==}@@ -5247,7 +5249,7 @@ snapshots:'@babel/parser': 7.28.0'@babel/template': 7.27.2'@babel/traverse': 7.28.0- '@babel/types': 7.28.2+ '@babel/types': 7.29.7convert-source-map: 2.0.0debug: 4.4.3gensync: 1.0.0-beta.2@@ -5267,7 +5269,7 @@ snapshots:'@babel/[email protected]':dependencies:'@babel/parser': 7.29.7- '@babel/types': 7.29.0+ '@babel/types': 7.29.7'@jridgewell/gen-mapping': 0.3.13'@jridgewell/trace-mapping': 0.3.31jsesc: 3.1.0@@ -5319,7 +5321,7 @@ snapshots:'@babel/[email protected]':dependencies:'@babel/traverse': 7.28.0- '@babel/types': 7.28.2+ '@babel/types': 7.29.7transitivePeerDependencies:- supports-color@@ -5387,7 +5389,7 @@ snapshots:'@babel/[email protected]':dependencies:'@babel/template': 7.27.2- '@babel/types': 7.28.2+ '@babel/types': 7.29.7'@babel/[email protected]':dependencies:@@ -5395,7 +5397,7 @@ snapshots:'@babel/[email protected]':dependencies:- '@babel/types': 7.29.0+ '@babel/types': 7.29.7'@babel/[email protected]':dependencies:@@ -5484,11 +5486,6 @@ snapshots:'@babel/helper-string-parser': 7.27.1'@babel/helper-validator-identifier': 7.27.1- '@babel/[email protected]':- dependencies:- '@babel/helper-string-parser': 7.27.1- '@babel/helper-validator-identifier': 7.28.5-'@babel/[email protected]':dependencies:'@babel/helper-string-parser': 7.29.7@@ -6912,9 +6909,9 @@ 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])':+ '@vercel/[email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])':optionalDependencies:- next: 16.2.9(@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ next: 16.2.9(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])react: 19.2.3'@wyw-in-js/[email protected]':@@ -7066,6 +7063,10 @@ snapshots:+ dependencies:+ '@babel/types': 7.29.7+@@ -8052,7 +8053,7 @@ snapshots:optional: true- [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):dependencies:'@formatjs/intl-localematcher': 0.6.2'@orama/orama': 3.1.16@@ -8074,20 +8075,20 @@ snapshots:optionalDependencies:'@types/react': 19.2.2lucide-react: 0.474.0([email protected])- next: 16.2.9(@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ next: 16.2.9(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])react: 19.2.3react-dom: 19.2.3([email protected])transitivePeerDependencies:- supports-color- [email protected]([email protected](@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected]([email protected](@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@mdx-js/mdx': 3.1.1'@standard-schema/spec': 1.1.0chokidar: 4.0.3esbuild: 0.25.11estree-util-value-to-estree: 3.5.0- fumadocs-core: 16.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ fumadocs-core: 16.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])js-yaml: 4.1.1lru-cache: 11.2.4mdast-util-to-markdown: 2.1.2@@ -8101,7 +8102,7 @@ snapshots:unist-util-visit: 5.0.0zod: 4.3.6optionalDependencies:- next: 16.2.9(@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ next: 16.2.9(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])react: 19.2.3vite: 7.3.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:@@ -9265,7 +9266,7 @@ snapshots:react: 19.2.3react-dom: 19.2.3([email protected])- [email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]):+ [email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]):dependencies:'@next/env': 16.2.9'@swc/helpers': 0.5.15@@ -9285,6 +9286,7 @@ snapshots:'@next/swc-win32-arm64-msvc': 16.2.9'@next/swc-win32-x64-msvc': 16.2.9'@opentelemetry/api': 1.9.0+ babel-plugin-react-compiler: 1.0.0sharp: 0.34.5transitivePeerDependencies:- '@babel/core'@@ -9311,12 +9313,12 @@ snapshots:- [email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]):+ [email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]):dependencies:'@standard-schema/spec': 1.0.0react: 19.2.3optionalDependencies:- next: 16.2.9(@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ next: 16.2.9(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])