TypeScript
Stabilize file thumbnail loading layout
Andrew Luo2f27824501fa
diff --git a/apps/v4/.tmp/pdf-viewer-current-page-rotated.pdf b/apps/v4/.tmp/pdf-viewer-current-page-rotated.pdfnew file mode 100644index 0000000..edd8da7Binary files /dev/null and b/apps/v4/.tmp/pdf-viewer-current-page-rotated.pdf differdiff --git a/apps/v4/app/api/block-code/route.ts b/apps/v4/app/api/block-code/route.tsnew file mode 100644index 0000000..97aa1a1--- /dev/null+++ b/apps/v4/app/api/block-code/route.ts@@ -0,0 +1,24 @@+import { NextResponse } from "next/server"++import { getLoadedBlockCodeFile } from "@/lib/block-code-samples"++export async function GET(request: Request) {+ const { searchParams } = new URL(request.url)+ const blockId = searchParams.get("block")+ const targetPath = searchParams.get("file")++ if (!blockId || !targetPath) {+ return NextResponse.json(+ { error: "Missing block or file parameter." },+ { status: 400 }+ )+ }++ const file = await getLoadedBlockCodeFile({ blockId, targetPath })++ if (!file) {+ return NextResponse.json({ error: "File not found." }, { status: 404 })+ }++ return NextResponse.json(file)+}diff --git a/apps/v4/components/document-splitter-docs.tsx b/apps/v4/components/document-splitter-docs.tsxindex 8d159fc..9645a8a 100644--- a/apps/v4/components/document-splitter-docs.tsx+++ b/apps/v4/components/document-splitter-docs.tsx@@ -273,7 +273,6 @@ const PageThumbnailPreview = React.memo(function PageThumbnailPreview({itemId,itemLabel,labelPlacement,- isActive,imageUrl,thumbnailSize,onSelect,@@ -282,7 +281,6 @@ const PageThumbnailPreview = React.memo(function PageThumbnailPreview({itemId: DocumentSplitItemIditemLabel: React.ReactNodelabelPlacement: ThumbnailLabelPlacement- isActive: booleanimageUrl?: stringthumbnailSize: ThumbnailSizeonSelect: (itemId: DocumentSplitItemId) => void@@ -294,12 +292,7 @@ const PageThumbnailPreview = React.memo(function PageThumbnailPreview({><buttontype="button"- className={cn(- "relative cursor-grab overflow-hidden rounded-md border bg-muted text-left shadow-xs transition-[border-color,box-shadow,opacity] active:cursor-grabbing",- isActive- ? "border-blue-500 shadow-[0_0_0_2px_rgb(59_130_246_/_14%)]"- : "border-border hover:border-foreground/30"- )}+ className="relative cursor-grab overflow-hidden rounded-md border border-border bg-muted text-left shadow-xs transition-[border-color,opacity] hover:border-foreground/30 active:cursor-grabbing"style={{ width: thumbnailSize.width, height: thumbnailSize.height }}onClick={() => onSelect(itemId)}>@@ -313,7 +306,7 @@ const PageThumbnailPreview = React.memo(function PageThumbnailPreview({/><spanclassName={cn(- "absolute bottom-1 rounded bg-background/90 px-1.5 py-0.5 text-[10px] font-medium shadow-xs",+ "absolute bottom-1 rounded bg-background/95 px-1.5 py-0.5 text-[10px] font-semibold text-foreground shadow-xs ring-1 ring-border/80",labelPlacement === "bottom"? "inset-x-1 truncate": "right-1 max-w-[calc(100%-0.5rem)]"@@ -332,7 +325,6 @@ function SortablePageThumbnail({groupId,pageId,labelPlacement,- isActive,imageUrl,thumbnailSize,onSelect,@@ -342,7 +334,6 @@ function SortablePageThumbnail({groupId: stringpageId: PageIdlabelPlacement: ThumbnailLabelPlacement- isActive: booleanimageUrl?: stringthumbnailSize: ThumbnailSizeonSelect: (itemId: DocumentSplitItemId) => void@@ -379,7 +370,6 @@ function SortablePageThumbnail({itemId={pageId}itemLabel={getItemLabel(pageId)}labelPlacement={labelPlacement}- isActive={isActive}imageUrl={imageUrl}thumbnailSize={thumbnailSize}onSelect={onSelect}@@ -389,7 +379,6 @@ function SortablePageThumbnail({}function SplitGroupCard({- activeItemId,emptyLabel,getItemFile,getItemLabel,@@ -405,7 +394,6 @@ function SplitGroupCard({onRemove,onSelectItem,}: {- activeItemId?: DocumentSplitItemIdemptyLabel: stringgetItemFile: (itemId: DocumentSplitItemId) => ThumbnailFilegetItemLabel: (itemId: DocumentSplitItemId) => React.ReactNode@@ -490,7 +478,6 @@ function SplitGroupCard({groupId={group.id}pageId={pageId}labelPlacement={labelPlacement}- isActive={activeItemId === pageId}imageUrl={thumbnailImages?.[pageId]}thumbnailSize={thumbnailSize}onSelect={onSelectItem}@@ -564,7 +551,7 @@ function PageDragOverlay({}) {return (<div- className="relative overflow-hidden rounded-md border border-blue-500 bg-background shadow-lg shadow-black/10"+ className="relative overflow-hidden rounded-md border border-border bg-background shadow-lg shadow-black/10"style={{ width: thumbnailSize.width, height: thumbnailSize.height }}><FileThumbnail@@ -577,7 +564,7 @@ function PageDragOverlay({/><spanclassName={cn(- "absolute bottom-1 rounded bg-background/90 px-1.5 py-0.5 text-[10px] font-medium shadow-xs",+ "absolute bottom-1 rounded bg-background/95 px-1.5 py-0.5 text-[10px] font-semibold text-foreground shadow-xs ring-1 ring-border/80",labelPlacement === "bottom"? "inset-x-1 truncate": "right-1 max-w-[calc(100%-0.5rem)]"@@ -623,27 +610,27 @@ function getGroupPages(groups: SplitGroup[], groupId: string | null) {}function movePageToGroup({- activePageId,+ draggedPageId,groups,insertIndex,targetGroupId,}: {- activePageId: PageId+ draggedPageId: PageIdgroups: SplitGroup[]insertIndex: numbertargetGroupId: string}) {return groups.map((group) => {- const pagesWithoutActive = group.pages.filter(- (pageId) => pageId !== activePageId+ const pagesWithoutDragged = group.pages.filter(+ (pageId) => pageId !== draggedPageId)if (group.id !== targetGroupId) {- return { ...group, pages: pagesWithoutActive }+ return { ...group, pages: pagesWithoutDragged }}- const nextPages = [...pagesWithoutActive]- nextPages.splice(insertIndex, 0, activePageId)+ const nextPages = [...pagesWithoutDragged]+ nextPages.splice(insertIndex, 0, draggedPageId)return { ...group, pages: nextPages }})}@@ -668,24 +655,24 @@ function areSplitGroupsEqual(left: SplitGroup[], right: SplitGroup[]) {}function reorderPageInGroup({- activePageId,+ draggedPageId,groups,overPageId,}: {- activePageId: PageId+ draggedPageId: PageIdgroups: SplitGroup[]overPageId: PageId}) {- const groupId = findGroupId(groups, activePageId)+ const groupId = findGroupId(groups, draggedPageId)const pages = getGroupPages(groups, groupId)- const activeIndex = pages.indexOf(activePageId)+ const draggedIndex = pages.indexOf(draggedPageId)const overIndex = pages.indexOf(overPageId)- if (!groupId || activeIndex === -1 || overIndex === -1) return groups+ if (!groupId || draggedIndex === -1 || overIndex === -1) return groupsreturn groups.map((group) =>group.id === groupId- ? { ...group, pages: arrayMove(group.pages, activeIndex, overIndex) }+ ? { ...group, pages: arrayMove(group.pages, draggedIndex, overIndex) }: group)}@@ -729,8 +716,6 @@ function useWorkbookSheetThumbnailUrls(workbookIdentity: string) {}export function DocumentSplits({- activeItemId,- activePage,addSplitLabel = "Add split",className,dndId = "document-splits-dnd",@@ -749,8 +734,6 @@ export function DocumentSplits({onAddSplit,onRemoveSplit,}: {- activeItemId?: DocumentSplitItemId- activePage?: numberaddSplitLabel?: stringclassName?: stringdndId?: string@@ -769,7 +752,7 @@ export function DocumentSplits({onAddSplit?: () => voidonRemoveSplit?: (groupId: string) => void}) {- const [activePageId, setActivePageId] = React.useState<PageId | null>(null)+ const [draggedPageId, setDraggedPageId] = React.useState<PageId | null>(null)const [activeSplitGroupId, setActiveSplitGroupId] = React.useState<string | null>(null)@@ -788,8 +771,6 @@ export function DocumentSplits({() => createPageRangeLabels(splits),[splits])- const resolvedActiveItemId =- activeItemId ?? (activePage ? toPageId(activePage) : undefined)const resolvedGetItemLabel = React.useCallback((itemId: DocumentSplitItemId) =>getItemLabel?.(itemId) ?? getPageNumber(itemId),@@ -879,7 +860,7 @@ export function DocumentSplits({const pageId = String(event.active.id) as PageIddragStartGroupIdRef.current = findGroupId(splits, pageId)dragStartGroupsRef.current = splits- setActivePageId(pageId)+ setDraggedPageId(pageId)setActiveSplitGroupId(null)setActiveSplitGroupWidth(undefined)return@@ -888,7 +869,7 @@ export function DocumentSplits({if (dragType === "split") {dragStartGroupIdRef.current = nulldragStartGroupsRef.current = null- setActivePageId(null)+ setDraggedPageId(null)setActiveSplitGroupId((event.active.data.current?.groupId as string | undefined) ?? null)@@ -898,7 +879,7 @@ export function DocumentSplits({dragStartGroupIdRef.current = nulldragStartGroupsRef.current = null- setActivePageId(null)+ setDraggedPageId(null)setActiveSplitGroupId(null)setActiveSplitGroupWidth(undefined)},@@ -942,7 +923,7 @@ export function DocumentSplits({return movePageToGroup({groups: previousSplits,- activePageId: pageId,+ draggedPageId: pageId,targetGroupId,insertIndex,})@@ -965,21 +946,21 @@ export function DocumentSplits({| undefinedupdateSplits((previousSplits) => {- const activeIndex = previousSplits.findIndex(+ const draggedIndex = previousSplits.findIndex((group) => group.id === activeGroupId)const overIndex = previousSplits.findIndex((group) => group.id === overGroupId)- if (activeIndex === -1 || overIndex === -1) return previousSplits+ if (draggedIndex === -1 || overIndex === -1) return previousSplits- return arrayMove(previousSplits, activeIndex, overIndex)+ return arrayMove(previousSplits, draggedIndex, overIndex)})}if (dragType === "page" && overId) {- const activePageId = String(event.active.id) as PageId+ const draggedPageId = String(event.active.id) as PageIdconst overPageId = String(overId) as PageIdupdateSplits((previousSplits) => {@@ -991,7 +972,7 @@ export function DocumentSplits({return reorderPageInGroup({groups: previousSplits,- activePageId,+ draggedPageId,overPageId,})})@@ -999,7 +980,7 @@ export function DocumentSplits({dragStartGroupIdRef.current = nulldragStartGroupsRef.current = null- setActivePageId(null)+ setDraggedPageId(null)setActiveSplitGroupId(null)setActiveSplitGroupWidth(undefined)},@@ -1013,12 +994,12 @@ export function DocumentSplits({dragStartGroupIdRef.current = nulldragStartGroupsRef.current = null- setActivePageId(null)+ setDraggedPageId(null)setActiveSplitGroupId(null)setActiveSplitGroupWidth(undefined)}, [onSplitsChange])- const isPageDragging = activePageId !== null+ const isPageDragging = draggedPageId !== nullconst activeSplitGroup = activeSplitGroupId? splits.find((group) => group.id === activeSplitGroupId): null@@ -1055,9 +1036,6 @@ export function DocumentSplits({{splits.map((group) => (<SortableSplitGroupCardkey={group.id}- activeItemId={- activePageId ? activePageId : resolvedActiveItemId- }emptyLabel={emptyLabel}getItemFile={resolvedGetItemFile}getItemLabel={resolvedGetItemLabel}@@ -1080,18 +1058,17 @@ export function DocumentSplits({</SortableContext></ScrollArea><DragOverlay dropAnimation={DRAG_OVERLAY_DROP_ANIMATION} zIndex={1000}>- {activePageId ? (+ {draggedPageId ? (<PageDragOverlaygetItemFile={resolvedGetItemFile}getItemLabel={resolvedGetItemLabel}labelPlacement={labelPlacement}- pageId={activePageId}- imageUrl={thumbnailImages[activePageId]}+ pageId={draggedPageId}+ imageUrl={thumbnailImages[draggedPageId]}thumbnailSize={thumbnailSize}/>) : activeSplitGroup ? (<SplitGroupDragOverlay- activeItemId={resolvedActiveItemId}emptyLabel={emptyLabel}getItemFile={resolvedGetItemFile}getItemLabel={resolvedGetItemLabel}@@ -1298,7 +1275,6 @@ function WorkbookSplitsPane({return (<DocumentSplits- activeItemId={toWorkbookSheetId(activeSheetIndex)}addSplitLabel="Add split"className={className}dndId="workbook-document-splits-dnd"@@ -1362,7 +1338,6 @@ export function DocumentSplitsBlock() {const [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null)const [pdfUrl, setPdfUrl] = React.useState(PDF_URL)const [numPages, setNumPages] = React.useState(0)- const [activePage, setActivePage] = React.useState(1)const [splits, setSplits] = React.useState<SplitGroup[]>(() =>createInitialGroups(DEFAULT_PREVIEW_PAGE_COUNT))@@ -1405,14 +1380,6 @@ export function DocumentSplitsBlock() {[])- const handleActivePageChange = React.useCallback((pageNumber: number) => {- window.queueMicrotask(() => {- setActivePage((currentPage) =>- currentPage === pageNumber ? currentPage : pageNumber- )- })- }, [])-const handlePdfUpload = React.useCallback((file: File) => {const nextUrl = URL.createObjectURL(file)@@ -1423,12 +1390,9 @@ export function DocumentSplitsBlock() {uploadedPdfUrlRef.current = nextUrlsetPdfUrl(nextUrl)setNumPages(0)- setActivePage(1)}, [])const scrollToPage = React.useCallback((pageNumber: number) => {- setActivePage(pageNumber)-viewerRef.current?.scrollToPage(pageNumber, {block: "start",behavior: "auto",@@ -1453,14 +1417,12 @@ export function DocumentSplitsBlock() {ref={viewerRef}file={pdfUrl}defaultZoom={DEFAULT_ZOOM}- onActivePageChange={handleActivePageChange}onPdfUpload={handlePdfUpload}onDocumentLoadSuccess={updatePageCountFromViewer}/>}right={<DocumentSplits- activePage={activePage}splits={splits}thumbnailImages={thumbnailImages}withFrameDivider={false}@@ -1500,12 +1462,10 @@ export function DocumentSplitsBlock() {function DocumentSplitExampleCard({title,pages,- activePage,className,}: {title: stringpages: number[]- activePage?: numberclassName?: string}) {return (@@ -1539,14 +1499,10 @@ function DocumentSplitExampleCard({<buttonkey={page}type="button"- className={cn(- "relative h-[92px] w-[72px] shrink-0 overflow-hidden rounded-md border bg-muted text-xs text-muted-foreground transition-colors hover:border-primary/50",- activePage === page &&- "border-primary bg-primary/5 text-primary"- )}+ className="relative h-[92px] w-[72px] shrink-0 overflow-hidden rounded-md border border-border bg-muted text-xs text-foreground transition-colors hover:border-foreground/30"><div className="absolute inset-2 rounded-sm bg-background/70 shadow-sm" />- <span className="absolute right-1.5 bottom-1.5 rounded bg-background/90 px-1 text-[10px]">+ <span className="absolute right-1.5 bottom-1.5 rounded bg-background/95 px-1 text-[10px] font-semibold text-foreground shadow-xs ring-1 ring-border/80">{page}</span></button>@@ -1563,12 +1519,10 @@ function DocumentSplitsExample() {<DocumentSplitExampleCardtitle="Abstract and intro"pages={[1, 2, 3]}- activePage={2}/><DocumentSplitExampleCardtitle="Model architecture"pages={[4, 5, 6, 7, 8]}- className="border-blue-500/50 bg-blue-500/5"/><DocumentSplitExampleCardtitle="Training and results"@@ -1608,7 +1562,6 @@ function DocumentSplitsPreview({ file }: { file: string }) {const panel = (<DocumentSplits- activePage={1}className="h-[620px]"splits={splits}thumbnailImages={thumbnailImages}@@ -1862,7 +1815,6 @@ export function DocumentSplitsExample() {const panel = (<DocumentSplits- activePage={1}className="h-[620px]"splits={splits}thumbnailImages={thumbnailImages}@@ -1888,7 +1840,7 @@ export function DocumentSplitsExample() {}`const documentSplitterSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n closestCenter,\n DndContext,\n DragOverlay,\n PointerSensor,\n useDroppable,\n useSensor,\n useSensors,\n type CollisionDetection,\n type DragEndEvent,\n type DragOverEvent,\n type DragStartEvent,\n} from "@dnd-kit/core"\nimport {\n arrayMove,\n horizontalListSortingStrategy,\n SortableContext,\n useSortable,\n verticalListSortingStrategy,\n} from "@dnd-kit/sortable"\nimport { CSS } from "@dnd-kit/utilities"\nimport {\n Add01Icon,\n Delete02Icon,\n DragDropVerticalIcon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\n\nimport { cn } from "@/lib/utils"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"\nimport { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"\nimport { Button } from "@/registry/new-york-v4/ui/button"\nimport { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"\n\nexport type DocumentSplitPageId = `page-${number}`\nexport type DocumentSplit = {\n id: string\n title: string\n pages: DocumentSplitPageId[]\n}\n\ntype PageId = DocumentSplitPageId\ntype SplitGroup = DocumentSplit\n\nconst THUMBNAIL_WIDTH = 72\nconst THUMBNAIL_HEIGHT = 92\nconst DRAG_OVERLAY_DROP_ANIMATION = null\n\nconst splitterCollisionDetection: CollisionDetection = (args) => {\n const dragType = args.active.data.current?.type\n\n if (dragType === "page") {\n return closestCenter({\n ...args,\n droppableContainers: args.droppableContainers.filter(\n (container) =>\n container.data.current?.type === "page" ||\n (container.data.current?.type === "page-dropzone" &&\n container.data.current?.isEmpty)\n ),\n })\n }\n\n if (dragType === "split") {\n return closestCenter({\n ...args,\n droppableContainers: args.droppableContainers.filter(\n (container) => container.data.current?.type === "split"\n ),\n })\n }\n\n return closestCenter(args)\n}\n\nconst INITIAL_SPLITS: DocumentSplit[] = [\n {\n id: "split-1",\n title: "Abstract and intro",\n pages: ["page-1", "page-2", "page-3"],\n },\n {\n id: "split-2",\n title: "Model architecture",\n pages: ["page-4", "page-5", "page-6", "page-7"],\n },\n {\n id: "split-3",\n title: "Training and results",\n pages: ["page-8", "page-9", "page-10"],\n },\n]\n\nfunction createInitialSplits(pageCount: number) {\n if (pageCount <= 0) return INITIAL_SPLITS\n\n const pages = Array.from(\n { length: pageCount },\n (_, index) => `page-${index + 1}` as PageId\n )\n const chunkSize = Math.max(1, Math.ceil(pageCount / 3))\n\n return Array.from(\n { length: Math.ceil(pageCount / chunkSize) },\n (_, index) => {\n const startIndex = index * chunkSize\n const groupPages = pages.slice(startIndex, startIndex + chunkSize)\n const firstPage = getPageNumber(groupPages[0])\n const lastPage = getPageNumber(groupPages[groupPages.length - 1])\n\n return {\n id: `split-${index + 1}`,\n title:\n firstPage === lastPage\n ? `Page ${firstPage}`\n : `Pages ${firstPage}-${lastPage}`,\n pages: groupPages,\n }\n }\n )\n}\n\nfunction getPageNumber(pageId: PageId) {\n return Number(pageId.replace("page-", ""))\n}\n\nfunction getSplitSortableId(groupId: string) {\n return `split-sortable-${groupId}`\n}\n\nfunction findGroupId(groups: SplitGroup[], id: string) {\n if (groups.some((group) => group.id === id)) return id\n\n return groups.find((group) => group.pages.includes(id as PageId))?.id ?? null\n}\n\nfunction getGroupPages(groups: SplitGroup[], groupId: string | null) {\n return groups.find((group) => group.id === groupId)?.pages ?? []\n}\n\nfunction movePageToGroup({\n activePageId,\n groups,\n insertIndex,\n targetGroupId,\n}: {\n activePageId: PageId\n groups: SplitGroup[]\n insertIndex: number\n targetGroupId: string\n}) {\n return groups.map((group) => {\n const pagesWithoutActive = group.pages.filter(\n (pageId) => pageId !== activePageId\n )\n\n if (group.id !== targetGroupId) {\n return { ...group, pages: pagesWithoutActive }\n }\n\n const nextPages = [...pagesWithoutActive]\n nextPages.splice(insertIndex, 0, activePageId)\n\n return { ...group, pages: nextPages }\n })\n}\n\nfunction areSplitGroupsEqual(left: SplitGroup[], right: SplitGroup[]) {\n if (left === right) return true\n if (left.length !== right.length) return false\n\n return left.every((leftGroup, groupIndex) => {\n const rightGroup = right[groupIndex]\n if (!rightGroup) return false\n\n return (\n leftGroup.id === rightGroup.id &&\n leftGroup.title === rightGroup.title &&\n leftGroup.pages.length === rightGroup.pages.length &&\n leftGroup.pages.every(\n (pageId, pageIndex) => pageId === rightGroup.pages[pageIndex]\n )\n )\n })\n}\n\nfunction reorderPageInGroup({\n activePageId,\n groups,\n overPageId,\n}: {\n activePageId: PageId\n groups: SplitGroup[]\n overPageId: PageId\n}) {\n const groupId = findGroupId(groups, activePageId)\n const pages = getGroupPages(groups, groupId)\n const activeIndex = pages.indexOf(activePageId)\n const overIndex = pages.indexOf(overPageId)\n\n if (!groupId || activeIndex === -1 || overIndex === -1) return groups\n\n return groups.map((group) =>\n group.id === groupId\n ? {\n ...group,\n pages: arrayMove(group.pages, activeIndex, overIndex),\n }\n : group\n )\n}\n\nfunction createPageRangeLabel(pageIds: PageId[]) {\n if (pageIds.length === 0) return "No pages"\n\n return `Pages ${pageIds.map(getPageNumber).join(", ")}`\n}\n\nfunction SplitGroupDropzone({\n children,\n group,\n}: {\n children: React.ReactNode\n group: SplitGroup\n}) {\n const { isOver, setNodeRef } = useDroppable({\n id: group.id,\n data: { type: "page-dropzone", isEmpty: group.pages.length === 0 },\n })\n\n return (\n <div\n ref={setNodeRef}\n className={cn(\n "min-h-[116px] rounded-lg p-2 transition-[background-color,box-shadow]",\n isOver && "bg-accent/30 shadow-[inset_0_0_0_1px_var(--border)]"\n )}\n >\n {children}\n </div>\n )\n}\n\nfunction PageThumbnail({\n imageUrl,\n isActive,\n onSelect,\n pageId,\n}: {\n imageUrl?: string\n isActive: boolean\n onSelect: (pageNumber: number) => void\n pageId: PageId\n}) {\n const pageNumber = getPageNumber(pageId)\n const {\n attributes,\n isDragging,\n listeners,\n setNodeRef,\n transform,\n transition,\n } = useSortable({\n id: pageId,\n data: { type: "page" },\n })\n\n return (\n <button\n ref={setNodeRef}\n type="button"\n className={cn(\n "relative shrink-0 cursor-grab overflow-hidden rounded-md border bg-muted text-left shadow-xs transition-[border-color,box-shadow,opacity] active:cursor-grabbing",\n isActive\n ? "border-blue-500 shadow-[0_0_0_2px_rgb(59_130_246_/_14%)]"\n : "border-border hover:border-foreground/30",\n isDragging && "opacity-0"\n )}\n style={{\n width: THUMBNAIL_WIDTH,\n height: THUMBNAIL_HEIGHT,\n transform: CSS.Transform.toString(transform),\n transition,\n }}\n onClick={() => onSelect(pageNumber)}\n {...attributes}\n {...listeners}\n >\n <FileThumbnail\n file={{\n name: `page-${pageNumber}.pdf`,\n type: "application/pdf",\n size: `Page ${pageNumber}`,\n }}\n showMetadata={false}\n previewImageUrl={imageUrl}\n isLoading={!imageUrl}\n previewClassName="h-full aspect-auto"\n className="size-full rounded-[inherit] border-0"\n />\n <span className="absolute right-1 bottom-1 rounded bg-background/90 px-1.5 py-0.5 text-[10px] font-medium shadow-xs">\n {pageNumber}\n </span>\n </button>\n )\n}\n\nfunction SplitGroupCard({\n activePage,\n canRemove,\n group,\n dragHandleProps,\n thumbnailImages,\n onRemove,\n onSelectPage,\n}: {\n activePage: number\n canRemove: boolean\n group: SplitGroup\n dragHandleProps?: React.ComponentPropsWithoutRef<"button">\n thumbnailImages: Record<PageId, string>\n onRemove: () => void\n onSelectPage: (pageNumber: number) => void\n}) {\n return (\n <section className="w-full rounded-lg border bg-background">\n <div className="flex items-center justify-between gap-3 border-b p-3">\n <div className="flex min-w-0 items-center gap-2">\n <button\n type="button"\n aria-label={`Reorder ${group.title}`}\n className="inline-flex size-7 shrink-0 cursor-grab items-center justify-center rounded-md text-muted-foreground hover:bg-muted active:cursor-grabbing"\n {...dragHandleProps}\n >\n <HugeiconsIcon icon={DragDropVerticalIcon} className="size-4" />\n </button>\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">{group.title}</div>\n <div className="mt-1 text-xs text-muted-foreground">\n {createPageRangeLabel(group.pages)}\n </div>\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-2">\n <div className="rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">\n {group.pages.length}\n </div>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label={`Remove ${group.title}`}\n disabled={!canRemove}\n onClick={onRemove}\n >\n <HugeiconsIcon icon={Delete02Icon} className="size-4" />\n </Button>\n </div>\n </div>\n <SplitGroupDropzone group={group}>\n {group.pages.length ? (\n <SortableContext\n items={group.pages}\n strategy={horizontalListSortingStrategy}\n >\n <ScrollArea\n className="h-[110px] w-full overflow-hidden"\n orientation="horizontal"\n scrollbarGutter\n scrollbarOverflowOnly\n viewportClassName="overflow-y-hidden"\n >\n <div className="flex w-max gap-2 overflow-y-hidden py-1 pr-6">\n {group.pages.map((pageId) => (\n <PageThumbnail\n key={pageId}\n pageId={pageId}\n imageUrl={thumbnailImages[pageId]}\n isActive={activePage === getPageNumber(pageId)}\n onSelect={onSelectPage}\n />\n ))}\n </div>\n </ScrollArea>\n </SortableContext>\n ) : (\n <div className="grid h-[104px] place-items-center rounded-lg bg-muted/35 text-xs text-muted-foreground">\n Drop pages here\n </div>\n )}\n </SplitGroupDropzone>\n </section>\n )\n}\n\nfunction SortableSplitGroupCard({\n activePage,\n canRemove,\n group,\n thumbnailImages,\n onRemove,\n onSelectPage,\n}: {\n activePage: number\n canRemove: boolean\n group: SplitGroup\n thumbnailImages: Record<PageId, string>\n onRemove: () => void\n onSelectPage: (pageNumber: number) => void\n}) {\n const {\n attributes,\n isDragging,\n listeners,\n setNodeRef,\n transform,\n transition,\n } = useSortable({\n id: getSplitSortableId(group.id),\n data: { type: "split", groupId: group.id },\n })\n\n return (\n <div\n ref={setNodeRef}\n className={cn("w-full", isDragging && "opacity-0")}\n style={{\n transform: CSS.Transform.toString(transform),\n transition,\n }}\n >\n <SplitGroupCard\n activePage={activePage}\n canRemove={canRemove}\n group={group}\n thumbnailImages={thumbnailImages}\n dragHandleProps={{ ...attributes, ...listeners }}\n onRemove={onRemove}\n onSelectPage={onSelectPage}\n />\n </div>\n )\n}\n\nfunction SplitGroupDragOverlay({\n activePage,\n group,\n thumbnailImages,\n width,\n onSelectPage,\n}: {\n activePage: number\n group: SplitGroup\n thumbnailImages: Record<PageId, string>\n width?: number\n onSelectPage: (pageNumber: number) => void\n}) {\n return (\n <div\n className="relative z-[1000] max-w-[calc(100vw-2rem)]"\n style={{ width }}\n >\n <SplitGroupCard\n activePage={activePage}\n canRemove={false}\n group={group}\n thumbnailImages={thumbnailImages}\n onRemove={() => {}}\n onSelectPage={onSelectPage}\n />\n </div>\n )\n}\n\nexport function DocumentSplits({\n activePage,\n className,\n splits,\n thumbnailImages = {},\n withFrameDivider = true,\n onSelectPage,\n onSplitsChange,\n}: {\n activePage: number\n className?: string\n splits: SplitGroup[]\n thumbnailImages?: Record<PageId, string>\n withFrameDivider?: boolean\n onSelectPage: (pageNumber: number) => void\n onSplitsChange: (splits: SplitGroup[]) => void\n}) {\n const [activePageId, setActivePageId] = React.useState<PageId | null>(null)\n const [activeSplitGroupId, setActiveSplitGroupId] = React.useState<\n string | null\n >(null)\n const [activeSplitGroupWidth, setActiveSplitGroupWidth] = React.useState<\n number | undefined\n >()\n const dragStartGroupIdRef = React.useRef<string | null>(null)\n const dragStartSplitsRef = React.useRef<SplitGroup[] | null>(null)\n const sensors = useSensors(\n useSensor(PointerSensor, { activationConstraint: { distance: 6 } })\n )\n\n const handleDragStart = React.useCallback(\n (event: DragStartEvent) => {\n const dragType = event.active.data.current?.type\n\n if (dragType === "split") {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setActivePageId(null)\n setActiveSplitGroupId(\n (event.active.data.current?.groupId as string | undefined) ?? null\n )\n setActiveSplitGroupWidth(event.active.rect.current.initial?.width)\n return\n }\n\n if (dragType !== "page") {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setActivePageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n const pageId = String(event.active.id) as PageId\n dragStartGroupIdRef.current = findGroupId(splits, pageId)\n dragStartSplitsRef.current = splits\n setActivePageId(pageId)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n },\n [splits]\n )\n\n const handleDragOver = React.useCallback(\n (event: DragOverEvent) => {\n if (event.active.data.current?.type !== "page" || !event.over) return\n\n const pageId = String(event.active.id) as PageId\n const overId = String(event.over.id)\n\n const sourceGroupId = findGroupId(splits, pageId)\n const targetGroupId = findGroupId(splits, overId)\n\n if (!sourceGroupId || !targetGroupId || sourceGroupId === targetGroupId) {\n return\n }\n\n const targetPages = getGroupPages(splits, targetGroupId)\n const overIndex = targetPages.indexOf(overId as PageId)\n const insertIndex = overIndex === -1 ? targetPages.length : overIndex\n\n const nextSplits = movePageToGroup({\n activePageId: pageId,\n groups: splits,\n insertIndex,\n targetGroupId,\n })\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n },\n [onSplitsChange, splits]\n )\n\n const handleDragEnd = React.useCallback(\n (event: DragEndEvent) => {\n if (event.active.data.current?.type === "split" && event.over) {\n const activeGroupId = event.active.data.current.groupId\n const overGroupId = event.over.data.current?.groupId\n\n const activeIndex = splits.findIndex(\n (group) => group.id === activeGroupId\n )\n const overIndex = splits.findIndex((group) => group.id === overGroupId)\n\n if (activeIndex !== -1 && overIndex !== -1) {\n const nextSplits = arrayMove(splits, activeIndex, overIndex)\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n }\n\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setActivePageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n if (event.active.data.current?.type !== "page" || !event.over) {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setActivePageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n const pageId = String(event.active.id) as PageId\n const overId = String(event.over.id) as PageId\n const overGroupId = findGroupId(splits, overId)\n\n if (dragStartGroupIdRef.current === overGroupId) {\n const nextSplits = reorderPageInGroup({\n activePageId: pageId,\n groups: splits,\n overPageId: overId,\n })\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n }\n\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setActivePageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n },\n [onSplitsChange, splits]\n )\n\n const handleDragCancel = React.useCallback(() => {\n if (dragStartSplitsRef.current) {\n onSplitsChange(dragStartSplitsRef.current)\n }\n\n dragStartSplitsRef.current = null\n dragStartGroupIdRef.current = null\n setActivePageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n }, [onSplitsChange])\n\n const activeSplitGroup = activeSplitGroupId\n ? splits.find((group) => group.id === activeSplitGroupId)\n : null\n\n return (\n <aside\n className={cn(\n "flex h-full min-h-0 flex-col bg-muted/20",\n withFrameDivider && "border-t md:border-t-0 md:border-l",\n className\n )}\n >\n <div className="flex min-h-12 items-center justify-end gap-3 border-b bg-background px-3">\n <Button\n type="button"\n variant="outline"\n size="sm"\n onClick={() =>\n onSplitsChange([\n ...splits,\n {\n id: `split-${Date.now()}`,\n title: `Split ${splits.length + 1}`,\n pages: [],\n },\n ])\n }\n >\n <HugeiconsIcon icon={Add01Icon} className="size-4" />\n Add split\n </Button>\n </div>\n <DndContext\n id="document-splits-dnd"\n sensors={sensors}\n collisionDetection={splitterCollisionDetection}\n onDragStart={handleDragStart}\n onDragOver={handleDragOver}\n onDragEnd={handleDragEnd}\n onDragCancel={handleDragCancel}\n >\n <ScrollArea className="min-h-0 flex-1" scrollFade>\n <SortableContext\n items={splits.map((group) => getSplitSortableId(group.id))}\n strategy={verticalListSortingStrategy}\n >\n <div className="space-y-3 p-3">\n {splits.map((group) => (\n <SortableSplitGroupCard\n key={group.id}\n activePage={\n activePageId ? getPageNumber(activePageId) : activePage\n }\n canRemove={splits.length > 1}\n group={group}\n thumbnailImages={thumbnailImages}\n onRemove={() => {\n if (splits.length <= 1) return\n onSplitsChange(\n splits.filter((split) => split.id !== group.id)\n )\n }}\n onSelectPage={onSelectPage}\n />\n ))}\n </div>\n </SortableContext>\n </ScrollArea>\n <DragOverlay dropAnimation={DRAG_OVERLAY_DROP_ANIMATION} zIndex={1000}>\n {activePageId ? (\n <div\n className="relative overflow-hidden rounded-md border bg-background shadow-lg shadow-black/10"\n style={{ width: THUMBNAIL_WIDTH, height: THUMBNAIL_HEIGHT }}\n >\n <FileThumbnail\n file={{ name: `${activePageId}.pdf`, type: "application/pdf" }}\n showMetadata={false}\n previewImageUrl={thumbnailImages[activePageId]}\n isLoading={!thumbnailImages[activePageId]}\n previewClassName="h-full aspect-auto"\n className="size-full rounded-[inherit] border-0"\n />\n </div>\n ) : activeSplitGroup ? (\n <SplitGroupDragOverlay\n activePage={activePage}\n group={activeSplitGroup}\n thumbnailImages={thumbnailImages}\n width={activeSplitGroupWidth}\n onSelectPage={onSelectPage}\n />\n ) : null}\n </DragOverlay>\n </DndContext>\n </aside>\n )\n}\n\nexport function DocumentSplitsBlock({\n file,\n thumbnailImages,\n}: {\n file?: string\n thumbnailImages?: Record<PageId, string>\n}) {\n const [activePage, setActivePage] = React.useState(1)\n const [splits, setSplits] = React.useState<DocumentSplit[]>(INITIAL_SPLITS)\n const [pdfFile, setPdfFile] = React.useState(file)\n const viewerRef = React.useRef<PDFViewerHandle>(null)\n const uploadedPdfUrlRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n setPdfFile(file)\n setActivePage(1)\n }, [file])\n\n React.useEffect(() => {\n return () => {\n if (uploadedPdfUrlRef.current) {\n URL.revokeObjectURL(uploadedPdfUrlRef.current)\n }\n }\n }, [])\n\n const handlePdfUpload = React.useCallback((uploadedFile: File) => {\n const nextUrl = URL.createObjectURL(uploadedFile)\n\n if (uploadedPdfUrlRef.current) {\n URL.revokeObjectURL(uploadedPdfUrlRef.current)\n }\n\n uploadedPdfUrlRef.current = nextUrl\n setPdfFile(nextUrl)\n setActivePage(1)\n }, [])\n\n const handleDocumentLoadSuccess = React.useCallback((pageCount: number) => {\n setSplits(createInitialSplits(pageCount))\n }, [])\n\n const handleSelectPage = React.useCallback((pageNumber: number) => {\n setActivePage(pageNumber)\n viewerRef.current?.scrollToPage(pageNumber, {\n block: "start",\n behavior: "auto",\n })\n }, [])\n\n return (\n <PdfBlockResizableShell\n autoSaveId="pdf-block-document-splits"\n heightClassName="h-[720px]"\n rightDefaultSize={50}\n rightMaxSize={66}\n rightMinSize={30}\n left={\n <PDFViewer\n ref={viewerRef}\n file={pdfFile}\n defaultZoom={0.75}\n onActivePageChange={setActivePage}\n onDocumentLoadSuccess={handleDocumentLoadSuccess}\n onPdfUpload={handlePdfUpload}\n />\n }\n right={\n <div className="flex min-h-0 flex-col bg-background">\n <div className="border-b px-4 py-3">\n <h3 className="text-sm font-medium">Document splits</h3>\n <p className="text-xs text-muted-foreground">\n Drag pages between split groups and reorder output documents.\n </p>\n </div>\n <DocumentSplits\n activePage={activePage}\n className="min-h-0 flex-1"\n splits={splits}\n thumbnailImages={thumbnailImages}\n withFrameDivider={false}\n onSelectPage={handleSelectPage}\n onSplitsChange={setSplits}\n />\n </div>\n }\n />\n )\n}\n'+ "\"use client\"\n\nimport * as React from \"react\"\nimport {\n closestCenter,\n DndContext,\n DragOverlay,\n PointerSensor,\n useDroppable,\n useSensor,\n useSensors,\n type CollisionDetection,\n type DragEndEvent,\n type DragOverEvent,\n type DragStartEvent,\n} from \"@dnd-kit/core\"\nimport {\n arrayMove,\n horizontalListSortingStrategy,\n SortableContext,\n useSortable,\n verticalListSortingStrategy,\n} from \"@dnd-kit/sortable\"\nimport { CSS } from \"@dnd-kit/utilities\"\nimport {\n Add01Icon,\n Delete02Icon,\n DragDropVerticalIcon,\n} from \"@hugeicons/core-free-icons\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { FileThumbnail } from \"@/components/ui/file-thumbnail\"\nimport { PDFViewer, type PDFViewerHandle } from \"@/components/ui/pdf-viewer\"\nimport { PdfBlockResizableShell } from \"@/components/pdf-block-resizable-shell\"\nimport { Button } from \"@/registry/new-york-v4/ui/button\"\nimport { ScrollArea } from \"@/registry/new-york-v4/ui/scroll-area\"\n\nexport type DocumentSplitPageId = `page-${number}`\nexport type DocumentSplit = {\n id: string\n title: string\n pages: DocumentSplitPageId[]\n}\n\ntype PageId = DocumentSplitPageId\ntype SplitGroup = DocumentSplit\n\nconst THUMBNAIL_WIDTH = 72\nconst THUMBNAIL_HEIGHT = 92\nconst DRAG_OVERLAY_DROP_ANIMATION = null\n\nconst splitterCollisionDetection: CollisionDetection = (args) => {\n const dragType = args.active.data.current?.type\n\n if (dragType === \"page\") {\n return closestCenter({\n ...args,\n droppableContainers: args.droppableContainers.filter(\n (container) =>\n container.data.current?.type === \"page\" ||\n (container.data.current?.type === \"page-dropzone\" &&\n container.data.current?.isEmpty)\n ),\n })\n }\n\n if (dragType === \"split\") {\n return closestCenter({\n ...args,\n droppableContainers: args.droppableContainers.filter(\n (container) => container.data.current?.type === \"split\"\n ),\n })\n }\n\n return closestCenter(args)\n}\n\nconst INITIAL_SPLITS: DocumentSplit[] = [\n {\n id: \"split-1\",\n title: \"Abstract and intro\",\n pages: [\"page-1\", \"page-2\", \"page-3\"],\n },\n {\n id: \"split-2\",\n title: \"Model architecture\",\n pages: [\"page-4\", \"page-5\", \"page-6\", \"page-7\"],\n },\n {\n id: \"split-3\",\n title: \"Training and results\",\n pages: [\"page-8\", \"page-9\", \"page-10\"],\n },\n]\n\nfunction createInitialSplits(pageCount: number) {\n if (pageCount <= 0) return INITIAL_SPLITS\n\n const pages = Array.from(\n { length: pageCount },\n (_, index) => `page-${index + 1}` as PageId\n )\n const chunkSize = Math.max(1, Math.ceil(pageCount / 3))\n\n return Array.from(\n { length: Math.ceil(pageCount / chunkSize) },\n (_, index) => {\n const startIndex = index * chunkSize\n const groupPages = pages.slice(startIndex, startIndex + chunkSize)\n const firstPage = getPageNumber(groupPages[0])\n const lastPage = getPageNumber(groupPages[groupPages.length - 1])\n\n return {\n id: `split-${index + 1}`,\n title:\n firstPage === lastPage\n ? `Page ${firstPage}`\n : `Pages ${firstPage}-${lastPage}`,\n pages: groupPages,\n }\n }\n )\n}\n\nfunction getPageNumber(pageId: PageId) {\n return Number(pageId.replace(\"page-\", \"\"))\n}\n\nfunction getSplitSortableId(groupId: string) {\n return `split-sortable-${groupId}`\n}\n\nfunction findGroupId(groups: SplitGroup[], id: string) {\n if (groups.some((group) => group.id === id)) return id\n\n return groups.find((group) => group.pages.includes(id as PageId))?.id ?? null\n}\n\nfunction getGroupPages(groups: SplitGroup[], groupId: string | null) {\n return groups.find((group) => group.id === groupId)?.pages ?? []\n}\n\nfunction movePageToGroup({\n draggedPageId,\n groups,\n insertIndex,\n targetGroupId,\n}: {\n draggedPageId: PageId\n groups: SplitGroup[]\n insertIndex: number\n targetGroupId: string\n}) {\n return groups.map((group) => {\n const pagesWithoutDragged = group.pages.filter(\n (pageId) => pageId !== draggedPageId\n )\n\n if (group.id !== targetGroupId) {\n return { ...group, pages: pagesWithoutDragged }\n }\n\n const nextPages = [...pagesWithoutDragged]\n nextPages.splice(insertIndex, 0, draggedPageId)\n\n return { ...group, pages: nextPages }\n })\n}\n\nfunction areSplitGroupsEqual(left: SplitGroup[], right: SplitGroup[]) {\n if (left === right) return true\n if (left.length !== right.length) return false\n\n return left.every((leftGroup, groupIndex) => {\n const rightGroup = right[groupIndex]\n if (!rightGroup) return false\n\n return (\n leftGroup.id === rightGroup.id &&\n leftGroup.title === rightGroup.title &&\n leftGroup.pages.length === rightGroup.pages.length &&\n leftGroup.pages.every(\n (pageId, pageIndex) => pageId === rightGroup.pages[pageIndex]\n )\n )\n })\n}\n\nfunction reorderPageInGroup({\n draggedPageId,\n groups,\n overPageId,\n}: {\n draggedPageId: PageId\n groups: SplitGroup[]\n overPageId: PageId\n}) {\n const groupId = findGroupId(groups, draggedPageId)\n const pages = getGroupPages(groups, groupId)\n const draggedIndex = pages.indexOf(draggedPageId)\n const overIndex = pages.indexOf(overPageId)\n\n if (!groupId || draggedIndex === -1 || overIndex === -1) return groups\n\n return groups.map((group) =>\n group.id === groupId\n ? {\n ...group,\n pages: arrayMove(group.pages, draggedIndex, overIndex),\n }\n : group\n )\n}\n\nfunction createPageRangeLabel(pageIds: PageId[]) {\n if (pageIds.length === 0) return \"No pages\"\n\n return `Pages ${pageIds.map(getPageNumber).join(\", \")}`\n}\n\nfunction SplitGroupDropzone({\n children,\n group,\n}: {\n children: React.ReactNode\n group: SplitGroup\n}) {\n const { isOver, setNodeRef } = useDroppable({\n id: group.id,\n data: { type: \"page-dropzone\", isEmpty: group.pages.length === 0 },\n })\n\n return (\n <div\n ref={setNodeRef}\n className={cn(\n \"min-h-[116px] rounded-lg p-2 transition-[background-color,box-shadow]\",\n isOver && \"bg-accent/30 shadow-[inset_0_0_0_1px_var(--border)]\"\n )}\n >\n {children}\n </div>\n )\n}\n\nfunction PageThumbnail({\n imageUrl,\n onSelect,\n pageId,\n}: {\n imageUrl?: string\n onSelect: (pageNumber: number) => void\n pageId: PageId\n}) {\n const pageNumber = getPageNumber(pageId)\n const {\n attributes,\n isDragging,\n listeners,\n setNodeRef,\n transform,\n transition,\n } = useSortable({\n id: pageId,\n data: { type: \"page\" },\n })\n\n return (\n <button\n ref={setNodeRef}\n type=\"button\"\n className={cn(\n \"relative shrink-0 cursor-grab overflow-hidden rounded-md border border-border bg-muted text-left shadow-xs transition-[border-color,opacity] hover:border-foreground/30 active:cursor-grabbing\",\n isDragging && \"opacity-0\"\n )}\n style={{\n width: THUMBNAIL_WIDTH,\n height: THUMBNAIL_HEIGHT,\n transform: CSS.Transform.toString(transform),\n transition,\n }}\n onClick={() => onSelect(pageNumber)}\n {...attributes}\n {...listeners}\n >\n <FileThumbnail\n file={{\n name: `page-${pageNumber}.pdf`,\n type: \"application/pdf\",\n size: `Page ${pageNumber}`,\n }}\n showMetadata={false}\n previewImageUrl={imageUrl}\n isLoading={!imageUrl}\n previewClassName=\"h-full aspect-auto\"\n className=\"size-full rounded-[inherit] border-0\"\n />\n <span\n className=\"absolute right-1 bottom-1 rounded bg-background/95 px-1.5 py-0.5 text-[10px] font-semibold text-foreground shadow-xs ring-1 ring-border/80\"\n >\n {pageNumber}\n </span>\n </button>\n )\n}\n\nfunction SplitGroupCard({\n canRemove,\n group,\n dragHandleProps,\n thumbnailImages,\n onRemove,\n onSelectPage,\n}: {\n canRemove: boolean\n group: SplitGroup\n dragHandleProps?: React.ComponentPropsWithoutRef<\"button\">\n thumbnailImages: Record<PageId, string>\n onRemove: () => void\n onSelectPage: (pageNumber: number) => void\n}) {\n return (\n <section className=\"w-full rounded-lg border bg-background\">\n <div className=\"flex items-center justify-between gap-3 border-b p-3\">\n <div className=\"flex min-w-0 items-center gap-2\">\n <button\n type=\"button\"\n aria-label={`Reorder ${group.title}`}\n className=\"inline-flex size-7 shrink-0 cursor-grab items-center justify-center rounded-md text-muted-foreground hover:bg-muted active:cursor-grabbing\"\n {...dragHandleProps}\n >\n <HugeiconsIcon icon={DragDropVerticalIcon} className=\"size-4\" />\n </button>\n <div className=\"min-w-0\">\n <div className=\"truncate text-sm font-medium\">{group.title}</div>\n <div className=\"mt-1 text-xs text-muted-foreground\">\n {createPageRangeLabel(group.pages)}\n </div>\n </div>\n </div>\n <div className=\"flex shrink-0 items-center gap-2\">\n <div className=\"rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground\">\n {group.pages.length}\n </div>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label={`Remove ${group.title}`}\n disabled={!canRemove}\n onClick={onRemove}\n >\n <HugeiconsIcon icon={Delete02Icon} className=\"size-4\" />\n </Button>\n </div>\n </div>\n <SplitGroupDropzone group={group}>\n {group.pages.length ? (\n <SortableContext\n items={group.pages}\n strategy={horizontalListSortingStrategy}\n >\n <ScrollArea\n className=\"h-[110px] w-full overflow-hidden\"\n orientation=\"horizontal\"\n scrollbarGutter\n scrollbarOverflowOnly\n viewportClassName=\"overflow-y-hidden\"\n >\n <div className=\"flex w-max gap-2 overflow-y-hidden py-1 pr-6\">\n {group.pages.map((pageId) => (\n <PageThumbnail\n key={pageId}\n pageId={pageId}\n imageUrl={thumbnailImages[pageId]}\n onSelect={onSelectPage}\n />\n ))}\n </div>\n </ScrollArea>\n </SortableContext>\n ) : (\n <div className=\"grid h-[104px] place-items-center rounded-lg bg-muted/35 text-xs text-muted-foreground\">\n Drop pages here\n </div>\n )}\n </SplitGroupDropzone>\n </section>\n )\n}\n\nfunction SortableSplitGroupCard({\n canRemove,\n group,\n thumbnailImages,\n onRemove,\n onSelectPage,\n}: {\n canRemove: boolean\n group: SplitGroup\n thumbnailImages: Record<PageId, string>\n onRemove: () => void\n onSelectPage: (pageNumber: number) => void\n}) {\n const {\n attributes,\n isDragging,\n listeners,\n setNodeRef,\n transform,\n transition,\n } = useSortable({\n id: getSplitSortableId(group.id),\n data: { type: \"split\", groupId: group.id },\n })\n\n return (\n <div\n ref={setNodeRef}\n className={cn(\"w-full\", isDragging && \"opacity-0\")}\n style={{\n transform: CSS.Transform.toString(transform),\n transition,\n }}\n >\n <SplitGroupCard\n canRemove={canRemove}\n group={group}\n thumbnailImages={thumbnailImages}\n dragHandleProps={{ ...attributes, ...listeners }}\n onRemove={onRemove}\n onSelectPage={onSelectPage}\n />\n </div>\n )\n}\n\nfunction SplitGroupDragOverlay({\n group,\n thumbnailImages,\n width,\n onSelectPage,\n}: {\n group: SplitGroup\n thumbnailImages: Record<PageId, string>\n width?: number\n onSelectPage: (pageNumber: number) => void\n}) {\n return (\n <div\n className=\"relative z-[1000] max-w-[calc(100vw-2rem)]\"\n style={{ width }}\n >\n <SplitGroupCard\n canRemove={false}\n group={group}\n thumbnailImages={thumbnailImages}\n onRemove={() => {}}\n onSelectPage={onSelectPage}\n />\n </div>\n )\n}\n\nexport function DocumentSplits({\n className,\n splits,\n thumbnailImages = {},\n withFrameDivider = true,\n onSelectPage,\n onSplitsChange,\n}: {\n className?: string\n splits: SplitGroup[]\n thumbnailImages?: Record<PageId, string>\n withFrameDivider?: boolean\n onSelectPage: (pageNumber: number) => void\n onSplitsChange: (splits: SplitGroup[]) => void\n}) {\n const [draggedPageId, setDraggedPageId] = React.useState<PageId | null>(null)\n const [activeSplitGroupId, setActiveSplitGroupId] = React.useState<\n string | null\n >(null)\n const [activeSplitGroupWidth, setActiveSplitGroupWidth] = React.useState<\n number | undefined\n >()\n const dragStartGroupIdRef = React.useRef<string | null>(null)\n const dragStartSplitsRef = React.useRef<SplitGroup[] | null>(null)\n const sensors = useSensors(\n useSensor(PointerSensor, { activationConstraint: { distance: 6 } })\n )\n\n const handleDragStart = React.useCallback(\n (event: DragStartEvent) => {\n const dragType = event.active.data.current?.type\n\n if (dragType === \"split\") {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(\n (event.active.data.current?.groupId as string | undefined) ?? null\n )\n setActiveSplitGroupWidth(event.active.rect.current.initial?.width)\n return\n }\n\n if (dragType !== \"page\") {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n const pageId = String(event.active.id) as PageId\n dragStartGroupIdRef.current = findGroupId(splits, pageId)\n dragStartSplitsRef.current = splits\n setDraggedPageId(pageId)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n },\n [splits]\n )\n\n const handleDragOver = React.useCallback(\n (event: DragOverEvent) => {\n if (event.active.data.current?.type !== \"page\" || !event.over) return\n\n const pageId = String(event.active.id) as PageId\n const overId = String(event.over.id)\n\n const sourceGroupId = findGroupId(splits, pageId)\n const targetGroupId = findGroupId(splits, overId)\n\n if (!sourceGroupId || !targetGroupId || sourceGroupId === targetGroupId) {\n return\n }\n\n const targetPages = getGroupPages(splits, targetGroupId)\n const overIndex = targetPages.indexOf(overId as PageId)\n const insertIndex = overIndex === -1 ? targetPages.length : overIndex\n\n const nextSplits = movePageToGroup({\n draggedPageId: pageId,\n groups: splits,\n insertIndex,\n targetGroupId,\n })\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n },\n [onSplitsChange, splits]\n )\n\n const handleDragEnd = React.useCallback(\n (event: DragEndEvent) => {\n if (event.active.data.current?.type === \"split\" && event.over) {\n const activeGroupId = event.active.data.current.groupId\n const overGroupId = event.over.data.current?.groupId\n\n const draggedIndex = splits.findIndex(\n (group) => group.id === activeGroupId\n )\n const overIndex = splits.findIndex((group) => group.id === overGroupId)\n\n if (draggedIndex !== -1 && overIndex !== -1) {\n const nextSplits = arrayMove(splits, draggedIndex, overIndex)\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n }\n\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n if (event.active.data.current?.type !== \"page\" || !event.over) {\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n return\n }\n\n const pageId = String(event.active.id) as PageId\n const overId = String(event.over.id) as PageId\n const overGroupId = findGroupId(splits, overId)\n\n if (dragStartGroupIdRef.current === overGroupId) {\n const nextSplits = reorderPageInGroup({\n draggedPageId: pageId,\n groups: splits,\n overPageId: overId,\n })\n\n if (!areSplitGroupsEqual(splits, nextSplits)) {\n onSplitsChange(nextSplits)\n }\n }\n\n dragStartGroupIdRef.current = null\n dragStartSplitsRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n },\n [onSplitsChange, splits]\n )\n\n const handleDragCancel = React.useCallback(() => {\n if (dragStartSplitsRef.current) {\n onSplitsChange(dragStartSplitsRef.current)\n }\n\n dragStartSplitsRef.current = null\n dragStartGroupIdRef.current = null\n setDraggedPageId(null)\n setActiveSplitGroupId(null)\n setActiveSplitGroupWidth(undefined)\n }, [onSplitsChange])\n\n const activeSplitGroup = activeSplitGroupId\n ? splits.find((group) => group.id === activeSplitGroupId)\n : null\n\n return (\n <aside\n className={cn(\n \"flex h-full min-h-0 flex-col bg-muted/20\",\n withFrameDivider && \"border-t md:border-t-0 md:border-l\",\n className\n )}\n >\n <div className=\"flex min-h-12 items-center justify-end gap-3 border-b bg-background px-3\">\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={() =>\n onSplitsChange([\n ...splits,\n {\n id: `split-${Date.now()}`,\n title: `Split ${splits.length + 1}`,\n pages: [],\n },\n ])\n }\n >\n <HugeiconsIcon icon={Add01Icon} className=\"size-4\" />\n Add split\n </Button>\n </div>\n <DndContext\n id=\"document-splits-dnd\"\n sensors={sensors}\n collisionDetection={splitterCollisionDetection}\n onDragStart={handleDragStart}\n onDragOver={handleDragOver}\n onDragEnd={handleDragEnd}\n onDragCancel={handleDragCancel}\n >\n <ScrollArea className=\"min-h-0 flex-1\" scrollFade>\n <SortableContext\n items={splits.map((group) => getSplitSortableId(group.id))}\n strategy={verticalListSortingStrategy}\n >\n <div className=\"space-y-3 p-3\">\n {splits.map((group) => (\n <SortableSplitGroupCard\n key={group.id}\n canRemove={splits.length > 1}\n group={group}\n thumbnailImages={thumbnailImages}\n onRemove={() => {\n if (splits.length <= 1) return\n onSplitsChange(\n splits.filter((split) => split.id !== group.id)\n )\n }}\n onSelectPage={onSelectPage}\n />\n ))}\n </div>\n </SortableContext>\n </ScrollArea>\n <DragOverlay dropAnimation={DRAG_OVERLAY_DROP_ANIMATION} zIndex={1000}>\n {draggedPageId ? (\n <div\n className=\"relative overflow-hidden rounded-md border bg-background shadow-lg shadow-black/10\"\n style={{ width: THUMBNAIL_WIDTH, height: THUMBNAIL_HEIGHT }}\n >\n <FileThumbnail\n file={{ name: `${draggedPageId}.pdf`, type: \"application/pdf\" }}\n showMetadata={false}\n previewImageUrl={thumbnailImages[draggedPageId]}\n isLoading={!thumbnailImages[draggedPageId]}\n previewClassName=\"h-full aspect-auto\"\n className=\"size-full rounded-[inherit] border-0\"\n />\n </div>\n ) : activeSplitGroup ? (\n <SplitGroupDragOverlay\n group={activeSplitGroup}\n thumbnailImages={thumbnailImages}\n width={activeSplitGroupWidth}\n onSelectPage={onSelectPage}\n />\n ) : null}\n </DragOverlay>\n </DndContext>\n </aside>\n )\n}\n\nexport function DocumentSplitsBlock({\n file,\n thumbnailImages,\n}: {\n file?: string\n thumbnailImages?: Record<PageId, string>\n}) {\n const [splits, setSplits] = React.useState<DocumentSplit[]>(INITIAL_SPLITS)\n const [pdfFile, setPdfFile] = React.useState(file)\n const viewerRef = React.useRef<PDFViewerHandle>(null)\n const uploadedPdfUrlRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n setPdfFile(file)\n }, [file])\n\n React.useEffect(() => {\n return () => {\n if (uploadedPdfUrlRef.current) {\n URL.revokeObjectURL(uploadedPdfUrlRef.current)\n }\n }\n }, [])\n\n const handlePdfUpload = React.useCallback((uploadedFile: File) => {\n const nextUrl = URL.createObjectURL(uploadedFile)\n\n if (uploadedPdfUrlRef.current) {\n URL.revokeObjectURL(uploadedPdfUrlRef.current)\n }\n\n uploadedPdfUrlRef.current = nextUrl\n setPdfFile(nextUrl)\n }, [])\n\n const handleDocumentLoadSuccess = React.useCallback((pageCount: number) => {\n setSplits(createInitialSplits(pageCount))\n }, [])\n\n const handleSelectPage = React.useCallback((pageNumber: number) => {\n viewerRef.current?.scrollToPage(pageNumber, {\n block: \"start\",\n behavior: \"auto\",\n })\n }, [])\n\n return (\n <PdfBlockResizableShell\n autoSaveId=\"pdf-block-document-splits\"\n heightClassName=\"h-[720px]\"\n rightDefaultSize={50}\n rightMaxSize={66}\n rightMinSize={30}\n left={\n <PDFViewer\n ref={viewerRef}\n file={pdfFile}\n defaultZoom={0.75}\n onDocumentLoadSuccess={handleDocumentLoadSuccess}\n onPdfUpload={handlePdfUpload}\n />\n }\n right={\n <div className=\"flex min-h-0 flex-col bg-background\">\n <div className=\"border-b px-4 py-3\">\n <h3 className=\"text-sm font-medium\">Document splits</h3>\n <p className=\"text-xs text-muted-foreground\">\n Drag pages between split groups and reorder output documents.\n </p>\n </div>\n <DocumentSplits\n className=\"min-h-0 flex-1\"\n splits={splits}\n thumbnailImages={thumbnailImages}\n withFrameDivider={false}\n onSelectPage={handleSelectPage}\n onSplitsChange={setSplits}\n />\n </div>\n }\n />\n )\n}\n"export function DocumentSplitsSource() {return <HighlightedCodeBlock code={documentSplitterSourceCode} />diff --git a/apps/v4/components/docx-editor-docs.tsx b/apps/v4/components/docx-editor-docs.tsxindex 002554a..43a66ee 100644--- a/apps/v4/components/docx-editor-docs.tsx+++ b/apps/v4/components/docx-editor-docs.tsx@@ -90,7 +90,7 @@ export function DocxEditorExample() {}`const docxEditorSourceCode =- '"use client"\n\nimport * as React from "react"\nimport { PreviewCard as PreviewCardPrimitive } from "@base-ui/react/preview-card"\nimport {\n DocxEditorViewer,\n paragraphLetterheadFloatSideAtNodeIndex,\n useDocxBorders,\n useDocxDocumentTheme,\n useDocxEditor,\n useDocxLineSpacing,\n useDocxPageLayout,\n useDocxParagraphStyles,\n useDocxTrackChanges,\n useDocxViewerThumbnails,\n type DocxBorderContext,\n type DocxBorderPreset,\n type DocxDocumentTheme,\n type DocxEditorController,\n type ParagraphStyleDefinition,\n} from "@extend-ai/react-docx"\nimport {\n ArrowExpandDiagonal01Icon,\n ArrowExpandDiagonal02Icon,\n BorderAll01Icon,\n BorderBottom01Icon,\n BorderHorizontalIcon,\n BorderInnerIcon,\n BorderLeft01Icon,\n BorderNone01Icon,\n BorderRight01Icon,\n BorderTop01Icon,\n BorderVerticalIcon,\n ColumnsThreeCogIcon,\n Download01Icon,\n EditOffIcon,\n FileDiffIcon,\n HighlighterIcon,\n ImageAdd01Icon,\n LeftToRightListBulletIcon,\n LeftToRightListNumberIcon,\n LineIcon,\n Link02Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n Redo02Icon,\n SidebarLeftIcon,\n Sun03Icon,\n TableIcon,\n TextAlignCenterIcon,\n TextAlignJustifyLeftIcon,\n TextAlignLeft01Icon,\n TextAlignRight01Icon,\n TextBoldIcon,\n TextColorIcon,\n TextItalicIcon,\n TextStrikethroughIcon,\n TextSubscriptIcon,\n TextSuperscriptIcon,\n TextUnderlineIcon,\n Undo02Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Input } from "@/components/ui/input"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/registry/new-york-v4/ui/dropdown-menu"\nimport { Separator } from "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_SOURCE_CACHE_LIMIT = 3\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_EDITOR_DEFAULT_ZOOM_SCALE = 75\nconst ZOOM_OPTIONS = [50, 75, 90, 100, 110, 125, 150, 175, 200] as const\nconst FONT_FAMILIES = [\n "Calibri",\n "Arial",\n "Times New Roman",\n "Georgia",\n "Helvetica",\n "Courier New",\n] as const\nconst FONT_SIZE_OPTIONS = [\n 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48,\n] as const\nconst LINE_SPACING_OPTIONS = [1, 1.15, 1.2, 1.5, 2, 2.5, 3] as const\nconst FALLBACK_PARAGRAPH_STYLE_OPTIONS = [\n { id: "Normal", name: "Body" },\n { id: "Heading1", name: "Heading 1" },\n { id: "Heading2", name: "Heading 2" },\n { id: "Heading3", name: "Heading 3" },\n] as const\nconst HIGHLIGHT_COLORS = [\n { label: "Yellow", value: "yellow", color: "#fff59d" },\n { label: "Green", value: "green", color: "#bbf7d0" },\n { label: "Cyan", value: "cyan", color: "#a5f3fc" },\n { label: "Magenta", value: "magenta", color: "#f5d0fe" },\n { label: "Red", value: "red", color: "#fecaca" },\n { label: "Blue", value: "blue", color: "#bfdbfe" },\n] as const\nconst HIGHLIGHT_PREVIEW_COLORS: Record<string, string> = {\n black: "#111827",\n white: "#ffffff",\n ...Object.fromEntries(\n HIGHLIGHT_COLORS.map((option) => [option.value, option.color])\n ),\n}\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\nconst DEFAULT_HEADING_PREVIEW_RUN_STYLES: Record<\n 1 | 2 | 3 | 4 | 5 | 6,\n NonNullable<ParagraphStyleDefinition["runStyle"]>\n> = {\n 1: {\n fontFamily: "Calibri Light",\n fontSizePt: 16,\n bold: true,\n color: "#2f5496",\n },\n 2: {\n fontFamily: "Calibri Light",\n fontSizePt: 13,\n bold: true,\n color: "#2f5496",\n },\n 3: {\n fontFamily: "Calibri",\n fontSizePt: 12,\n bold: true,\n color: "#1f3763",\n },\n 4: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 5: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 6: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n}\n\nconst docxFileCache = new Map<string, File>()\nconst docxFilePromiseCache = new Map<string, Promise<File>>()\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n}\n\ntype BorderControlOption = {\n id: DocxBorderPreset\n label: string\n contexts?: DocxBorderContext[]\n separatorBefore?: boolean\n}\n\nconst BORDER_CONTROL_OPTIONS: BorderControlOption[] = [\n { id: "bottom", label: "Bottom Border" },\n { id: "top", label: "Top Border" },\n { id: "left", label: "Left Border" },\n { id: "right", label: "Right Border" },\n { id: "none", label: "No Border", separatorBefore: true },\n { id: "all", label: "All Borders" },\n { id: "outside", label: "Outside Borders" },\n { id: "inside", label: "Inside Borders", contexts: ["table"] },\n {\n id: "inside-horizontal",\n label: "Inside Horizontal Border",\n contexts: ["table"],\n },\n {\n id: "inside-vertical",\n label: "Inside Vertical Border",\n contexts: ["table"],\n },\n {\n id: "diagonal-down",\n label: "Diagonal Down Border",\n contexts: ["table"],\n separatorBefore: true,\n },\n { id: "diagonal-up", label: "Diagonal Up Border", contexts: ["table"] },\n { id: "horizontal-line", label: "Horizontal Line", separatorBefore: true },\n]\n\nfunction borderControlOptionIcon(optionId: DocxBorderPreset) {\n switch (optionId) {\n case "bottom":\n return BorderBottom01Icon\n case "top":\n return BorderTop01Icon\n case "left":\n return BorderLeft01Icon\n case "right":\n return BorderRight01Icon\n case "none":\n return BorderNone01Icon\n case "inside":\n return BorderInnerIcon\n case "inside-horizontal":\n return BorderHorizontalIcon\n case "inside-vertical":\n return BorderVerticalIcon\n case "diagonal-down":\n return ArrowExpandDiagonal01Icon\n case "diagonal-up":\n return ArrowExpandDiagonal02Icon\n case "horizontal-line":\n return LineIcon\n default:\n return BorderAll01Icon\n }\n}\n\nfunction getDocumentCacheKey(url: string, fileName?: string) {\n return `${url.split("?")[0] ?? url}::${fileName ?? ""}`\n}\n\nfunction rememberDocxFile(cacheKey: string, file: File) {\n if (docxFileCache.has(cacheKey)) {\n docxFileCache.delete(cacheKey)\n }\n\n docxFileCache.set(cacheKey, file)\n\n while (docxFileCache.size > DOCX_SOURCE_CACHE_LIMIT) {\n const oldestKey = docxFileCache.keys().next().value\n if (!oldestKey) break\n docxFileCache.delete(oldestKey)\n }\n}\n\nasync function loadCachedDocxFile(\n url: string,\n displayFileName: string,\n cacheKey: string\n): Promise<File> {\n const cachedFile = docxFileCache.get(cacheKey)\n if (cachedFile) return cachedFile\n\n const pendingRequest = docxFilePromiseCache.get(cacheKey)\n if (pendingRequest) return pendingRequest\n\n const nextRequest = fetch(url)\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n const docxFile = new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n\n rememberDocxFile(cacheKey, docxFile)\n return docxFile\n })\n .finally(() => {\n docxFilePromiseCache.delete(cacheKey)\n })\n\n docxFilePromiseCache.set(cacheKey, nextRequest)\n return nextRequest\n}\n\nfunction formatDocumentName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "document.docx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {\n const currentIndex = ZOOM_OPTIONS.indexOf(\n currentZoomScale as (typeof ZOOM_OPTIONS)[number]\n )\n let fallbackIndex = -1\n\n if (direction > 0) {\n fallbackIndex = ZOOM_OPTIONS.findIndex((value) => value > currentZoomScale)\n } else {\n for (let index = ZOOM_OPTIONS.length - 1; index >= 0; index -= 1) {\n if (ZOOM_OPTIONS[index] < currentZoomScale) {\n fallbackIndex = index\n break\n }\n }\n }\n\n const resolvedIndex = currentIndex >= 0 ? currentIndex : fallbackIndex\n if (resolvedIndex < 0) return currentZoomScale\n\n const nextIndex = Math.min(\n Math.max(resolvedIndex + direction, 0),\n ZOOM_OPTIONS.length - 1\n )\n\n return ZOOM_OPTIONS[nextIndex] ?? currentZoomScale\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\n}\n\nfunction useControllableDarkMode({\n defaultIsDark = false,\n isDark,\n onIsDarkChange,\n}: {\n defaultIsDark?: boolean\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n}) {\n const [uncontrolledIsDark, setUncontrolledIsDark] =\n React.useState(defaultIsDark)\n const resolvedIsDark = isDark ?? uncontrolledIsDark\n\n const setIsDark = React.useCallback(\n (nextIsDark: boolean) => {\n if (isDark === undefined) {\n setUncontrolledIsDark(nextIsDark)\n }\n\n onIsDarkChange?.(nextIsDark)\n },\n [isDark, onIsDarkChange]\n )\n\n return [resolvedIsDark, setIsDark] as const\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction normalizeHexColor(value?: string, fallback = "#111827") {\n if (!value) return fallback\n\n const trimmed = value.trim()\n const threeDigit = /^#([0-9a-f]{3})$/i.exec(trimmed)\n if (threeDigit?.[1]) {\n const [red, green, blue] = threeDigit[1].split("")\n return `#${red}${red}${green}${green}${blue}${blue}`.toLowerCase()\n }\n\n const sixDigit = /^#([0-9a-f]{6})$/i.exec(trimmed)\n if (sixDigit?.[1]) {\n return `#${sixDigit[1].toLowerCase()}`\n }\n\n return fallback\n}\n\nfunction inferParagraphStyleHeadingLevel(value?: string) {\n if (!value) return undefined\n\n const match = value.match(/(?:^|[\\s_-])(?:heading|h)\\s*([1-6])(?:$|[\\s_-])/i)\n const level = match?.[1] ? Number(match[1]) : NaN\n\n return level >= 1 && level <= 6 ? (level as 1 | 2 | 3 | 4 | 5 | 6) : undefined\n}\n\nfunction resolveParagraphStyleHeadingLevel(option?: ParagraphStyleDefinition) {\n if (\n Number.isFinite(option?.headingLevel) &&\n option?.headingLevel &&\n option.headingLevel >= 1 &&\n option.headingLevel <= 6\n ) {\n return option.headingLevel as 1 | 2 | 3 | 4 | 5 | 6\n }\n\n return (\n inferParagraphStyleHeadingLevel(option?.id) ??\n inferParagraphStyleHeadingLevel(option?.name)\n )\n}\n\nfunction resolveParagraphStyleRunPreview(option?: ParagraphStyleDefinition) {\n if (!option) return undefined\n\n const headingLevel = resolveParagraphStyleHeadingLevel(option)\n const headingRunStyle = headingLevel\n ? DEFAULT_HEADING_PREVIEW_RUN_STYLES[headingLevel]\n : undefined\n\n return headingRunStyle\n ? {\n ...headingRunStyle,\n ...(option.runStyle ?? {}),\n }\n : option.runStyle\n}\n\nfunction resolveHighlightPreview(value?: string) {\n if (!value) return undefined\n\n const normalized = value.trim().toLowerCase()\n if (!normalized) return undefined\n\n const hex = normalizeHexColor(normalized, "")\n if (hex) return hex\n\n return HIGHLIGHT_PREVIEW_COLORS[normalized]\n}\n\nfunction themedPreviewColor(\n color: string | undefined,\n documentTheme: DocxDocumentTheme\n) {\n if (documentTheme !== "dark") return color\n if (!color) return "#f3f4f6"\n\n const normalized = color.trim().toLowerCase()\n if (\n normalized === "#000" ||\n normalized === "#000000" ||\n normalized === "#111111" ||\n normalized === "#111827" ||\n normalized === "black" ||\n normalized === "rgb(0,0,0)" ||\n normalized === "rgb(0, 0, 0)"\n ) {\n return "#f3f4f6"\n }\n\n return color\n}\n\nfunction paragraphStylePreviewStyle(\n option: ParagraphStyleDefinition,\n documentTheme: DocxDocumentTheme\n): React.CSSProperties {\n const runStyle = resolveParagraphStyleRunPreview(option)\n const textDecoration = [\n runStyle?.underline ? "underline" : "",\n runStyle?.strike ? "line-through" : "",\n ]\n .filter(Boolean)\n .join(" ")\n\n return {\n textAlign: option.align ?? "left",\n fontFamily: runStyle?.fontFamily,\n fontSize: runStyle?.fontSizePt ? `${runStyle.fontSizePt}pt` : "11pt",\n fontWeight:\n runStyle?.bold !== undefined ? (runStyle.bold ? 700 : 400) : undefined,\n fontStyle: runStyle?.italic ? "italic" : undefined,\n textDecoration: textDecoration || undefined,\n color:\n runStyle?.color !== undefined\n ? themedPreviewColor(normalizeHexColor(runStyle.color), documentTheme)\n : undefined,\n backgroundColor: resolveHighlightPreview(runStyle?.highlight),\n lineHeight: 1,\n whiteSpace: "pre-wrap",\n }\n}\n\nfunction paragraphStylePreviewTriggerId(prefix: string, styleId: string) {\n return `${prefix}-paragraph-style-preview-${styleId.replace(\n /[^a-zA-Z0-9_-]/g,\n "_"\n )}`\n}\n\nfunction parseToolbarSectionColumns(\n sectionPropertiesXml?: string\n): { count: number; gapPx: number } | undefined {\n if (!sectionPropertiesXml) return undefined\n\n const columnsTag = sectionPropertiesXml.match(/<w:cols\\b[^>]*\\/?>/i)?.[0]\n if (!columnsTag) return undefined\n\n const countRaw = columnsTag.match(/\\bw:num="(\\d+)"/i)?.[1]\n const count = countRaw ? Number(countRaw) : 1\n if (!Number.isFinite(count) || count <= 1) return undefined\n\n const gapRaw = columnsTag.match(/\\bw:space="(\\d+)"/i)?.[1]\n const gapTwips = gapRaw ? Number(gapRaw) : 720\n const gapPx = Math.max(0, Math.round((gapTwips * 96) / 1440))\n\n return {\n count: Math.max(2, Math.round(count)),\n gapPx,\n }\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction EditorLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction ToolbarIconButton({\n active,\n children,\n label,\n ...props\n}: React.ComponentProps<typeof Button> & {\n active?: boolean\n label: string\n}) {\n return (\n <ToolbarTooltip label={label}>\n <Button\n type="button"\n variant={active ? "secondary" : "ghost"}\n size="icon-sm"\n aria-label={label}\n data-pressed={active ? "" : undefined}\n {...props}\n >\n {children}\n </Button>\n </ToolbarTooltip>\n )\n}\n\nfunction ToolbarColorInput({\n color,\n disabled,\n icon,\n label,\n onChange,\n}: {\n color: string\n disabled?: boolean\n icon: typeof TextColorIcon\n label: string\n onChange: (color: string) => void\n}) {\n return (\n <ToolbarTooltip label={label}>\n <label\n className={cn(\n "relative inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-lg border border-transparent text-foreground transition-colors hover:bg-accent",\n disabled && "pointer-events-none opacity-64"\n )}\n aria-label={label}\n >\n <HugeiconsIcon icon={icon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: color }}\n />\n <input\n type="color"\n aria-label={label}\n disabled={disabled}\n value={color}\n className="sr-only"\n onChange={(event) => onChange(event.target.value)}\n />\n </label>\n </ToolbarTooltip>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n showMetadata={false}\n className={cn(\n "w-full rounded-sm border shadow-xs transition-[border-color,box-shadow] duration-150",\n isActive && "border-primary shadow-sm"\n )}\n />\n )\n}\n\nfunction ParagraphStylePreviewCard({\n documentTheme,\n option,\n}: {\n documentTheme: DocxDocumentTheme\n option: ParagraphStyleDefinition\n}) {\n const surfaceStyle: React.CSSProperties =\n documentTheme === "dark"\n ? {\n backgroundColor: "#111827",\n borderColor: "#374151",\n color: "#f3f4f6",\n }\n : {\n backgroundColor: "#ffffff",\n borderColor: "#d4d4d8",\n color: "#111827",\n }\n const secondaryTextColor = documentTheme === "dark" ? "#9ca3af" : "#6b7280"\n\n return (\n <div className="w-[260px] p-3">\n <p className="text-[10px] font-medium tracking-wide text-muted-foreground uppercase">\n Style Preview\n </p>\n <div className="mt-2 rounded-sm border p-2.5" style={surfaceStyle}>\n <p style={paragraphStylePreviewStyle(option, documentTheme)}>\n {option.name}\n </p>\n <p\n className="mt-1 text-[11px]"\n style={{\n color: secondaryTextColor,\n textAlign: option.align ?? "left",\n }}\n >\n The quick brown fox jumps over the lazy dog.\n </p>\n </div>\n </div>\n )\n}\n\nfunction DocxEditorToolbar({\n activePage,\n controlsDisabled,\n editor,\n isReadOnly,\n onImageUploadClick,\n onIsDarkChange,\n onIsReadOnlyChange,\n onOpenLinkEditor,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n editor: DocxEditorController\n isReadOnly: boolean\n onImageUploadClick: () => void\n onIsDarkChange: (checked: boolean) => void\n onIsReadOnlyChange: (checked: boolean) => void\n onOpenLinkEditor: () => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showNightRenderToggle: boolean\n zoomScale: number\n}) {\n const { documentTheme, setDocumentTheme } = useDocxDocumentTheme(editor)\n const { layout: pageLayout } = useDocxPageLayout(editor)\n const { paragraphStyles, selectedParagraphStyleId, setParagraphStyle } =\n useDocxParagraphStyles(editor)\n const { lineSpacing, setLineSpacing } = useDocxLineSpacing(editor)\n const { borderContext, activeBorderPresets, applyBorderPreset } =\n useDocxBorders(editor)\n const { showTrackedChanges, setShowTrackedChanges } =\n useDocxTrackChanges(editor)\n const selectedRunStyle = editor.selectedRunStyle\n const selectedParagraph = editor.selectedParagraph\n const paragraphStyleOptions: ParagraphStyleDefinition[] =\n paragraphStyles.length > 0\n ? paragraphStyles\n : [...FALLBACK_PARAGRAPH_STYLE_OPTIONS]\n const selectedParagraphStyleValue =\n selectedParagraphStyleId ??\n paragraphStyleOptions.find((option) => "isDefault" in option)?.id ??\n paragraphStyleOptions[0]?.id ??\n "Normal"\n const selectedParagraphStyleOption =\n paragraphStyleOptions.find(\n (option) => option.id === selectedParagraphStyleValue\n ) ??\n paragraphStyleOptions[0] ??\n FALLBACK_PARAGRAPH_STYLE_OPTIONS[0]\n const paragraphStylePreviewHandle = React.useMemo(\n () => PreviewCardPrimitive.createHandle<ParagraphStyleDefinition>(),\n []\n )\n const paragraphStylePreviewIdPrefix = React.useId()\n const [isParagraphStyleMenuOpen, setIsParagraphStyleMenuOpen] =\n React.useState(false)\n const openParagraphStylePreview = React.useCallback(\n (styleId: string) => {\n paragraphStylePreviewHandle.open(\n paragraphStylePreviewTriggerId(paragraphStylePreviewIdPrefix, styleId)\n )\n },\n [paragraphStylePreviewHandle, paragraphStylePreviewIdPrefix]\n )\n const selectedLineSpacingValue = React.useMemo(() => {\n const current = Number.isFinite(lineSpacing.multiple)\n ? lineSpacing.multiple\n : 1\n const nearest = LINE_SPACING_OPTIONS.reduce((closest, candidate) => {\n return Math.abs(candidate - current) < Math.abs(closest - current)\n ? candidate\n : closest\n }, LINE_SPACING_OPTIONS[0])\n return String(nearest)\n }, [lineSpacing.multiple])\n const textColorValue = normalizeHexColor(selectedRunStyle?.color)\n const highlightColor =\n HIGHLIGHT_COLORS.find(\n (option) => option.value === selectedRunStyle?.highlight\n )?.color ?? "#fff59d"\n const activeNodeIndex =\n editor.selection.kind === "paragraph"\n ? editor.selection.nodeIndex\n : editor.selection.tableIndex\n const letterheadColumns =\n editor.selection.kind === "paragraph" &&\n paragraphLetterheadFloatSideAtNodeIndex(\n editor.model.nodes,\n editor.selection.nodeIndex\n )\n ? { count: 2, gapPx: 28 }\n : undefined\n const sections = editor.model.metadata.sections ?? []\n const activeSection = sections\n .filter((section) => section.startNodeIndex <= activeNodeIndex)\n .at(-1)\n const activeColumns =\n letterheadColumns ??\n parseToolbarSectionColumns(activeSection?.sectionPropertiesXml) ??\n parseToolbarSectionColumns(editor.model.metadata.sectionPropertiesXml) ??\n pageLayout.columns\n const activeBorderControlOptions = BORDER_CONTROL_OPTIONS.filter(\n (option) => activeBorderPresets[option.id]\n )\n const borderTriggerLabel =\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].label\n : "Borders"\n const borderTriggerIcon = borderControlOptionIcon(\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].id\n : "all"\n )\n const canEdit = !controlsDisabled && !isReadOnly\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n\n const preserveTextSelection = React.useCallback(\n (event: React.MouseEvent<HTMLElement> | React.PointerEvent<HTMLElement>) =>\n event.preventDefault(),\n []\n )\n\n return (\n <div className="border-b bg-background">\n <TooltipProvider>\n <div className="flex min-h-11 items-center gap-2 overflow-x-auto overflow-y-hidden border-b px-3">\n <ToolbarIconButton\n label="Toggle pages"\n disabled={controlsDisabled}\n onClick={onToggleSidebar}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </ToolbarIconButton>\n <div className="min-w-28 text-sm whitespace-nowrap text-primary">\n Page {pageCount ? activePage : 1} of {pageCount || "-"}\n </div>\n <div className="min-w-0 flex-1" />\n {showNightRenderToggle ? (\n <>\n <ToolbarIconButton\n label={\n documentTheme === "dark"\n ? "Use light document"\n : "Use dark document"\n }\n disabled={controlsDisabled}\n onClick={() => {\n const nextIsDark = documentTheme !== "dark"\n setDocumentTheme(nextIsDark ? "dark" : "light")\n onIsDarkChange(nextIsDark)\n }}\n >\n <HugeiconsIcon\n icon={documentTheme === "dark" ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </ToolbarIconButton>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <ToolbarIconButton\n label="Show tracked changes"\n active={showTrackedChanges}\n disabled={controlsDisabled}\n onClick={() => setShowTrackedChanges(!showTrackedChanges)}\n >\n <HugeiconsIcon icon={FileDiffIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label={isReadOnly ? "Switch to edit mode" : "Switch to read-only"}\n active={isReadOnly}\n disabled={controlsDisabled}\n onClick={() => onIsReadOnlyChange(!isReadOnly)}\n >\n <HugeiconsIcon icon={EditOffIcon} className="size-4" />\n </ToolbarIconButton>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarIconButton\n label="Import DOCX"\n disabled={editor.isImporting}\n onClick={onUploadClick}\n >\n {editor.isImporting ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n )}\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Download DOCX"\n disabled={controlsDisabled || editor.isImporting}\n onClick={editor.exportDocx}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex min-h-12 flex-wrap items-center gap-2 border-b px-3 py-2">\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Undo"\n disabled={!editor.canUndo || isReadOnly}\n onClick={editor.undo}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Redo"\n disabled={!editor.canRedo || isReadOnly}\n onClick={editor.redo}\n >\n <HugeiconsIcon icon={Redo02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <PreviewCardPrimitive.Root handle={paragraphStylePreviewHandle}>\n {({ payload }) => {\n const previewOption = payload ?? selectedParagraphStyleOption\n\n return (\n <>\n <Select\n value={selectedParagraphStyleValue}\n onOpenChange={(open) => {\n setIsParagraphStyleMenuOpen(open)\n\n if (!open) {\n paragraphStylePreviewHandle.close()\n return\n }\n\n window.requestAnimationFrame(() => {\n openParagraphStylePreview(selectedParagraphStyleValue)\n })\n }}\n onValueChange={(value) => {\n if (value) {\n setParagraphStyle(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[136px] min-w-[136px]"\n aria-label="Paragraph style"\n >\n <SelectValue placeholder="Style" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010] min-w-[210px]"\n >\n {paragraphStyleOptions.map((option) => {\n const previewTriggerId = paragraphStylePreviewTriggerId(\n paragraphStylePreviewIdPrefix,\n option.id\n )\n\n return (\n <SelectItem\n key={option.id}\n value={option.id}\n label={option.name}\n className="relative min-w-[190px]"\n onFocus={() => openParagraphStylePreview(option.id)}\n onPointerEnter={() =>\n openParagraphStylePreview(option.id)\n }\n >\n <span className="block truncate">\n {option.name}\n </span>\n <PreviewCardPrimitive.Trigger\n id={previewTriggerId}\n handle={paragraphStylePreviewHandle}\n payload={option}\n delay={0}\n closeDelay={120}\n render={\n <span\n aria-hidden="true"\n className="pointer-events-none absolute inset-0 block"\n />\n }\n />\n </SelectItem>\n )\n })}\n </SelectContent>\n </Select>\n {isParagraphStyleMenuOpen && previewOption ? (\n <PreviewCardPrimitive.Portal>\n <PreviewCardPrimitive.Positioner\n side="right"\n align="start"\n sideOffset={10}\n alignOffset={-4}\n className="z-[100020] transition-[top,left,right,bottom,transform] duration-100 ease-out data-instant:transition-none"\n >\n <PreviewCardPrimitive.Popup\n data-slot="paragraph-style-preview-card"\n className="origin-(--transform-origin) rounded-lg border bg-popover text-popover-foreground shadow-lg/5 transition-opacity duration-100 outline-none not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]"\n >\n <ParagraphStylePreviewCard\n documentTheme={documentTheme}\n option={previewOption}\n />\n </PreviewCardPrimitive.Popup>\n </PreviewCardPrimitive.Positioner>\n </PreviewCardPrimitive.Portal>\n ) : null}\n </>\n )\n }}\n </PreviewCardPrimitive.Root>\n\n <Select\n value={selectedRunStyle?.fontFamily ?? "Calibri"}\n onValueChange={(value) => {\n if (value) {\n editor.setFontFamily(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[156px] min-w-[156px]"\n aria-label="Font family"\n >\n <SelectValue placeholder="Font" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {FONT_FAMILIES.map((fontFamily) => (\n <SelectItem key={fontFamily} value={fontFamily}>\n <span style={{ fontFamily }}>{fontFamily}</span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={String(Math.round(selectedRunStyle?.fontSizePt ?? 12))}\n onValueChange={(value) => {\n const nextSize = Number(value)\n if (Number.isFinite(nextSize)) {\n editor.setFontSize(nextSize)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[86px] min-w-[86px]"\n aria-label="Font size"\n >\n <SelectValue placeholder="Size" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {FONT_SIZE_OPTIONS.map((size) => (\n <SelectItem key={size} value={String(size)}>\n {size} pt\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={selectedLineSpacingValue}\n onValueChange={(value) => {\n const nextSpacing = Number(value)\n if (Number.isFinite(nextSpacing)) {\n setLineSpacing(nextSpacing)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[94px] min-w-[94px]"\n aria-label="Line spacing"\n >\n <SelectValue placeholder="Spacing" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {LINE_SPACING_OPTIONS.map((spacing) => (\n <SelectItem key={spacing} value={String(spacing)}>\n {spacing}x\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bold"\n active={Boolean(selectedRunStyle?.bold)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleBold}\n >\n <HugeiconsIcon icon={TextBoldIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Italic"\n active={Boolean(selectedRunStyle?.italic)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleItalic}\n >\n <HugeiconsIcon icon={TextItalicIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Underline"\n active={Boolean(selectedRunStyle?.underline)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleUnderline}\n >\n <HugeiconsIcon icon={TextUnderlineIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Strikethrough"\n active={Boolean(selectedRunStyle?.strike)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleStrike}\n >\n <HugeiconsIcon icon={TextStrikethroughIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Superscript"\n active={selectedRunStyle?.verticalAlign === "superscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSuperscript}\n >\n <HugeiconsIcon icon={TextSuperscriptIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Subscript"\n active={selectedRunStyle?.verticalAlign === "subscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSubscript}\n >\n <HugeiconsIcon icon={TextSubscriptIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarColorInput\n label="Text color"\n icon={TextColorIcon}\n color={textColorValue}\n disabled={!canEdit}\n onChange={(color) =>\n editor.setTextColor(normalizeHexColor(color))\n }\n />\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!canEdit}\n aria-label="Highlight color"\n className="relative"\n >\n <HugeiconsIcon icon={HighlighterIcon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: highlightColor }}\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-[100010] w-44">\n {HIGHLIGHT_COLORS.map((option) => (\n <DropdownMenuCheckboxItem\n key={option.value}\n checked={selectedRunStyle?.highlight === option.value}\n onCheckedChange={() => editor.setHighlight(option.value)}\n >\n <span\n className="size-3 rounded-full border"\n style={{ backgroundColor: option.color }}\n />\n {option.label}\n </DropdownMenuCheckboxItem>\n ))}\n <DropdownMenuSeparator />\n <DropdownMenuCheckboxItem\n checked={!selectedRunStyle?.highlight}\n onCheckedChange={() => editor.setHighlight(undefined)}\n >\n No highlight\n </DropdownMenuCheckboxItem>\n </DropdownMenuContent>\n </DropdownMenu>\n <ToolbarIconButton\n label="Link"\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={onOpenLinkEditor}\n >\n <HugeiconsIcon icon={Link02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Align left"\n active={\n selectedParagraph?.style?.align === "left" ||\n !selectedParagraph?.style?.align\n }\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("left")}\n >\n <HugeiconsIcon icon={TextAlignLeft01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Align center"\n active={selectedParagraph?.style?.align === "center"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("center")}\n >\n <HugeiconsIcon icon={TextAlignCenterIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Align right"\n active={selectedParagraph?.style?.align === "right"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("right")}\n >\n <HugeiconsIcon icon={TextAlignRight01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Justify"\n active={selectedParagraph?.style?.align === "justify"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("justify")}\n >\n <HugeiconsIcon\n icon={TextAlignJustifyLeftIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bulleted list"\n active={editor.hasUnorderedList}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.toggleList("unordered")}\n >\n <HugeiconsIcon\n icon={LeftToRightListBulletIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Numbered list"\n active={editor.hasOrderedList}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.toggleList("ordered")}\n >\n <HugeiconsIcon\n icon={LeftToRightListNumberIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="sm"\n disabled={!canEdit}\n className="h-7 gap-1 px-2 shadow-none"\n >\n <HugeiconsIcon icon={borderTriggerIcon} className="size-4" />\n {borderTriggerLabel}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-[100010] w-56">\n {BORDER_CONTROL_OPTIONS.map((option) => {\n const enabledForContext =\n !option.contexts || option.contexts.includes(borderContext)\n const BorderOptionIcon = borderControlOptionIcon(option.id)\n\n return (\n <React.Fragment key={option.id}>\n {option.separatorBefore ? <DropdownMenuSeparator /> : null}\n <DropdownMenuCheckboxItem\n checked={activeBorderPresets[option.id]}\n disabled={!enabledForContext}\n onCheckedChange={() => {\n if (enabledForContext) {\n applyBorderPreset(option.id)\n }\n }}\n >\n <HugeiconsIcon\n icon={BorderOptionIcon}\n className="size-4 text-muted-foreground"\n />\n {option.label}\n </DropdownMenuCheckboxItem>\n </React.Fragment>\n )\n })}\n </DropdownMenuContent>\n </DropdownMenu>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Insert image"\n disabled={!canEdit}\n onClick={onImageUploadClick}\n >\n <HugeiconsIcon icon={ImageAdd01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Insert table"\n disabled={!canEdit}\n onClick={editor.insertTable}\n >\n <HugeiconsIcon icon={TableIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarTooltip label="Section columns">\n <div className="flex h-7 shrink-0 items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground">\n <HugeiconsIcon icon={ColumnsThreeCogIcon} className="size-4" />\n {activeColumns ? `${activeColumns.count} cols` : "1 col"}\n </div>\n </ToolbarTooltip>\n </div>\n\n <div className="ml-auto flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Zoom out"\n disabled={controlsDisabled || !canZoomOut}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, -1)\n )\n }\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n <Select\n value={zoomScale.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="end"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarIconButton\n label="Zoom in"\n disabled={controlsDisabled || !canZoomIn}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function DocxEditorPreview({\n className,\n defaultIsDark = false,\n fileName,\n isDark: controlledIsDark,\n onIsDarkChange,\n rounded = false,\n src,\n}: {\n className?: string\n defaultIsDark?: boolean\n fileName?: string\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n rounded?: boolean\n src?: string\n}) {\n const [effectiveIsDark, setIsDark] = useControllableDarkMode({\n defaultIsDark,\n isDark: controlledIsDark,\n onIsDarkChange,\n })\n\n return (\n <DocxEditorContent\n className={className}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setIsDark={setIsDark}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction DocxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n rounded,\n setIsDark,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setIsDark: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const imageInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const [zoomScale, setZoomScale] = React.useState<number>(\n DOCX_EDITOR_DEFAULT_ZOOM_SCALE\n )\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const [isReadOnly, setIsReadOnly] = React.useState(false)\n const [linkEditorOpen, setLinkEditorOpen] = React.useState(false)\n const [linkDraft, setLinkDraft] = React.useState("")\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const cacheKey = React.useMemo(\n () =>\n uploadedDocxFile?.identity ??\n (url ? getDocumentCacheKey(url, displayFileName) : "docx-empty"),\n [displayFileName, uploadedDocxFile?.identity, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { importDocxFile, setDocumentTheme, status } = editor\n const [reportedPageCount, setReportedPageCount] = React.useState(0)\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, editor.totalPages, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <EditorLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\n ? await loadCachedDocxFile(url, displayFileName, cacheKey)\n : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : "Unknown DOCX load error"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n void load()\n\n return () => {\n isCurrent = false\n }\n }, [cacheKey, displayFileName, importDocxFile, uploadedDocxFile, url])\n\n React.useEffect(() => {\n if (url) {\n setUploadedDocxFile(null)\n }\n }, [url])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n \'[data-docx-page-wrapper="true"][data-index]\'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback((pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport || !page) return\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n }, [])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomScale(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\n setActivePage(1)\n setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n async function handleImageUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n await editor.insertImageFile(file)\n }\n\n function openLinkEditor() {\n setLinkDraft(editor.selectedLink ?? "")\n setLinkEditorOpen(true)\n }\n\n function applyLink() {\n editor.setLink(linkDraft.trim() || undefined)\n setLinkEditorOpen(false)\n }\n\n return (\n <div\n className={cn(\n "flex h-[720px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <input\n ref={imageInputRef}\n type="file"\n accept="image/*"\n className="hidden"\n onChange={handleImageUpload}\n />\n <DocxEditorToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n editor={editor}\n isReadOnly={isReadOnly}\n onImageUploadClick={() => imageInputRef.current?.click()}\n onIsDarkChange={setIsDark}\n onIsReadOnlyChange={setIsReadOnly}\n onOpenLinkEditor={openLinkEditor}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showNightRenderToggle={shouldRenderNightMode}\n zoomScale={zoomScale}\n />\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {linkEditorOpen ? (\n <div className="absolute top-3 left-1/2 z-50 flex w-[min(420px,calc(100%-2rem))] -translate-x-1/2 items-center gap-2 rounded-lg border bg-background p-2 shadow-lg">\n <Input\n value={linkDraft}\n onChange={(event) => setLinkDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n event.preventDefault()\n applyLink()\n }\n if (event.key === "Escape") {\n setLinkEditorOpen(false)\n }\n }}\n placeholder="https://example.com"\n aria-label="Link URL"\n />\n <Button type="button" size="sm" onClick={applyLink}>\n Apply\n </Button>\n <Button\n type="button"\n size="sm"\n variant="ghost"\n onClick={() => {\n editor.setLink(undefined)\n setLinkEditorOpen(false)\n }}\n >\n Clear\n </Button>\n </div>\n ) : null}\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <div className="h-full overflow-auto">\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 rounded-sm border bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs text-muted-foreground shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </div>\n </DocumentViewerThumbnailSidebar>\n <div\n ref={viewportRef}\n className={cn(\n "min-h-0 flex-1 overflow-auto p-4",\n rounded && "rounded-b-lg"\n )}\n style={{ backgroundColor: viewerBackgroundColor }}\n >\n {!url && !uploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">Upload a DOCX to edit</div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to edit DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="mx-auto flex min-h-full justify-center">\n <div\n className={cn(\n "origin-top",\n editor.documentTheme === "dark" && "docx-night-reader-shell"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode={isReadOnly ? "read-only" : "edit"}\n showTrackedChanges={editor.showTrackedChanges}\n loadingState={loadingState}\n pageBackgroundColor={\n editor.documentTheme === "dark" ? "#0a0a0a" : undefined\n }\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n onPageCountChange={handlePageCountChange}\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport { PreviewCard as PreviewCardPrimitive } from "@base-ui/react/preview-card"\nimport {\n DocxEditorViewer,\n paragraphLetterheadFloatSideAtNodeIndex,\n useDocxBorders,\n useDocxDocumentTheme,\n useDocxEditor,\n useDocxLineSpacing,\n useDocxPageLayout,\n useDocxParagraphStyles,\n useDocxTrackChanges,\n useDocxViewerThumbnails,\n type DocxBorderContext,\n type DocxBorderPreset,\n type DocxDocumentTheme,\n type DocxEditorController,\n type ParagraphStyleDefinition,\n} from "@extend-ai/react-docx"\nimport {\n ArrowExpandDiagonal01Icon,\n ArrowExpandDiagonal02Icon,\n BorderAll01Icon,\n BorderBottom01Icon,\n BorderHorizontalIcon,\n BorderInnerIcon,\n BorderLeft01Icon,\n BorderNone01Icon,\n BorderRight01Icon,\n BorderTop01Icon,\n BorderVerticalIcon,\n ColumnsThreeCogIcon,\n Download01Icon,\n EditOffIcon,\n FileDiffIcon,\n HighlighterIcon,\n ImageAdd01Icon,\n LeftToRightListBulletIcon,\n LeftToRightListNumberIcon,\n LineIcon,\n Link02Icon,\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n Redo02Icon,\n SidebarLeftIcon,\n Sun03Icon,\n TableIcon,\n TextAlignCenterIcon,\n TextAlignJustifyLeftIcon,\n TextAlignLeft01Icon,\n TextAlignRight01Icon,\n TextBoldIcon,\n TextColorIcon,\n TextItalicIcon,\n TextStrikethroughIcon,\n TextSubscriptIcon,\n TextSuperscriptIcon,\n TextUnderlineIcon,\n Undo02Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Input } from "@/components/ui/input"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/registry/new-york-v4/ui/dropdown-menu"\nimport { Separator } from "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_SOURCE_CACHE_LIMIT = 3\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_EDITOR_DEFAULT_ZOOM_SCALE = 75\nconst ZOOM_OPTIONS = [50, 75, 90, 100, 110, 125, 150, 175, 200] as const\nconst FONT_FAMILIES = [\n "Calibri",\n "Arial",\n "Times New Roman",\n "Georgia",\n "Helvetica",\n "Courier New",\n] as const\nconst FONT_SIZE_OPTIONS = [\n 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48,\n] as const\nconst LINE_SPACING_OPTIONS = [1, 1.15, 1.2, 1.5, 2, 2.5, 3] as const\nconst FALLBACK_PARAGRAPH_STYLE_OPTIONS = [\n { id: "Normal", name: "Body" },\n { id: "Heading1", name: "Heading 1" },\n { id: "Heading2", name: "Heading 2" },\n { id: "Heading3", name: "Heading 3" },\n] as const\nconst HIGHLIGHT_COLORS = [\n { label: "Yellow", value: "yellow", color: "#fff59d" },\n { label: "Green", value: "green", color: "#bbf7d0" },\n { label: "Cyan", value: "cyan", color: "#a5f3fc" },\n { label: "Magenta", value: "magenta", color: "#f5d0fe" },\n { label: "Red", value: "red", color: "#fecaca" },\n { label: "Blue", value: "blue", color: "#bfdbfe" },\n] as const\nconst HIGHLIGHT_PREVIEW_COLORS: Record<string, string> = {\n black: "#111827",\n white: "#ffffff",\n ...Object.fromEntries(\n HIGHLIGHT_COLORS.map((option) => [option.value, option.color])\n ),\n}\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\nconst DEFAULT_HEADING_PREVIEW_RUN_STYLES: Record<\n 1 | 2 | 3 | 4 | 5 | 6,\n NonNullable<ParagraphStyleDefinition["runStyle"]>\n> = {\n 1: {\n fontFamily: "Calibri Light",\n fontSizePt: 16,\n bold: true,\n color: "#2f5496",\n },\n 2: {\n fontFamily: "Calibri Light",\n fontSizePt: 13,\n bold: true,\n color: "#2f5496",\n },\n 3: {\n fontFamily: "Calibri",\n fontSizePt: 12,\n bold: true,\n color: "#1f3763",\n },\n 4: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 5: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n 6: {\n fontFamily: "Calibri",\n fontSizePt: 11,\n bold: true,\n color: "#1f3763",\n },\n}\n\nconst docxFileCache = new Map<string, File>()\nconst docxFilePromiseCache = new Map<string, Promise<File>>()\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n}\n\ntype BorderControlOption = {\n id: DocxBorderPreset\n label: string\n contexts?: DocxBorderContext[]\n separatorBefore?: boolean\n}\n\nconst BORDER_CONTROL_OPTIONS: BorderControlOption[] = [\n { id: "bottom", label: "Bottom Border" },\n { id: "top", label: "Top Border" },\n { id: "left", label: "Left Border" },\n { id: "right", label: "Right Border" },\n { id: "none", label: "No Border", separatorBefore: true },\n { id: "all", label: "All Borders" },\n { id: "outside", label: "Outside Borders" },\n { id: "inside", label: "Inside Borders", contexts: ["table"] },\n {\n id: "inside-horizontal",\n label: "Inside Horizontal Border",\n contexts: ["table"],\n },\n {\n id: "inside-vertical",\n label: "Inside Vertical Border",\n contexts: ["table"],\n },\n {\n id: "diagonal-down",\n label: "Diagonal Down Border",\n contexts: ["table"],\n separatorBefore: true,\n },\n { id: "diagonal-up", label: "Diagonal Up Border", contexts: ["table"] },\n { id: "horizontal-line", label: "Horizontal Line", separatorBefore: true },\n]\n\nfunction borderControlOptionIcon(optionId: DocxBorderPreset) {\n switch (optionId) {\n case "bottom":\n return BorderBottom01Icon\n case "top":\n return BorderTop01Icon\n case "left":\n return BorderLeft01Icon\n case "right":\n return BorderRight01Icon\n case "none":\n return BorderNone01Icon\n case "inside":\n return BorderInnerIcon\n case "inside-horizontal":\n return BorderHorizontalIcon\n case "inside-vertical":\n return BorderVerticalIcon\n case "diagonal-down":\n return ArrowExpandDiagonal01Icon\n case "diagonal-up":\n return ArrowExpandDiagonal02Icon\n case "horizontal-line":\n return LineIcon\n default:\n return BorderAll01Icon\n }\n}\n\nfunction getDocumentCacheKey(url: string, fileName?: string) {\n return `${url.split("?")[0] ?? url}::${fileName ?? ""}`\n}\n\nfunction rememberDocxFile(cacheKey: string, file: File) {\n if (docxFileCache.has(cacheKey)) {\n docxFileCache.delete(cacheKey)\n }\n\n docxFileCache.set(cacheKey, file)\n\n while (docxFileCache.size > DOCX_SOURCE_CACHE_LIMIT) {\n const oldestKey = docxFileCache.keys().next().value\n if (!oldestKey) break\n docxFileCache.delete(oldestKey)\n }\n}\n\nasync function loadCachedDocxFile(\n url: string,\n displayFileName: string,\n cacheKey: string\n): Promise<File> {\n const cachedFile = docxFileCache.get(cacheKey)\n if (cachedFile) return cachedFile\n\n const pendingRequest = docxFilePromiseCache.get(cacheKey)\n if (pendingRequest) return pendingRequest\n\n const nextRequest = fetch(url)\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n const docxFile = new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n\n rememberDocxFile(cacheKey, docxFile)\n return docxFile\n })\n .finally(() => {\n docxFilePromiseCache.delete(cacheKey)\n })\n\n docxFilePromiseCache.set(cacheKey, nextRequest)\n return nextRequest\n}\n\nfunction formatDocumentName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "document.docx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {\n const currentIndex = ZOOM_OPTIONS.indexOf(\n currentZoomScale as (typeof ZOOM_OPTIONS)[number]\n )\n let fallbackIndex = -1\n\n if (direction > 0) {\n fallbackIndex = ZOOM_OPTIONS.findIndex((value) => value > currentZoomScale)\n } else {\n for (let index = ZOOM_OPTIONS.length - 1; index >= 0; index -= 1) {\n if (ZOOM_OPTIONS[index] < currentZoomScale) {\n fallbackIndex = index\n break\n }\n }\n }\n\n const resolvedIndex = currentIndex >= 0 ? currentIndex : fallbackIndex\n if (resolvedIndex < 0) return currentZoomScale\n\n const nextIndex = Math.min(\n Math.max(resolvedIndex + direction, 0),\n ZOOM_OPTIONS.length - 1\n )\n\n return ZOOM_OPTIONS[nextIndex] ?? currentZoomScale\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\n}\n\nfunction useControllableDarkMode({\n defaultIsDark = false,\n isDark,\n onIsDarkChange,\n}: {\n defaultIsDark?: boolean\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n}) {\n const [uncontrolledIsDark, setUncontrolledIsDark] =\n React.useState(defaultIsDark)\n const resolvedIsDark = isDark ?? uncontrolledIsDark\n\n const setIsDark = React.useCallback(\n (nextIsDark: boolean) => {\n if (isDark === undefined) {\n setUncontrolledIsDark(nextIsDark)\n }\n\n onIsDarkChange?.(nextIsDark)\n },\n [isDark, onIsDarkChange]\n )\n\n return [resolvedIsDark, setIsDark] as const\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction normalizeHexColor(value?: string, fallback = "#111827") {\n if (!value) return fallback\n\n const trimmed = value.trim()\n const threeDigit = /^#([0-9a-f]{3})$/i.exec(trimmed)\n if (threeDigit?.[1]) {\n const [red, green, blue] = threeDigit[1].split("")\n return `#${red}${red}${green}${green}${blue}${blue}`.toLowerCase()\n }\n\n const sixDigit = /^#([0-9a-f]{6})$/i.exec(trimmed)\n if (sixDigit?.[1]) {\n return `#${sixDigit[1].toLowerCase()}`\n }\n\n return fallback\n}\n\nfunction inferParagraphStyleHeadingLevel(value?: string) {\n if (!value) return undefined\n\n const match = value.match(/(?:^|[\\s_-])(?:heading|h)\\s*([1-6])(?:$|[\\s_-])/i)\n const level = match?.[1] ? Number(match[1]) : NaN\n\n return level >= 1 && level <= 6 ? (level as 1 | 2 | 3 | 4 | 5 | 6) : undefined\n}\n\nfunction resolveParagraphStyleHeadingLevel(option?: ParagraphStyleDefinition) {\n if (\n Number.isFinite(option?.headingLevel) &&\n option?.headingLevel &&\n option.headingLevel >= 1 &&\n option.headingLevel <= 6\n ) {\n return option.headingLevel as 1 | 2 | 3 | 4 | 5 | 6\n }\n\n return (\n inferParagraphStyleHeadingLevel(option?.id) ??\n inferParagraphStyleHeadingLevel(option?.name)\n )\n}\n\nfunction resolveParagraphStyleRunPreview(option?: ParagraphStyleDefinition) {\n if (!option) return undefined\n\n const headingLevel = resolveParagraphStyleHeadingLevel(option)\n const headingRunStyle = headingLevel\n ? DEFAULT_HEADING_PREVIEW_RUN_STYLES[headingLevel]\n : undefined\n\n return headingRunStyle\n ? {\n ...headingRunStyle,\n ...(option.runStyle ?? {}),\n }\n : option.runStyle\n}\n\nfunction resolveHighlightPreview(value?: string) {\n if (!value) return undefined\n\n const normalized = value.trim().toLowerCase()\n if (!normalized) return undefined\n\n const hex = normalizeHexColor(normalized, "")\n if (hex) return hex\n\n return HIGHLIGHT_PREVIEW_COLORS[normalized]\n}\n\nfunction themedPreviewColor(\n color: string | undefined,\n documentTheme: DocxDocumentTheme\n) {\n if (documentTheme !== "dark") return color\n if (!color) return "#f3f4f6"\n\n const normalized = color.trim().toLowerCase()\n if (\n normalized === "#000" ||\n normalized === "#000000" ||\n normalized === "#111111" ||\n normalized === "#111827" ||\n normalized === "black" ||\n normalized === "rgb(0,0,0)" ||\n normalized === "rgb(0, 0, 0)"\n ) {\n return "#f3f4f6"\n }\n\n return color\n}\n\nfunction paragraphStylePreviewStyle(\n option: ParagraphStyleDefinition,\n documentTheme: DocxDocumentTheme\n): React.CSSProperties {\n const runStyle = resolveParagraphStyleRunPreview(option)\n const textDecoration = [\n runStyle?.underline ? "underline" : "",\n runStyle?.strike ? "line-through" : "",\n ]\n .filter(Boolean)\n .join(" ")\n\n return {\n textAlign: option.align ?? "left",\n fontFamily: runStyle?.fontFamily,\n fontSize: runStyle?.fontSizePt ? `${runStyle.fontSizePt}pt` : "11pt",\n fontWeight:\n runStyle?.bold !== undefined ? (runStyle.bold ? 700 : 400) : undefined,\n fontStyle: runStyle?.italic ? "italic" : undefined,\n textDecoration: textDecoration || undefined,\n color:\n runStyle?.color !== undefined\n ? themedPreviewColor(normalizeHexColor(runStyle.color), documentTheme)\n : undefined,\n backgroundColor: resolveHighlightPreview(runStyle?.highlight),\n lineHeight: 1,\n whiteSpace: "pre-wrap",\n }\n}\n\nfunction paragraphStylePreviewTriggerId(prefix: string, styleId: string) {\n return `${prefix}-paragraph-style-preview-${styleId.replace(\n /[^a-zA-Z0-9_-]/g,\n "_"\n )}`\n}\n\nfunction parseToolbarSectionColumns(\n sectionPropertiesXml?: string\n): { count: number; gapPx: number } | undefined {\n if (!sectionPropertiesXml) return undefined\n\n const columnsTag = sectionPropertiesXml.match(/<w:cols\\b[^>]*\\/?>/i)?.[0]\n if (!columnsTag) return undefined\n\n const countRaw = columnsTag.match(/\\bw:num="(\\d+)"/i)?.[1]\n const count = countRaw ? Number(countRaw) : 1\n if (!Number.isFinite(count) || count <= 1) return undefined\n\n const gapRaw = columnsTag.match(/\\bw:space="(\\d+)"/i)?.[1]\n const gapTwips = gapRaw ? Number(gapRaw) : 720\n const gapPx = Math.max(0, Math.round((gapTwips * 96) / 1440))\n\n return {\n count: Math.max(2, Math.round(count)),\n gapPx,\n }\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction EditorLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction ToolbarIconButton({\n active,\n children,\n label,\n ...props\n}: React.ComponentProps<typeof Button> & {\n active?: boolean\n label: string\n}) {\n return (\n <ToolbarTooltip label={label}>\n <Button\n type="button"\n variant={active ? "secondary" : "ghost"}\n size="icon-sm"\n aria-label={label}\n data-pressed={active ? "" : undefined}\n {...props}\n >\n {children}\n </Button>\n </ToolbarTooltip>\n )\n}\n\nfunction ToolbarColorInput({\n color,\n disabled,\n icon,\n label,\n onChange,\n}: {\n color: string\n disabled?: boolean\n icon: typeof TextColorIcon\n label: string\n onChange: (color: string) => void\n}) {\n return (\n <ToolbarTooltip label={label}>\n <label\n className={cn(\n "relative inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-lg border border-transparent text-foreground transition-colors hover:bg-accent",\n disabled && "pointer-events-none opacity-64"\n )}\n aria-label={label}\n >\n <HugeiconsIcon icon={icon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: color }}\n />\n <input\n type="color"\n aria-label={label}\n disabled={disabled}\n value={color}\n className="sr-only"\n onChange={(event) => onChange(event.target.value)}\n />\n </label>\n </ToolbarTooltip>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="rounded-md bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n showMetadata={false}\n className={cn(\n "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",\n isActive && "shadow-sm"\n )}\n />\n )\n}\n\nfunction ParagraphStylePreviewCard({\n documentTheme,\n option,\n}: {\n documentTheme: DocxDocumentTheme\n option: ParagraphStyleDefinition\n}) {\n const surfaceStyle: React.CSSProperties =\n documentTheme === "dark"\n ? {\n backgroundColor: "#111827",\n borderColor: "#374151",\n color: "#f3f4f6",\n }\n : {\n backgroundColor: "#ffffff",\n borderColor: "#d4d4d8",\n color: "#111827",\n }\n const secondaryTextColor = documentTheme === "dark" ? "#9ca3af" : "#6b7280"\n\n return (\n <div className="w-[260px] p-3">\n <p className="text-[10px] font-medium tracking-wide text-muted-foreground uppercase">\n Style Preview\n </p>\n <div className="mt-2 rounded-sm border p-2.5" style={surfaceStyle}>\n <p style={paragraphStylePreviewStyle(option, documentTheme)}>\n {option.name}\n </p>\n <p\n className="mt-1 text-[11px]"\n style={{\n color: secondaryTextColor,\n textAlign: option.align ?? "left",\n }}\n >\n The quick brown fox jumps over the lazy dog.\n </p>\n </div>\n </div>\n )\n}\n\nfunction DocxEditorToolbar({\n activePage,\n controlsDisabled,\n editor,\n isReadOnly,\n onImageUploadClick,\n onIsDarkChange,\n onIsReadOnlyChange,\n onOpenLinkEditor,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n editor: DocxEditorController\n isReadOnly: boolean\n onImageUploadClick: () => void\n onIsDarkChange: (checked: boolean) => void\n onIsReadOnlyChange: (checked: boolean) => void\n onOpenLinkEditor: () => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showNightRenderToggle: boolean\n zoomScale: number\n}) {\n const { documentTheme, setDocumentTheme } = useDocxDocumentTheme(editor)\n const { layout: pageLayout } = useDocxPageLayout(editor)\n const { paragraphStyles, selectedParagraphStyleId, setParagraphStyle } =\n useDocxParagraphStyles(editor)\n const { lineSpacing, setLineSpacing } = useDocxLineSpacing(editor)\n const { borderContext, activeBorderPresets, applyBorderPreset } =\n useDocxBorders(editor)\n const { showTrackedChanges, setShowTrackedChanges } =\n useDocxTrackChanges(editor)\n const selectedRunStyle = editor.selectedRunStyle\n const selectedParagraph = editor.selectedParagraph\n const paragraphStyleOptions: ParagraphStyleDefinition[] =\n paragraphStyles.length > 0\n ? paragraphStyles\n : [...FALLBACK_PARAGRAPH_STYLE_OPTIONS]\n const selectedParagraphStyleValue =\n selectedParagraphStyleId ??\n paragraphStyleOptions.find((option) => "isDefault" in option)?.id ??\n paragraphStyleOptions[0]?.id ??\n "Normal"\n const selectedParagraphStyleOption =\n paragraphStyleOptions.find(\n (option) => option.id === selectedParagraphStyleValue\n ) ??\n paragraphStyleOptions[0] ??\n FALLBACK_PARAGRAPH_STYLE_OPTIONS[0]\n const paragraphStylePreviewHandle = React.useMemo(\n () => PreviewCardPrimitive.createHandle<ParagraphStyleDefinition>(),\n []\n )\n const paragraphStylePreviewIdPrefix = React.useId()\n const [isParagraphStyleMenuOpen, setIsParagraphStyleMenuOpen] =\n React.useState(false)\n const openParagraphStylePreview = React.useCallback(\n (styleId: string) => {\n paragraphStylePreviewHandle.open(\n paragraphStylePreviewTriggerId(paragraphStylePreviewIdPrefix, styleId)\n )\n },\n [paragraphStylePreviewHandle, paragraphStylePreviewIdPrefix]\n )\n const selectedLineSpacingValue = React.useMemo(() => {\n const current = Number.isFinite(lineSpacing.multiple)\n ? lineSpacing.multiple\n : 1\n const nearest = LINE_SPACING_OPTIONS.reduce((closest, candidate) => {\n return Math.abs(candidate - current) < Math.abs(closest - current)\n ? candidate\n : closest\n }, LINE_SPACING_OPTIONS[0])\n return String(nearest)\n }, [lineSpacing.multiple])\n const textColorValue = normalizeHexColor(selectedRunStyle?.color)\n const highlightColor =\n HIGHLIGHT_COLORS.find(\n (option) => option.value === selectedRunStyle?.highlight\n )?.color ?? "#fff59d"\n const activeNodeIndex =\n editor.selection.kind === "paragraph"\n ? editor.selection.nodeIndex\n : editor.selection.tableIndex\n const letterheadColumns =\n editor.selection.kind === "paragraph" &&\n paragraphLetterheadFloatSideAtNodeIndex(\n editor.model.nodes,\n editor.selection.nodeIndex\n )\n ? { count: 2, gapPx: 28 }\n : undefined\n const sections = editor.model.metadata.sections ?? []\n const activeSection = sections\n .filter((section) => section.startNodeIndex <= activeNodeIndex)\n .at(-1)\n const activeColumns =\n letterheadColumns ??\n parseToolbarSectionColumns(activeSection?.sectionPropertiesXml) ??\n parseToolbarSectionColumns(editor.model.metadata.sectionPropertiesXml) ??\n pageLayout.columns\n const activeBorderControlOptions = BORDER_CONTROL_OPTIONS.filter(\n (option) => activeBorderPresets[option.id]\n )\n const borderTriggerLabel =\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].label\n : "Borders"\n const borderTriggerIcon = borderControlOptionIcon(\n activeBorderControlOptions.length === 1\n ? activeBorderControlOptions[0].id\n : "all"\n )\n const canEdit = !controlsDisabled && !isReadOnly\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n\n const preserveTextSelection = React.useCallback(\n (event: React.MouseEvent<HTMLElement> | React.PointerEvent<HTMLElement>) =>\n event.preventDefault(),\n []\n )\n\n return (\n <div className="border-b bg-background">\n <TooltipProvider>\n <div className="flex min-h-11 items-center gap-2 overflow-x-auto overflow-y-hidden border-b px-3">\n <ToolbarIconButton\n label="Toggle pages"\n disabled={controlsDisabled}\n onClick={onToggleSidebar}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </ToolbarIconButton>\n <div className="min-w-28 text-sm whitespace-nowrap text-primary">\n Page {pageCount ? activePage : 1} of {pageCount || "-"}\n </div>\n <div className="min-w-0 flex-1" />\n {showNightRenderToggle ? (\n <>\n <ToolbarIconButton\n label={\n documentTheme === "dark"\n ? "Use light document"\n : "Use dark document"\n }\n disabled={controlsDisabled}\n onClick={() => {\n const nextIsDark = documentTheme !== "dark"\n setDocumentTheme(nextIsDark ? "dark" : "light")\n onIsDarkChange(nextIsDark)\n }}\n >\n <HugeiconsIcon\n icon={documentTheme === "dark" ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </ToolbarIconButton>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <ToolbarIconButton\n label="Show tracked changes"\n active={showTrackedChanges}\n disabled={controlsDisabled}\n onClick={() => setShowTrackedChanges(!showTrackedChanges)}\n >\n <HugeiconsIcon icon={FileDiffIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label={isReadOnly ? "Switch to edit mode" : "Switch to read-only"}\n active={isReadOnly}\n disabled={controlsDisabled}\n onClick={() => onIsReadOnlyChange(!isReadOnly)}\n >\n <HugeiconsIcon icon={EditOffIcon} className="size-4" />\n </ToolbarIconButton>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarIconButton\n label="Import DOCX"\n disabled={editor.isImporting}\n onClick={onUploadClick}\n >\n {editor.isImporting ? (\n <Spinner className="size-4" />\n ) : (\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n )}\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Download DOCX"\n disabled={controlsDisabled || editor.isImporting}\n onClick={editor.exportDocx}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex min-h-12 flex-wrap items-center gap-2 border-b px-3 py-2">\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Undo"\n disabled={!editor.canUndo || isReadOnly}\n onClick={editor.undo}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Redo"\n disabled={!editor.canRedo || isReadOnly}\n onClick={editor.redo}\n >\n <HugeiconsIcon icon={Redo02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <PreviewCardPrimitive.Root handle={paragraphStylePreviewHandle}>\n {({ payload }) => {\n const previewOption = payload ?? selectedParagraphStyleOption\n\n return (\n <>\n <Select\n value={selectedParagraphStyleValue}\n onOpenChange={(open) => {\n setIsParagraphStyleMenuOpen(open)\n\n if (!open) {\n paragraphStylePreviewHandle.close()\n return\n }\n\n window.requestAnimationFrame(() => {\n openParagraphStylePreview(selectedParagraphStyleValue)\n })\n }}\n onValueChange={(value) => {\n if (value) {\n setParagraphStyle(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[136px] min-w-[136px]"\n aria-label="Paragraph style"\n >\n <SelectValue placeholder="Style" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010] min-w-[210px]"\n >\n {paragraphStyleOptions.map((option) => {\n const previewTriggerId = paragraphStylePreviewTriggerId(\n paragraphStylePreviewIdPrefix,\n option.id\n )\n\n return (\n <SelectItem\n key={option.id}\n value={option.id}\n label={option.name}\n className="relative min-w-[190px]"\n onFocus={() => openParagraphStylePreview(option.id)}\n onPointerEnter={() =>\n openParagraphStylePreview(option.id)\n }\n >\n <span className="block truncate">\n {option.name}\n </span>\n <PreviewCardPrimitive.Trigger\n id={previewTriggerId}\n handle={paragraphStylePreviewHandle}\n payload={option}\n delay={0}\n closeDelay={120}\n render={\n <span\n aria-hidden="true"\n className="pointer-events-none absolute inset-0 block"\n />\n }\n />\n </SelectItem>\n )\n })}\n </SelectContent>\n </Select>\n {isParagraphStyleMenuOpen && previewOption ? (\n <PreviewCardPrimitive.Portal>\n <PreviewCardPrimitive.Positioner\n side="right"\n align="start"\n sideOffset={10}\n alignOffset={-4}\n className="z-[100020] transition-[top,left,right,bottom,transform] duration-100 ease-out data-instant:transition-none"\n >\n <PreviewCardPrimitive.Popup\n data-slot="paragraph-style-preview-card"\n className="origin-(--transform-origin) rounded-lg border bg-popover text-popover-foreground shadow-lg/5 transition-opacity duration-100 outline-none not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]"\n >\n <ParagraphStylePreviewCard\n documentTheme={documentTheme}\n option={previewOption}\n />\n </PreviewCardPrimitive.Popup>\n </PreviewCardPrimitive.Positioner>\n </PreviewCardPrimitive.Portal>\n ) : null}\n </>\n )\n }}\n </PreviewCardPrimitive.Root>\n\n <Select\n value={selectedRunStyle?.fontFamily ?? "Calibri"}\n onValueChange={(value) => {\n if (value) {\n editor.setFontFamily(value)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[156px] min-w-[156px]"\n aria-label="Font family"\n >\n <SelectValue placeholder="Font" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {FONT_FAMILIES.map((fontFamily) => (\n <SelectItem key={fontFamily} value={fontFamily}>\n <span style={{ fontFamily }}>{fontFamily}</span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={String(Math.round(selectedRunStyle?.fontSizePt ?? 12))}\n onValueChange={(value) => {\n const nextSize = Number(value)\n if (Number.isFinite(nextSize)) {\n editor.setFontSize(nextSize)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[86px] min-w-[86px]"\n aria-label="Font size"\n >\n <SelectValue placeholder="Size" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {FONT_SIZE_OPTIONS.map((size) => (\n <SelectItem key={size} value={String(size)}>\n {size} pt\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <Select\n value={selectedLineSpacingValue}\n onValueChange={(value) => {\n const nextSpacing = Number(value)\n if (Number.isFinite(nextSpacing)) {\n setLineSpacing(nextSpacing)\n }\n }}\n disabled={!canEdit}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[94px] min-w-[94px]"\n aria-label="Line spacing"\n >\n <SelectValue placeholder="Spacing" />\n </SelectTrigger>\n <SelectContent\n align="start"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {LINE_SPACING_OPTIONS.map((spacing) => (\n <SelectItem key={spacing} value={String(spacing)}>\n {spacing}x\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bold"\n active={Boolean(selectedRunStyle?.bold)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleBold}\n >\n <HugeiconsIcon icon={TextBoldIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Italic"\n active={Boolean(selectedRunStyle?.italic)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleItalic}\n >\n <HugeiconsIcon icon={TextItalicIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Underline"\n active={Boolean(selectedRunStyle?.underline)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleUnderline}\n >\n <HugeiconsIcon icon={TextUnderlineIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Strikethrough"\n active={Boolean(selectedRunStyle?.strike)}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleStrike}\n >\n <HugeiconsIcon icon={TextStrikethroughIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Superscript"\n active={selectedRunStyle?.verticalAlign === "superscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSuperscript}\n >\n <HugeiconsIcon icon={TextSuperscriptIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Subscript"\n active={selectedRunStyle?.verticalAlign === "subscript"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={editor.toggleSubscript}\n >\n <HugeiconsIcon icon={TextSubscriptIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarColorInput\n label="Text color"\n icon={TextColorIcon}\n color={textColorValue}\n disabled={!canEdit}\n onChange={(color) =>\n editor.setTextColor(normalizeHexColor(color))\n }\n />\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={!canEdit}\n aria-label="Highlight color"\n className="relative"\n >\n <HugeiconsIcon icon={HighlighterIcon} className="size-4" />\n <span\n className="absolute right-1 bottom-1 h-1 w-4 rounded-full border border-background"\n style={{ backgroundColor: highlightColor }}\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-[100010] w-44">\n {HIGHLIGHT_COLORS.map((option) => (\n <DropdownMenuCheckboxItem\n key={option.value}\n checked={selectedRunStyle?.highlight === option.value}\n onCheckedChange={() => editor.setHighlight(option.value)}\n >\n <span\n className="size-3 rounded-full border"\n style={{ backgroundColor: option.color }}\n />\n {option.label}\n </DropdownMenuCheckboxItem>\n ))}\n <DropdownMenuSeparator />\n <DropdownMenuCheckboxItem\n checked={!selectedRunStyle?.highlight}\n onCheckedChange={() => editor.setHighlight(undefined)}\n >\n No highlight\n </DropdownMenuCheckboxItem>\n </DropdownMenuContent>\n </DropdownMenu>\n <ToolbarIconButton\n label="Link"\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={onOpenLinkEditor}\n >\n <HugeiconsIcon icon={Link02Icon} className="size-4" />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Align left"\n active={\n selectedParagraph?.style?.align === "left" ||\n !selectedParagraph?.style?.align\n }\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("left")}\n >\n <HugeiconsIcon icon={TextAlignLeft01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Align center"\n active={selectedParagraph?.style?.align === "center"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("center")}\n >\n <HugeiconsIcon icon={TextAlignCenterIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Align right"\n active={selectedParagraph?.style?.align === "right"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("right")}\n >\n <HugeiconsIcon icon={TextAlignRight01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Justify"\n active={selectedParagraph?.style?.align === "justify"}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.setAlignment("justify")}\n >\n <HugeiconsIcon\n icon={TextAlignJustifyLeftIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Bulleted list"\n active={editor.hasUnorderedList}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.toggleList("unordered")}\n >\n <HugeiconsIcon\n icon={LeftToRightListBulletIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Numbered list"\n active={editor.hasOrderedList}\n disabled={!canEdit}\n onMouseDown={preserveTextSelection}\n onPointerDown={preserveTextSelection}\n onClick={() => editor.toggleList("ordered")}\n >\n <HugeiconsIcon\n icon={LeftToRightListNumberIcon}\n className="size-4"\n />\n </ToolbarIconButton>\n </div>\n\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="sm"\n disabled={!canEdit}\n className="h-7 gap-1 px-2 shadow-none"\n >\n <HugeiconsIcon icon={borderTriggerIcon} className="size-4" />\n {borderTriggerLabel}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="start" className="z-[100010] w-56">\n {BORDER_CONTROL_OPTIONS.map((option) => {\n const enabledForContext =\n !option.contexts || option.contexts.includes(borderContext)\n const BorderOptionIcon = borderControlOptionIcon(option.id)\n\n return (\n <React.Fragment key={option.id}>\n {option.separatorBefore ? <DropdownMenuSeparator /> : null}\n <DropdownMenuCheckboxItem\n checked={activeBorderPresets[option.id]}\n disabled={!enabledForContext}\n onCheckedChange={() => {\n if (enabledForContext) {\n applyBorderPreset(option.id)\n }\n }}\n >\n <HugeiconsIcon\n icon={BorderOptionIcon}\n className="size-4 text-muted-foreground"\n />\n {option.label}\n </DropdownMenuCheckboxItem>\n </React.Fragment>\n )\n })}\n </DropdownMenuContent>\n </DropdownMenu>\n\n <div className="flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Insert image"\n disabled={!canEdit}\n onClick={onImageUploadClick}\n >\n <HugeiconsIcon icon={ImageAdd01Icon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarIconButton\n label="Insert table"\n disabled={!canEdit}\n onClick={editor.insertTable}\n >\n <HugeiconsIcon icon={TableIcon} className="size-4" />\n </ToolbarIconButton>\n <ToolbarTooltip label="Section columns">\n <div className="flex h-7 shrink-0 items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground">\n <HugeiconsIcon icon={ColumnsThreeCogIcon} className="size-4" />\n {activeColumns ? `${activeColumns.count} cols` : "1 col"}\n </div>\n </ToolbarTooltip>\n </div>\n\n <div className="ml-auto flex shrink-0 items-center gap-1">\n <ToolbarIconButton\n label="Zoom out"\n disabled={controlsDisabled || !canZoomOut}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, -1)\n )\n }\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n <Select\n value={zoomScale.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent\n align="end"\n alignItemWithTrigger={false}\n className="z-[100010]"\n >\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarIconButton\n label="Zoom in"\n disabled={controlsDisabled || !canZoomIn}\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </ToolbarIconButton>\n </div>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nexport function DocxEditorPreview({\n className,\n defaultIsDark = false,\n fileName,\n isDark: controlledIsDark,\n onIsDarkChange,\n rounded = false,\n src,\n}: {\n className?: string\n defaultIsDark?: boolean\n fileName?: string\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n rounded?: boolean\n src?: string\n}) {\n const [effectiveIsDark, setIsDark] = useControllableDarkMode({\n defaultIsDark,\n isDark: controlledIsDark,\n onIsDarkChange,\n })\n\n return (\n <DocxEditorContent\n className={className}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setIsDark={setIsDark}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction DocxEditorContent({\n className,\n effectiveIsDark,\n fileName,\n rounded,\n setIsDark,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setIsDark: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const imageInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const [zoomScale, setZoomScale] = React.useState<number>(\n DOCX_EDITOR_DEFAULT_ZOOM_SCALE\n )\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const [isReadOnly, setIsReadOnly] = React.useState(false)\n const [linkEditorOpen, setLinkEditorOpen] = React.useState(false)\n const [linkDraft, setLinkDraft] = React.useState("")\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const cacheKey = React.useMemo(\n () =>\n uploadedDocxFile?.identity ??\n (url ? getDocumentCacheKey(url, displayFileName) : "docx-empty"),\n [displayFileName, uploadedDocxFile?.identity, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { importDocxFile, setDocumentTheme, status } = editor\n const [reportedPageCount, setReportedPageCount] = React.useState(0)\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, editor.totalPages, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <EditorLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\n ? await loadCachedDocxFile(url, displayFileName, cacheKey)\n : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : "Unknown DOCX load error"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n void load()\n\n return () => {\n isCurrent = false\n }\n }, [cacheKey, displayFileName, importDocxFile, uploadedDocxFile, url])\n\n React.useEffect(() => {\n if (url) {\n setUploadedDocxFile(null)\n }\n }, [url])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n \'[data-docx-page-wrapper="true"][data-index]\'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback((pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport || !page) return\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n }, [])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomScale(DOCX_EDITOR_DEFAULT_ZOOM_SCALE)\n setActivePage(1)\n setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n async function handleImageUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n await editor.insertImageFile(file)\n }\n\n function openLinkEditor() {\n setLinkDraft(editor.selectedLink ?? "")\n setLinkEditorOpen(true)\n }\n\n function applyLink() {\n editor.setLink(linkDraft.trim() || undefined)\n setLinkEditorOpen(false)\n }\n\n return (\n <div\n className={cn(\n "flex h-[720px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <input\n ref={imageInputRef}\n type="file"\n accept="image/*"\n className="hidden"\n onChange={handleImageUpload}\n />\n <DocxEditorToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n editor={editor}\n isReadOnly={isReadOnly}\n onImageUploadClick={() => imageInputRef.current?.click()}\n onIsDarkChange={setIsDark}\n onIsReadOnlyChange={setIsReadOnly}\n onOpenLinkEditor={openLinkEditor}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showNightRenderToggle={shouldRenderNightMode}\n zoomScale={zoomScale}\n />\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n {linkEditorOpen ? (\n <div className="absolute top-3 left-1/2 z-50 flex w-[min(420px,calc(100%-2rem))] -translate-x-1/2 items-center gap-2 rounded-lg border bg-background p-2 shadow-lg">\n <Input\n value={linkDraft}\n onChange={(event) => setLinkDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === "Enter") {\n event.preventDefault()\n applyLink()\n }\n if (event.key === "Escape") {\n setLinkEditorOpen(false)\n }\n }}\n placeholder="https://example.com"\n aria-label="Link URL"\n />\n <Button type="button" size="sm" onClick={applyLink}>\n Apply\n </Button>\n <Button\n type="button"\n size="sm"\n variant="ghost"\n onClick={() => {\n editor.setLink(undefined)\n setLinkEditorOpen(false)\n }}\n >\n Clear\n </Button>\n </div>\n ) : null}\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <div className="h-full overflow-auto">\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </div>\n </DocumentViewerThumbnailSidebar>\n <div\n ref={viewportRef}\n className={cn(\n "min-h-0 flex-1 overflow-auto p-4",\n rounded && "rounded-b-lg"\n )}\n style={{ backgroundColor: viewerBackgroundColor }}\n >\n {!url && !uploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">Upload a DOCX to edit</div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to edit DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="mx-auto flex min-h-full justify-center">\n <div\n className={cn(\n "origin-top",\n editor.documentTheme === "dark" && "docx-night-reader-shell"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode={isReadOnly ? "read-only" : "edit"}\n showTrackedChanges={editor.showTrackedChanges}\n loadingState={loadingState}\n pageBackgroundColor={\n editor.documentTheme === "dark" ? "#0a0a0a" : undefined\n }\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n onPageCountChange={handlePageCountChange}\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n'export function DocxEditorSource() {return <HighlightedCodeBlock code={docxEditorSourceCode} />diff --git a/apps/v4/components/docx-viewer-docs.tsx b/apps/v4/components/docx-viewer-docs.tsxindex ceedb76..aa5cf94 100644--- a/apps/v4/components/docx-viewer-docs.tsx+++ b/apps/v4/components/docx-viewer-docs.tsx@@ -94,7 +94,7 @@ export function DocxViewerExample() {}`const docxViewerSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n useDocxEditor,\n useDocxViewerThumbnails,\n type DocxDocumentTheme,\n type DocxEditorController,\n} from "@extend-ai/react-docx"\nimport {\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n SidebarLeftIcon,\n Sun03Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport { Separator } from "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_SOURCE_CACHE_LIMIT = 3\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst ZOOM_OPTIONS = [10, 25, 50, 75, 100, 125, 150, 175, 200, 400] as const\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\n\nconst docxFileCache = new Map<string, File>()\nconst docxFilePromiseCache = new Map<string, Promise<File>>()\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n}\n\nfunction getDocumentCacheKey(url: string, fileName?: string) {\n return `${url.split("?")[0] ?? url}::${fileName ?? ""}`\n}\n\nfunction rememberDocxFile(cacheKey: string, file: File) {\n if (docxFileCache.has(cacheKey)) {\n docxFileCache.delete(cacheKey)\n }\n\n docxFileCache.set(cacheKey, file)\n\n while (docxFileCache.size > DOCX_SOURCE_CACHE_LIMIT) {\n const oldestKey = docxFileCache.keys().next().value\n if (!oldestKey) break\n docxFileCache.delete(oldestKey)\n }\n}\n\nasync function loadCachedDocxFile(\n url: string,\n displayFileName: string,\n cacheKey: string\n): Promise<File> {\n const cachedFile = docxFileCache.get(cacheKey)\n if (cachedFile) return cachedFile\n\n const pendingRequest = docxFilePromiseCache.get(cacheKey)\n if (pendingRequest) return pendingRequest\n\n const nextRequest = fetch(url)\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n const docxFile = new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n\n rememberDocxFile(cacheKey, docxFile)\n return docxFile\n })\n .finally(() => {\n docxFilePromiseCache.delete(cacheKey)\n })\n\n docxFilePromiseCache.set(cacheKey, nextRequest)\n return nextRequest\n}\n\nfunction formatDocumentName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "document.docx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {\n const currentIndex = ZOOM_OPTIONS.indexOf(\n currentZoomScale as (typeof ZOOM_OPTIONS)[number]\n )\n let fallbackIndex = -1\n\n if (direction > 0) {\n fallbackIndex = ZOOM_OPTIONS.findIndex((value) => value > currentZoomScale)\n } else {\n for (let index = ZOOM_OPTIONS.length - 1; index >= 0; index -= 1) {\n if (ZOOM_OPTIONS[index] < currentZoomScale) {\n fallbackIndex = index\n break\n }\n }\n }\n\n const resolvedIndex = currentIndex >= 0 ? currentIndex : fallbackIndex\n if (resolvedIndex < 0) return currentZoomScale\n\n const nextIndex = Math.min(\n Math.max(resolvedIndex + direction, 0),\n ZOOM_OPTIONS.length - 1\n )\n\n return ZOOM_OPTIONS[nextIndex] ?? currentZoomScale\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\n}\n\nfunction useControllableDarkMode({\n defaultIsDark = false,\n isDark,\n onIsDarkChange,\n}: {\n defaultIsDark?: boolean\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n}) {\n const [uncontrolledIsDark, setUncontrolledIsDark] =\n React.useState(defaultIsDark)\n const resolvedIsDark = isDark ?? uncontrolledIsDark\n\n const setIsDark = React.useCallback(\n (nextIsDark: boolean) => {\n if (isDark === undefined) {\n setUncontrolledIsDark(nextIsDark)\n }\n\n onIsDarkChange?.(nextIsDark)\n },\n [isDark, onIsDarkChange]\n )\n\n return [resolvedIsDark, setIsDark] as const\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction ViewerLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction DocxToolbar({\n activePage,\n controlsDisabled,\n isDark,\n onIsDarkChange,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showNightRenderToggle: boolean\n zoomScale: number\n}) {\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n\n return (\n <div className="flex min-h-12 items-center justify-between gap-3 overflow-x-auto overflow-y-hidden border-b bg-background px-3">\n <TooltipProvider>\n <div className="flex items-center gap-2">\n <ToolbarTooltip label="Toggle thumbnails">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Toggle thumbnails"\n disabled={controlsDisabled}\n onClick={onToggleSidebar}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <div className="text-sm whitespace-nowrap text-primary">\n Page {pageCount ? activePage : 1} of {pageCount || "-"}\n </div>\n </div>\n <div className="ml-auto flex shrink-0 items-center gap-1">\n {showNightRenderToggle ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <ToolbarTooltip\n label={isDark ? "Use light document" : "Use dark document"}\n >\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled}\n aria-label={\n isDark ? "Use light document" : "Use dark document"\n }\n onClick={() => onIsDarkChange(!isDark)}\n >\n <HugeiconsIcon\n icon={isDark ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled || !canZoomOut}\n aria-label="Zoom out"\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, -1)\n )\n }\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={zoomScale.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align="end" alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled || !canZoomIn}\n aria-label="Zoom in"\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarTooltip label="Upload DOCX">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Upload DOCX"\n onClick={onUploadClick}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n showMetadata={false}\n className={cn(\n "w-full rounded-sm border shadow-xs transition-[border-color,box-shadow] duration-150",\n isActive && "border-primary shadow-sm"\n )}\n />\n )\n}\n\nexport function DocxViewerPreview({\n className,\n defaultThumbnailSidebarOpen = true,\n defaultIsDark = false,\n fileName,\n isDark: controlledIsDark,\n onIsDarkChange,\n rounded = false,\n src,\n}: {\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n defaultIsDark?: boolean\n fileName?: string\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n rounded?: boolean\n src?: string\n}) {\n const [effectiveIsDark, setIsDark] = useControllableDarkMode({\n defaultIsDark,\n isDark: controlledIsDark,\n onIsDarkChange,\n })\n\n return (\n <DocxViewerContent\n className={className}\n defaultThumbnailSidebarOpen={defaultThumbnailSidebarOpen}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setIsDark}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction DocxViewerContent({\n className,\n defaultThumbnailSidebarOpen,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n defaultThumbnailSidebarOpen: boolean\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(\n defaultThumbnailSidebarOpen\n )\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const cacheKey = React.useMemo(\n () =>\n uploadedDocxFile?.identity ??\n (url ? getDocumentCacheKey(url, displayFileName) : "docx-empty"),\n [displayFileName, uploadedDocxFile?.identity, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { importDocxFile, setDocumentTheme, status } = editor\n const [reportedPageCount, setReportedPageCount] = React.useState(0)\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, editor.totalPages, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const [zoomScale, setZoomScale] = React.useState(50)\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <ViewerLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(50)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\n ? await loadCachedDocxFile(url, displayFileName, cacheKey)\n : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : "Unknown DOCX load error"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n void load()\n\n return () => {\n isCurrent = false\n }\n }, [cacheKey, displayFileName, importDocxFile, uploadedDocxFile, url])\n\n React.useEffect(() => {\n if (url) {\n setUploadedDocxFile(null)\n }\n }, [url])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n \'[data-docx-page-wrapper="true"][data-index]\'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback((pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport || !page) return\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n }, [])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomScale(50)\n setActivePage(1)\n setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <DocxToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n isDark={effectiveIsDark}\n onIsDarkChange={setNightRenderEnabled}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showNightRenderToggle={shouldRenderNightMode}\n zoomScale={zoomScale}\n />\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <div className="h-full overflow-auto">\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 rounded-sm border bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs text-muted-foreground shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </div>\n </DocumentViewerThumbnailSidebar>\n <div\n ref={viewportRef}\n className={cn(\n "min-h-0 flex-1 overflow-auto p-4",\n rounded && "rounded-b-lg"\n )}\n style={{ backgroundColor: viewerBackgroundColor }}\n >\n {!url && !uploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">Upload a DOCX to preview</div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to display DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="mx-auto flex min-h-full justify-center">\n <div\n className={cn(\n "origin-top",\n effectiveIsDark && "docx-night-reader-shell"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode="read-only"\n loadingState={loadingState}\n pageBackgroundColor={effectiveIsDark ? "#0a0a0a" : undefined}\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n onPageCountChange={handlePageCountChange}\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n useDocxEditor,\n useDocxViewerThumbnails,\n type DocxDocumentTheme,\n type DocxEditorController,\n} from "@extend-ai/react-docx"\nimport {\n MinusSignCircleIcon,\n Moon02Icon,\n PlusSignCircleIcon,\n SidebarLeftIcon,\n Sun03Icon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/ui/document-viewer-sidebar"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Spinner } from "@/components/ui/spinner"\nimport { Separator } from "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_SOURCE_CACHE_LIMIT = 3\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst ZOOM_OPTIONS = [10, 25, 50, 75, 100, 125, 150, 175, 200, 400] as const\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\n\nconst docxFileCache = new Map<string, File>()\nconst docxFilePromiseCache = new Map<string, Promise<File>>()\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n}\n\nfunction getDocumentCacheKey(url: string, fileName?: string) {\n return `${url.split("?")[0] ?? url}::${fileName ?? ""}`\n}\n\nfunction rememberDocxFile(cacheKey: string, file: File) {\n if (docxFileCache.has(cacheKey)) {\n docxFileCache.delete(cacheKey)\n }\n\n docxFileCache.set(cacheKey, file)\n\n while (docxFileCache.size > DOCX_SOURCE_CACHE_LIMIT) {\n const oldestKey = docxFileCache.keys().next().value\n if (!oldestKey) break\n docxFileCache.delete(oldestKey)\n }\n}\n\nasync function loadCachedDocxFile(\n url: string,\n displayFileName: string,\n cacheKey: string\n): Promise<File> {\n const cachedFile = docxFileCache.get(cacheKey)\n if (cachedFile) return cachedFile\n\n const pendingRequest = docxFilePromiseCache.get(cacheKey)\n if (pendingRequest) return pendingRequest\n\n const nextRequest = fetch(url)\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n const docxFile = new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n\n rememberDocxFile(cacheKey, docxFile)\n return docxFile\n })\n .finally(() => {\n docxFilePromiseCache.delete(cacheKey)\n })\n\n docxFilePromiseCache.set(cacheKey, nextRequest)\n return nextRequest\n}\n\nfunction formatDocumentName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "document.docx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {\n const currentIndex = ZOOM_OPTIONS.indexOf(\n currentZoomScale as (typeof ZOOM_OPTIONS)[number]\n )\n let fallbackIndex = -1\n\n if (direction > 0) {\n fallbackIndex = ZOOM_OPTIONS.findIndex((value) => value > currentZoomScale)\n } else {\n for (let index = ZOOM_OPTIONS.length - 1; index >= 0; index -= 1) {\n if (ZOOM_OPTIONS[index] < currentZoomScale) {\n fallbackIndex = index\n break\n }\n }\n }\n\n const resolvedIndex = currentIndex >= 0 ? currentIndex : fallbackIndex\n if (resolvedIndex < 0) return currentZoomScale\n\n const nextIndex = Math.min(\n Math.max(resolvedIndex + direction, 0),\n ZOOM_OPTIONS.length - 1\n )\n\n return ZOOM_OPTIONS[nextIndex] ?? currentZoomScale\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n\n React.useEffect(() => {\n if (!isLoading) {\n setShowSpinner(false)\n return\n }\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return showSpinner\n}\n\nfunction useControllableDarkMode({\n defaultIsDark = false,\n isDark,\n onIsDarkChange,\n}: {\n defaultIsDark?: boolean\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n}) {\n const [uncontrolledIsDark, setUncontrolledIsDark] =\n React.useState(defaultIsDark)\n const resolvedIsDark = isDark ?? uncontrolledIsDark\n\n const setIsDark = React.useCallback(\n (nextIsDark: boolean) => {\n if (isDark === undefined) {\n setUncontrolledIsDark(nextIsDark)\n }\n\n onIsDarkChange?.(nextIsDark)\n },\n [isDark, onIsDarkChange]\n )\n\n return [resolvedIsDark, setIsDark] as const\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction ViewerLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction DocxToolbar({\n activePage,\n controlsDisabled,\n isDark,\n onIsDarkChange,\n onToggleSidebar,\n onUploadClick,\n pageCount,\n setZoomScale,\n showNightRenderToggle,\n zoomScale,\n}: {\n activePage: number\n controlsDisabled: boolean\n isDark: boolean\n onIsDarkChange: (checked: boolean) => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n pageCount: number\n setZoomScale: React.Dispatch<React.SetStateAction<number>>\n showNightRenderToggle: boolean\n zoomScale: number\n}) {\n const canZoomIn = zoomScale < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = zoomScale > ZOOM_OPTIONS[0]\n\n return (\n <div className="flex min-h-12 items-center justify-between gap-3 overflow-x-auto overflow-y-hidden border-b bg-background px-3">\n <TooltipProvider>\n <div className="flex items-center gap-2">\n <ToolbarTooltip label="Toggle thumbnails">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Toggle thumbnails"\n disabled={controlsDisabled}\n onClick={onToggleSidebar}\n >\n <HugeiconsIcon icon={SidebarLeftIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <div className="text-sm whitespace-nowrap text-primary">\n Page {pageCount ? activePage : 1} of {pageCount || "-"}\n </div>\n </div>\n <div className="ml-auto flex shrink-0 items-center gap-1">\n {showNightRenderToggle ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <ToolbarTooltip\n label={isDark ? "Use light document" : "Use dark document"}\n >\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled}\n aria-label={\n isDark ? "Use light document" : "Use dark document"\n }\n onClick={() => onIsDarkChange(!isDark)}\n >\n <HugeiconsIcon\n icon={isDark ? Sun03Icon : Moon02Icon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </>\n ) : null}\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled || !canZoomOut}\n aria-label="Zoom out"\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, -1)\n )\n }\n >\n <HugeiconsIcon icon={MinusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Select\n value={zoomScale.toString()}\n onValueChange={(value) => setZoomScale(Number(value))}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[84px] min-w-[84px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(zoomScale)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align="end" alignItemWithTrigger={false}>\n {ZOOM_OPTIONS.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled || !canZoomIn}\n aria-label="Zoom in"\n onClick={() =>\n setZoomScale((currentZoomScale) =>\n getNextZoomScale(currentZoomScale, 1)\n )\n }\n >\n <HugeiconsIcon icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <ToolbarTooltip label="Upload DOCX">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Upload DOCX"\n onClick={onUploadClick}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="rounded-md bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n renderDocumentPreview={false}\n isLoading={isLoading}\n hasError={hasError}\n showMetadata={false}\n className={cn(\n "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",\n isActive && "shadow-sm"\n )}\n />\n )\n}\n\nexport function DocxViewerPreview({\n className,\n defaultThumbnailSidebarOpen = true,\n defaultIsDark = false,\n fileName,\n isDark: controlledIsDark,\n onIsDarkChange,\n rounded = false,\n src,\n}: {\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n defaultIsDark?: boolean\n fileName?: string\n isDark?: boolean\n onIsDarkChange?: (isDark: boolean) => void\n rounded?: boolean\n src?: string\n}) {\n const [effectiveIsDark, setIsDark] = useControllableDarkMode({\n defaultIsDark,\n isDark: controlledIsDark,\n onIsDarkChange,\n })\n\n return (\n <DocxViewerContent\n className={className}\n defaultThumbnailSidebarOpen={defaultThumbnailSidebarOpen}\n effectiveIsDark={effectiveIsDark}\n fileName={fileName}\n rounded={rounded}\n setNightRenderEnabled={setIsDark}\n shouldRenderNightMode\n url={src}\n />\n )\n}\n\nfunction DocxViewerContent({\n className,\n defaultThumbnailSidebarOpen,\n effectiveIsDark,\n fileName,\n rounded,\n setNightRenderEnabled,\n shouldRenderNightMode,\n url,\n}: {\n className?: string\n defaultThumbnailSidebarOpen: boolean\n effectiveIsDark: boolean\n fileName?: string\n rounded: boolean\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [activePage, setActivePage] = React.useState(1)\n const [sidebarOpen, setSidebarOpen] = React.useState(\n defaultThumbnailSidebarOpen\n )\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n uploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [fileName, uploadedDocxFile?.file.name, url]\n )\n const cacheKey = React.useMemo(\n () =>\n uploadedDocxFile?.identity ??\n (url ? getDocumentCacheKey(url, displayFileName) : "docx-empty"),\n [displayFileName, uploadedDocxFile?.identity, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { importDocxFile, setDocumentTheme, status } = editor\n const [reportedPageCount, setReportedPageCount] = React.useState(0)\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, editor.totalPages, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n []\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const [zoomScale, setZoomScale] = React.useState(50)\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <ViewerLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const hasDocument = Boolean(url || uploadedDocxFile)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setZoomScale(50)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [url])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n setLoadError(status)\n setIsLoadingDocument(false)\n }\n }, [status])\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n if (!uploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n uploadedDocxFile?.file ??\n (url\n ? await loadCachedDocxFile(url, displayFileName, cacheKey)\n : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : "Unknown DOCX load error"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n void load()\n\n return () => {\n isCurrent = false\n }\n }, [cacheKey, displayFileName, importDocxFile, uploadedDocxFile, url])\n\n React.useEffect(() => {\n if (url) {\n setUploadedDocxFile(null)\n }\n }, [url])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n \'[data-docx-page-wrapper="true"][data-index]\'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback((pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport || !page) return\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n }, [])\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomScale(50)\n setActivePage(1)\n setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n })\n }\n\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n <DocxToolbar\n activePage={activePage}\n controlsDisabled={controlsDisabled}\n isDark={effectiveIsDark}\n onIsDarkChange={setNightRenderEnabled}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n setZoomScale={setZoomScale}\n showNightRenderToggle={shouldRenderNightMode}\n zoomScale={zoomScale}\n />\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={Boolean(sidebarOpen && (pageCount || isLoadingDocument))}\n >\n <div className="h-full overflow-auto">\n <div className="p-4">\n {isLoadingDocument ? (\n <>\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </>\n ) : (\n <div className="flex flex-col items-center gap-3">\n {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (\n <Button\n key={thumbnail.pageIndex}\n type="button"\n variant="ghost"\n size="sm"\n className={cn(\n "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onClick={() => scrollToPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n !thumbnail.isMounted &&\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </Button>\n ))}\n </div>\n )}\n </div>\n </div>\n </DocumentViewerThumbnailSidebar>\n <div\n ref={viewportRef}\n className={cn(\n "min-h-0 flex-1 overflow-auto p-4",\n rounded && "rounded-b-lg"\n )}\n style={{ backgroundColor: viewerBackgroundColor }}\n >\n {!url && !uploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">Upload a DOCX to preview</div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <HugeiconsIcon icon={Upload01Icon} className="size-4" />\n Upload DOCX\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to display DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="mx-auto flex min-h-full justify-center">\n <div\n className={cn(\n "origin-top",\n effectiveIsDark && "docx-night-reader-shell"\n )}\n style={{ zoom: zoomScale / 100 }}\n >\n <DocxEditorViewer\n editor={editor}\n mode="read-only"\n loadingState={loadingState}\n pageBackgroundColor={effectiveIsDark ? "#0a0a0a" : undefined}\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n onPageCountChange={handlePageCountChange}\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n'export function DocxViewerSource() {return <HighlightedCodeBlock code={docxViewerSourceCode} />diff --git a/apps/v4/components/e-signature-docs.tsx b/apps/v4/components/e-signature-docs.tsxindex 1a39d74..b30d5bb 100644--- a/apps/v4/components/e-signature-docs.tsx+++ b/apps/v4/components/e-signature-docs.tsx@@ -41,24 +41,26 @@ type SignatureField = {imageDataUrl?: string}-const PDF_URL = "/samples/attention.pdf"+const PDF_URL = "/samples/loan-application.pdf"const PAGE_WIDTH = 612const PAGE_HEIGHT = 792const DEFAULT_ZOOM = 0.75const MIN_FIELD_WIDTH = 96const MIN_FIELD_HEIGHT = 34const SIGNATURE_PAD_PADDING = 8+const SIGNATURE_PAD_BACKGROUND_COLOR = "#ffffff"+const SIGNATURE_PAD_PEN_COLOR = "#000000"const DEFAULT_SIGNATURE_ASPECT_RATIO = 3const INITIAL_FIELD: SignatureField = {id: "signature-1",- label: "Signature1",+ label: "Loan originator signature",page: 1,bbox: {- x: 300,- y: 504,- width: 250,- height: 58,+ x: 88,+ y: 177,+ width: 294,+ height: 42,},}@@ -331,7 +333,7 @@ function SignatureDialog({const signaturePad = new SignaturePadConstructor(canvas, {minWidth: 1.4,maxWidth: 2.8,- penColor: "rgb(15, 23, 42)",+ penColor: SIGNATURE_PAD_PEN_COLOR,})signaturePadRef.current = signaturePad@@ -401,13 +403,14 @@ function SignatureDialog({><divclassName={cn(- "relative overflow-hidden rounded-md border border-dashed border-input bg-background shadow-xs",+ "relative overflow-hidden rounded-md border border-dashed border-input bg-white shadow-xs",isReady ? "cursor-crosshair" : "cursor-wait")}style={{width: guideSize ? `${guideSize.width}px` : undefined,height: guideSize ? `${guideSize.height}px` : undefined,opacity: guideSize ? 1 : 0,+ backgroundColor: SIGNATURE_PAD_BACKGROUND_COLOR,}}><canvas@@ -416,7 +419,10 @@ function SignatureDialog({"absolute inset-0 size-full touch-none",!isReady && "pointer-events-none")}- style={{ touchAction: "none" }}+ style={{+ backgroundColor: SIGNATURE_PAD_BACKGROUND_COLOR,+ touchAction: "none",+ }}/></div></div>@@ -539,7 +545,7 @@ async function downloadSignedPdf(field: SignatureField) {const url = URL.createObjectURL(blob)const anchor = document.createElement("a")anchor.href = url- anchor.download = "signed-attention.pdf"+ anchor.download = "signed-loan-application.pdf"anchor.click()URL.revokeObjectURL(url)}@@ -892,11 +898,11 @@ function ESignatureExample() {<><div className="flex h-[420px] flex-col gap-2 bg-background p-3"><SignatureFieldExampleCard- label="Signature1"+ label="Loan originator signature"status={signatureSigned ? "signed" : "unsigned"}pageLabel="p. 1"description={- signatureSigned ? "Completed just now" : "250 x 58 field"+ signatureSigned ? "Completed just now" : "294 x 42 field"}actionLabel={signatureSigned ? "Edit signature" : undefined}onAction={() => setDialogOpen(true)}@@ -983,9 +989,9 @@ export function ESignatureExample() {return (<div className="flex h-[420px] flex-col gap-2 bg-background p-3"><SignatureFieldCard- label="Signature1"+ label="Loan originator signature"pageLabel="p. 1"- description="250 x 58 field"+ description="294 x 42 field"onAction={() => {}}/><SignatureFieldCard@@ -1001,7 +1007,7 @@ export function ESignatureExample() {}`const eSignatureSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n Download01Icon,\n FilePenIcon,\n Pen01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport type SignaturePad from "signature_pad"\n\nimport { cn } from "@/lib/utils"\nimport { PDFViewer } from "@/components/ui/pdf-viewer"\nimport { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"\nimport { Button } from "@/registry/new-york-v4/ui/button"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogPanel,\n DialogTitle,\n} from "@/registry/new-york-v4/ui/dialog"\nimport { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"\n\ntype BoundingBox = {\n x: number\n y: number\n width: number\n height: number\n}\n\ntype SignatureField = {\n id: string\n label: string\n page: number\n bbox: BoundingBox\n imageDataUrl?: string\n}\n\nconst PAGE_WIDTH = 612\nconst PAGE_HEIGHT = 792\nconst DEFAULT_ZOOM = 0.75\nconst SIGNATURE_PAD_PADDING = 8\nconst DEFAULT_SIGNATURE_ASPECT_RATIO = 3\n\nconst INITIAL_FIELD: SignatureField = {\n id: "signature-1",\n label: "Signature",\n page: 1,\n bbox: { x: 300, y: 504, width: 250, height: 58 },\n}\n\nfunction bboxToStyle(bbox: BoundingBox): React.CSSProperties {\n return {\n left: `${(bbox.x / PAGE_WIDTH) * 100}%`,\n top: `${(bbox.y / PAGE_HEIGHT) * 100}%`,\n width: `${(bbox.width / PAGE_WIDTH) * 100}%`,\n height: `${(bbox.height / PAGE_HEIGHT) * 100}%`,\n }\n}\n\nfunction getSignatureAspectRatio(bbox?: BoundingBox): number {\n if (!bbox || bbox.width <= 0 || bbox.height <= 0) {\n return DEFAULT_SIGNATURE_ASPECT_RATIO\n }\n\n return bbox.width / bbox.height\n}\n\nfunction getSignatureGuideSize({\n containerWidth,\n containerHeight,\n aspectRatio,\n}: {\n containerWidth: number\n containerHeight: number\n aspectRatio: number\n}): { width: number; height: number } {\n const maxWidth = Math.max(containerWidth - SIGNATURE_PAD_PADDING * 2, 1)\n const maxHeight = Math.max(containerHeight - SIGNATURE_PAD_PADDING * 2, 1)\n\n if (maxWidth / maxHeight > aspectRatio) {\n const height = maxHeight\n return {\n width: height * aspectRatio,\n height,\n }\n }\n\n const width = maxWidth\n return {\n width,\n height: width / aspectRatio,\n }\n}\n\nfunction getCroppedSignatureDataUrl(canvas: HTMLCanvasElement): string {\n const context = canvas.getContext("2d")\n if (!context) {\n return canvas.toDataURL("image/png")\n }\n\n const { width, height } = canvas\n const imageData = context.getImageData(0, 0, width, height)\n const { data } = imageData\n let minX = width\n let minY = height\n let maxX = -1\n let maxY = -1\n\n for (let y = 0; y < height; y += 1) {\n for (let x = 0; x < width; x += 1) {\n const alpha = data[(y * width + x) * 4 + 3]\n if (alpha === 0) continue\n\n minX = Math.min(minX, x)\n minY = Math.min(minY, y)\n maxX = Math.max(maxX, x)\n maxY = Math.max(maxY, y)\n }\n }\n\n if (maxX < minX || maxY < minY) {\n return canvas.toDataURL("image/png")\n }\n\n const croppedWidth = maxX - minX + 1\n const croppedHeight = maxY - minY + 1\n const croppedCanvas = document.createElement("canvas")\n croppedCanvas.width = croppedWidth\n croppedCanvas.height = croppedHeight\n\n const croppedContext = croppedCanvas.getContext("2d")\n if (!croppedContext) {\n return canvas.toDataURL("image/png")\n }\n\n croppedContext.drawImage(\n canvas,\n minX,\n minY,\n croppedWidth,\n croppedHeight,\n 0,\n 0,\n croppedWidth,\n croppedHeight\n )\n\n return croppedCanvas.toDataURL("image/png")\n}\n\nfunction SignatureDialog({\n open,\n fieldBbox,\n initialValue,\n onOpenChange,\n onConfirm,\n}: {\n open: boolean\n fieldBbox: BoundingBox\n initialValue?: string\n onOpenChange: (open: boolean) => void\n onConfirm: (value: string) => void\n}) {\n const canvasContainerRef = React.useRef<HTMLDivElement>(null)\n const canvasRef = React.useRef<HTMLCanvasElement>(null)\n const signaturePadRef = React.useRef<SignaturePad | null>(null)\n const [isReady, setIsReady] = React.useState(false)\n const [hasSignature, setHasSignature] = React.useState(false)\n const [guideSize, setGuideSize] = React.useState<{\n width: number\n height: number\n } | null>(null)\n const signatureAspectRatio = React.useMemo(\n () => getSignatureAspectRatio(fieldBbox),\n [fieldBbox]\n )\n\n React.useEffect(() => {\n if (!open) {\n setGuideSize(null)\n return\n }\n\n let frameId = 0\n let resizeObserver: ResizeObserver | null = null\n\n const updateGuideSize = (container?: HTMLDivElement | null) => {\n const currentContainer = container ?? canvasContainerRef.current\n if (\n !currentContainer ||\n currentContainer.clientWidth <= 0 ||\n currentContainer.clientHeight <= 0\n ) {\n return false\n }\n\n const nextSize = getSignatureGuideSize({\n containerWidth: currentContainer.clientWidth,\n containerHeight: currentContainer.clientHeight,\n aspectRatio: signatureAspectRatio,\n })\n\n setGuideSize((previousSize) => {\n if (\n previousSize &&\n Math.abs(previousSize.width - nextSize.width) < 0.5 &&\n Math.abs(previousSize.height - nextSize.height) < 0.5\n ) {\n return previousSize\n }\n\n return nextSize\n })\n\n return true\n }\n\n const connect = () => {\n const container = canvasContainerRef.current\n if (!updateGuideSize(container)) {\n frameId = window.requestAnimationFrame(connect)\n return\n }\n\n if (container) {\n resizeObserver = new ResizeObserver(() => {\n updateGuideSize(container)\n })\n resizeObserver.observe(container)\n }\n }\n\n connect()\n\n return () => {\n window.cancelAnimationFrame(frameId)\n resizeObserver?.disconnect()\n }\n }, [open, signatureAspectRatio])\n\n React.useEffect(() => {\n if (!open || !guideSize || guideSize.width <= 1 || guideSize.height <= 1) {\n signaturePadRef.current?.off()\n signaturePadRef.current = null\n setIsReady(false)\n if (!open) {\n setHasSignature(false)\n }\n return\n }\n\n let cancelled = false\n let resizeObserver: ResizeObserver | null = null\n\n const syncCanvasSize = (canvas: HTMLCanvasElement) => {\n const width = Math.max(canvas.offsetWidth, 1)\n const height = Math.max(canvas.offsetHeight, 1)\n const ratio = Math.max(window.devicePixelRatio || 1, 1)\n\n canvas.style.width = `${width}px`\n canvas.style.height = `${height}px`\n canvas.width = Math.floor(width * ratio)\n canvas.height = Math.floor(height * ratio)\n const context = canvas.getContext("2d")\n context?.setTransform(1, 0, 0, 1, 0, 0)\n context?.scale(ratio, ratio)\n\n return { width, height, ratio }\n }\n\n const initialize = async () => {\n const canvas = canvasRef.current\n if (!canvas) return\n\n const { default: SignaturePadConstructor } = await import("signature_pad")\n if (cancelled) return\n\n const signaturePad = new SignaturePadConstructor(canvas, {\n minWidth: 1.4,\n maxWidth: 2.8,\n penColor: "rgb(15, 23, 42)",\n })\n\n signaturePadRef.current = signaturePad\n\n const loadSignature = async (dataUrl?: string) => {\n const size = syncCanvasSize(canvas)\n\n if (dataUrl) {\n await signaturePad.fromDataURL(dataUrl, size)\n setHasSignature(true)\n return\n }\n\n signaturePad.clear()\n setHasSignature(false)\n }\n\n await loadSignature(initialValue)\n if (cancelled) return\n\n signaturePad.addEventListener("endStroke", () => {\n setHasSignature(true)\n })\n\n resizeObserver = new ResizeObserver(() => {\n const currentCanvas = canvasRef.current\n const currentSignaturePad = signaturePadRef.current\n if (!currentCanvas || !currentSignaturePad) return\n\n const previousSignature = currentSignaturePad.isEmpty()\n ? undefined\n : currentSignaturePad.toDataURL("image/png")\n void loadSignature(previousSignature)\n })\n resizeObserver.observe(canvas)\n setIsReady(true)\n }\n\n const animationFrame = window.requestAnimationFrame(() => {\n void initialize()\n })\n\n return () => {\n cancelled = true\n window.cancelAnimationFrame(animationFrame)\n resizeObserver?.disconnect()\n signaturePadRef.current?.off()\n signaturePadRef.current = null\n setIsReady(false)\n }\n }, [open, guideSize, initialValue])\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className="max-w-xl">\n <DialogHeader>\n <DialogTitle>Add signature</DialogTitle>\n <DialogDescription>\n Draw a signature to place it into the selected PDF field.\n </DialogDescription>\n </DialogHeader>\n <DialogPanel>\n <div className="rounded-xl border bg-muted/30 p-3">\n <div\n ref={canvasContainerRef}\n className="flex h-56 w-full items-center justify-center overflow-hidden rounded-lg border bg-muted/40 p-2"\n >\n <div\n className={cn(\n "relative overflow-hidden rounded-md border border-dashed border-input bg-background shadow-xs",\n isReady ? "cursor-crosshair" : "cursor-wait"\n )}\n style={{\n width: guideSize ? `${guideSize.width}px` : undefined,\n height: guideSize ? `${guideSize.height}px` : undefined,\n opacity: guideSize ? 1 : 0,\n }}\n >\n <canvas\n ref={canvasRef}\n className={cn(\n "absolute inset-0 size-full touch-none",\n !isReady && "pointer-events-none"\n )}\n style={{ touchAction: "none" }}\n />\n </div>\n </div>\n </div>\n </DialogPanel>\n <DialogFooter className="sm:justify-between">\n <Button\n type="button"\n variant="outline"\n disabled={!isReady}\n onClick={() => {\n signaturePadRef.current?.clear()\n setHasSignature(false)\n }}\n >\n Clear\n </Button>\n <div className="flex flex-col-reverse gap-2 sm:flex-row">\n <Button\n type="button"\n variant="outline"\n onClick={() => onOpenChange(false)}\n >\n Cancel\n </Button>\n <Button\n type="button"\n disabled={!isReady || !hasSignature}\n onClick={() => {\n const canvas = canvasRef.current\n if (!canvas) return\n\n onConfirm(getCroppedSignatureDataUrl(canvas))\n onOpenChange(false)\n }}\n >\n Confirm\n </Button>\n </div>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\nfunction SignatureFieldOverlay({\n field,\n onOpen,\n}: {\n field: SignatureField\n onOpen: () => void\n}) {\n return (\n <button\n type="button"\n className={cn(\n "absolute z-20 overflow-hidden rounded-[3px] border border-blue-500/70 transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",\n field.imageDataUrl\n ? "bg-transparent shadow-none hover:bg-blue-500/5"\n : "bg-blue-500/10 hover:bg-blue-500/15"\n )}\n style={bboxToStyle(field.bbox)}\n onClick={onOpen}\n >\n {field.imageDataUrl ? (\n <img\n src={field.imageDataUrl}\n alt=""\n className="size-full object-contain"\n draggable={false}\n />\n ) : (\n <span className="flex size-full items-center justify-center gap-1.5 px-2 text-[11px] font-medium text-blue-700 dark:text-blue-300">\n <HugeiconsIcon icon={Pen01Icon} className="size-3.5" />\n Signature\n </span>\n )}\n </button>\n )\n}\n\nasync function downloadSignedPdf({\n file,\n field,\n}: {\n file: string\n field: SignatureField\n}) {\n const { PDFDocument } = await import("pdf-lib")\n const existingPdfBytes = await fetch(file).then((response) =>\n response.arrayBuffer()\n )\n const pdfDocument = await PDFDocument.load(existingPdfBytes)\n const page = pdfDocument.getPage(field.page - 1)\n\n if (field.imageDataUrl) {\n const signatureImage = await pdfDocument.embedPng(field.imageDataUrl)\n const { width: pageWidth, height: pageHeight } = page.getSize()\n const scaleX = pageWidth / PAGE_WIDTH\n const scaleY = pageHeight / PAGE_HEIGHT\n const fieldWidth = field.bbox.width * scaleX\n const fieldHeight = field.bbox.height * scaleY\n const imageAspectRatio = signatureImage.width / signatureImage.height\n const fieldAspectRatio = fieldWidth / fieldHeight\n const drawWidth =\n fieldAspectRatio > imageAspectRatio\n ? fieldHeight * imageAspectRatio\n : fieldWidth\n const drawHeight =\n fieldAspectRatio > imageAspectRatio\n ? fieldHeight\n : fieldWidth / imageAspectRatio\n const fieldX = field.bbox.x * scaleX\n const fieldY = pageHeight - (field.bbox.y + field.bbox.height) * scaleY\n\n page.drawImage(signatureImage, {\n x: fieldX + (fieldWidth - drawWidth) / 2,\n y: fieldY + (fieldHeight - drawHeight) / 2,\n width: drawWidth,\n height: drawHeight,\n })\n }\n\n const bytes = await pdfDocument.save()\n const blob = new Blob([new Uint8Array(bytes)], { type: "application/pdf" })\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n anchor.href = url\n anchor.download = "signed-document.pdf"\n anchor.click()\n URL.revokeObjectURL(url)\n}\n\nfunction SignatureFieldsPanel({\n field,\n className,\n canExport,\n isDownloading,\n onSign,\n onClear,\n onDownload,\n}: {\n field: SignatureField\n className?: string\n canExport: boolean\n isDownloading: boolean\n onSign: () => void\n onClear: () => void\n onDownload: () => void\n}) {\n return (\n <aside className={cn("flex min-h-0 flex-col bg-background", className)}>\n <ScrollArea className="min-h-0 flex-1" scrollFade>\n <div className="space-y-4 p-4">\n <div className="space-y-1">\n <h3 className="text-sm font-medium">Signature fields</h3>\n <p className="text-xs text-muted-foreground">\n Review fields, collect signatures, and export a signed PDF.\n </p>\n </div>\n <div className="rounded-lg border bg-background p-3">\n <div className="flex items-start gap-3">\n <div className="grid size-9 shrink-0 place-items-center rounded-md bg-blue-500/10 text-blue-600 dark:text-blue-300">\n <HugeiconsIcon icon={FilePenIcon} className="size-4" />\n </div>\n <div className="min-w-0 flex-1">\n <div className="flex items-center justify-between gap-2">\n <div className="text-sm font-medium">{field.label}</div>\n <div\n className={cn(\n "rounded-full px-2 py-0.5 text-xs",\n field.imageDataUrl\n ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-300"\n : "bg-muted text-muted-foreground"\n )}\n >\n {field.imageDataUrl ? "Signed" : "Unsigned"}\n </div>\n </div>\n <div className="mt-2 text-xs text-muted-foreground">\n {Math.round(field.bbox.width)} x{" "}\n {Math.round(field.bbox.height)} on page {field.page}\n </div>\n <div className="mt-3 flex gap-2">\n <Button\n type="button"\n size="sm"\n variant={field.imageDataUrl ? "outline" : "default"}\n className="flex-1"\n onClick={onSign}\n >\n <HugeiconsIcon icon={Pen01Icon} className="size-4" />\n {field.imageDataUrl ? "Edit" : "Sign"}\n </Button>\n {field.imageDataUrl ? (\n <Button\n type="button"\n size="sm"\n variant="outline"\n onClick={onClear}\n >\n Clear\n </Button>\n ) : null}\n </div>\n </div>\n </div>\n </div>\n <Button\n type="button"\n className="w-full"\n disabled={!canExport || isDownloading}\n onClick={onDownload}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n {isDownloading ? "Exporting..." : "Export signed PDF"}\n </Button>\n </div>\n </ScrollArea>\n </aside>\n )\n}\n\nexport function ESignatureBlock({ file }: { file?: string }) {\n const [field, setField] = React.useState<SignatureField>(INITIAL_FIELD)\n const [dialogOpen, setDialogOpen] = React.useState(false)\n const [isDownloading, setIsDownloading] = React.useState(false)\n\n const handleDownload = React.useCallback(async () => {\n if (!file || !field.imageDataUrl) return\n\n setIsDownloading(true)\n try {\n await downloadSignedPdf({ file, field })\n } finally {\n setIsDownloading(false)\n }\n }, [field, file])\n\n return (\n <>\n <PdfBlockResizableShell\n autoSaveId="pdf-block-e-signature"\n left={\n <PDFViewer\n file={file}\n defaultZoom={DEFAULT_ZOOM}\n pageWidth={PAGE_WIDTH}\n pageHeight={PAGE_HEIGHT}\n toolbarActions={\n <Button\n type="button"\n size="sm"\n variant="outline"\n disabled={!file || !field.imageDataUrl || isDownloading}\n onClick={handleDownload}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n Download\n </Button>\n }\n renderPageOverlay={({ pageNumber }) =>\n pageNumber === field.page ? (\n <SignatureFieldOverlay\n field={field}\n onOpen={() => setDialogOpen(true)}\n />\n ) : null\n }\n />\n }\n right={\n <SignatureFieldsPanel\n field={field}\n canExport={Boolean(file && field.imageDataUrl)}\n isDownloading={isDownloading}\n onSign={() => setDialogOpen(true)}\n onClear={() =>\n setField((previousField) => ({\n ...previousField,\n imageDataUrl: undefined,\n }))\n }\n onDownload={handleDownload}\n />\n }\n />\n <SignatureDialog\n open={dialogOpen}\n fieldBbox={field.bbox}\n initialValue={field.imageDataUrl}\n onOpenChange={setDialogOpen}\n onConfirm={(imageDataUrl) => {\n setField((previousField) => ({ ...previousField, imageDataUrl }))\n }}\n />\n </>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n Download01Icon,\n FilePenIcon,\n Pen01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport type SignaturePad from "signature_pad"\n\nimport { cn } from "@/lib/utils"\nimport { PDFViewer } from "@/components/ui/pdf-viewer"\nimport { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"\nimport { Button } from "@/registry/new-york-v4/ui/button"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogPanel,\n DialogTitle,\n} from "@/registry/new-york-v4/ui/dialog"\nimport { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"\n\ntype BoundingBox = {\n x: number\n y: number\n width: number\n height: number\n}\n\ntype SignatureField = {\n id: string\n label: string\n page: number\n bbox: BoundingBox\n imageDataUrl?: string\n}\n\nconst PAGE_WIDTH = 612\nconst PAGE_HEIGHT = 792\nconst DEFAULT_ZOOM = 0.75\nconst SIGNATURE_PAD_PADDING = 8\nconst SIGNATURE_PAD_BACKGROUND_COLOR = "#ffffff"\nconst SIGNATURE_PAD_PEN_COLOR = "#000000"\nconst DEFAULT_SIGNATURE_ASPECT_RATIO = 3\n\nconst INITIAL_FIELD: SignatureField = {\n id: "signature-1",\n label: "Signature",\n page: 1,\n bbox: { x: 300, y: 504, width: 250, height: 58 },\n}\n\nfunction bboxToStyle(bbox: BoundingBox): React.CSSProperties {\n return {\n left: `${(bbox.x / PAGE_WIDTH) * 100}%`,\n top: `${(bbox.y / PAGE_HEIGHT) * 100}%`,\n width: `${(bbox.width / PAGE_WIDTH) * 100}%`,\n height: `${(bbox.height / PAGE_HEIGHT) * 100}%`,\n }\n}\n\nfunction getSignatureAspectRatio(bbox?: BoundingBox): number {\n if (!bbox || bbox.width <= 0 || bbox.height <= 0) {\n return DEFAULT_SIGNATURE_ASPECT_RATIO\n }\n\n return bbox.width / bbox.height\n}\n\nfunction getSignatureGuideSize({\n containerWidth,\n containerHeight,\n aspectRatio,\n}: {\n containerWidth: number\n containerHeight: number\n aspectRatio: number\n}): { width: number; height: number } {\n const maxWidth = Math.max(containerWidth - SIGNATURE_PAD_PADDING * 2, 1)\n const maxHeight = Math.max(containerHeight - SIGNATURE_PAD_PADDING * 2, 1)\n\n if (maxWidth / maxHeight > aspectRatio) {\n const height = maxHeight\n return {\n width: height * aspectRatio,\n height,\n }\n }\n\n const width = maxWidth\n return {\n width,\n height: width / aspectRatio,\n }\n}\n\nfunction getCroppedSignatureDataUrl(canvas: HTMLCanvasElement): string {\n const context = canvas.getContext("2d")\n if (!context) {\n return canvas.toDataURL("image/png")\n }\n\n const { width, height } = canvas\n const imageData = context.getImageData(0, 0, width, height)\n const { data } = imageData\n let minX = width\n let minY = height\n let maxX = -1\n let maxY = -1\n\n for (let y = 0; y < height; y += 1) {\n for (let x = 0; x < width; x += 1) {\n const alpha = data[(y * width + x) * 4 + 3]\n if (alpha === 0) continue\n\n minX = Math.min(minX, x)\n minY = Math.min(minY, y)\n maxX = Math.max(maxX, x)\n maxY = Math.max(maxY, y)\n }\n }\n\n if (maxX < minX || maxY < minY) {\n return canvas.toDataURL("image/png")\n }\n\n const croppedWidth = maxX - minX + 1\n const croppedHeight = maxY - minY + 1\n const croppedCanvas = document.createElement("canvas")\n croppedCanvas.width = croppedWidth\n croppedCanvas.height = croppedHeight\n\n const croppedContext = croppedCanvas.getContext("2d")\n if (!croppedContext) {\n return canvas.toDataURL("image/png")\n }\n\n croppedContext.drawImage(\n canvas,\n minX,\n minY,\n croppedWidth,\n croppedHeight,\n 0,\n 0,\n croppedWidth,\n croppedHeight\n )\n\n return croppedCanvas.toDataURL("image/png")\n}\n\nfunction SignatureDialog({\n open,\n fieldBbox,\n initialValue,\n onOpenChange,\n onConfirm,\n}: {\n open: boolean\n fieldBbox: BoundingBox\n initialValue?: string\n onOpenChange: (open: boolean) => void\n onConfirm: (value: string) => void\n}) {\n const canvasContainerRef = React.useRef<HTMLDivElement>(null)\n const canvasRef = React.useRef<HTMLCanvasElement>(null)\n const signaturePadRef = React.useRef<SignaturePad | null>(null)\n const [isReady, setIsReady] = React.useState(false)\n const [hasSignature, setHasSignature] = React.useState(false)\n const [guideSize, setGuideSize] = React.useState<{\n width: number\n height: number\n } | null>(null)\n const signatureAspectRatio = React.useMemo(\n () => getSignatureAspectRatio(fieldBbox),\n [fieldBbox]\n )\n\n React.useEffect(() => {\n if (!open) {\n setGuideSize(null)\n return\n }\n\n let frameId = 0\n let resizeObserver: ResizeObserver | null = null\n\n const updateGuideSize = (container?: HTMLDivElement | null) => {\n const currentContainer = container ?? canvasContainerRef.current\n if (\n !currentContainer ||\n currentContainer.clientWidth <= 0 ||\n currentContainer.clientHeight <= 0\n ) {\n return false\n }\n\n const nextSize = getSignatureGuideSize({\n containerWidth: currentContainer.clientWidth,\n containerHeight: currentContainer.clientHeight,\n aspectRatio: signatureAspectRatio,\n })\n\n setGuideSize((previousSize) => {\n if (\n previousSize &&\n Math.abs(previousSize.width - nextSize.width) < 0.5 &&\n Math.abs(previousSize.height - nextSize.height) < 0.5\n ) {\n return previousSize\n }\n\n return nextSize\n })\n\n return true\n }\n\n const connect = () => {\n const container = canvasContainerRef.current\n if (!updateGuideSize(container)) {\n frameId = window.requestAnimationFrame(connect)\n return\n }\n\n if (container) {\n resizeObserver = new ResizeObserver(() => {\n updateGuideSize(container)\n })\n resizeObserver.observe(container)\n }\n }\n\n connect()\n\n return () => {\n window.cancelAnimationFrame(frameId)\n resizeObserver?.disconnect()\n }\n }, [open, signatureAspectRatio])\n\n React.useEffect(() => {\n if (!open || !guideSize || guideSize.width <= 1 || guideSize.height <= 1) {\n signaturePadRef.current?.off()\n signaturePadRef.current = null\n setIsReady(false)\n if (!open) {\n setHasSignature(false)\n }\n return\n }\n\n let cancelled = false\n let resizeObserver: ResizeObserver | null = null\n\n const syncCanvasSize = (canvas: HTMLCanvasElement) => {\n const width = Math.max(canvas.offsetWidth, 1)\n const height = Math.max(canvas.offsetHeight, 1)\n const ratio = Math.max(window.devicePixelRatio || 1, 1)\n\n canvas.style.width = `${width}px`\n canvas.style.height = `${height}px`\n canvas.width = Math.floor(width * ratio)\n canvas.height = Math.floor(height * ratio)\n const context = canvas.getContext("2d")\n context?.setTransform(1, 0, 0, 1, 0, 0)\n context?.scale(ratio, ratio)\n\n return { width, height, ratio }\n }\n\n const initialize = async () => {\n const canvas = canvasRef.current\n if (!canvas) return\n\n const { default: SignaturePadConstructor } = await import("signature_pad")\n if (cancelled) return\n\n const signaturePad = new SignaturePadConstructor(canvas, {\n minWidth: 1.4,\n maxWidth: 2.8,\n penColor: SIGNATURE_PAD_PEN_COLOR,\n })\n\n signaturePadRef.current = signaturePad\n\n const loadSignature = async (dataUrl?: string) => {\n const size = syncCanvasSize(canvas)\n\n if (dataUrl) {\n await signaturePad.fromDataURL(dataUrl, size)\n setHasSignature(true)\n return\n }\n\n signaturePad.clear()\n setHasSignature(false)\n }\n\n await loadSignature(initialValue)\n if (cancelled) return\n\n signaturePad.addEventListener("endStroke", () => {\n setHasSignature(true)\n })\n\n resizeObserver = new ResizeObserver(() => {\n const currentCanvas = canvasRef.current\n const currentSignaturePad = signaturePadRef.current\n if (!currentCanvas || !currentSignaturePad) return\n\n const previousSignature = currentSignaturePad.isEmpty()\n ? undefined\n : currentSignaturePad.toDataURL("image/png")\n void loadSignature(previousSignature)\n })\n resizeObserver.observe(canvas)\n setIsReady(true)\n }\n\n const animationFrame = window.requestAnimationFrame(() => {\n void initialize()\n })\n\n return () => {\n cancelled = true\n window.cancelAnimationFrame(animationFrame)\n resizeObserver?.disconnect()\n signaturePadRef.current?.off()\n signaturePadRef.current = null\n setIsReady(false)\n }\n }, [open, guideSize, initialValue])\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className="max-w-xl">\n <DialogHeader>\n <DialogTitle>Add signature</DialogTitle>\n <DialogDescription>\n Draw a signature to place it into the selected PDF field.\n </DialogDescription>\n </DialogHeader>\n <DialogPanel>\n <div className="rounded-xl border bg-muted/30 p-3">\n <div\n ref={canvasContainerRef}\n className="flex h-56 w-full items-center justify-center overflow-hidden rounded-lg border bg-muted/40 p-2"\n >\n <div\n className={cn(\n "relative overflow-hidden rounded-md border border-dashed border-input bg-white shadow-xs",\n isReady ? "cursor-crosshair" : "cursor-wait"\n )}\n style={{\n width: guideSize ? `${guideSize.width}px` : undefined,\n height: guideSize ? `${guideSize.height}px` : undefined,\n opacity: guideSize ? 1 : 0,\n backgroundColor: SIGNATURE_PAD_BACKGROUND_COLOR,\n }}\n >\n <canvas\n ref={canvasRef}\n className={cn(\n "absolute inset-0 size-full touch-none",\n !isReady && "pointer-events-none"\n )}\n style={{\n backgroundColor: SIGNATURE_PAD_BACKGROUND_COLOR,\n touchAction: "none",\n }}\n />\n </div>\n </div>\n </div>\n </DialogPanel>\n <DialogFooter className="sm:justify-between">\n <Button\n type="button"\n variant="outline"\n disabled={!isReady}\n onClick={() => {\n signaturePadRef.current?.clear()\n setHasSignature(false)\n }}\n >\n Clear\n </Button>\n <div className="flex flex-col-reverse gap-2 sm:flex-row">\n <Button\n type="button"\n variant="outline"\n onClick={() => onOpenChange(false)}\n >\n Cancel\n </Button>\n <Button\n type="button"\n disabled={!isReady || !hasSignature}\n onClick={() => {\n const canvas = canvasRef.current\n if (!canvas) return\n\n onConfirm(getCroppedSignatureDataUrl(canvas))\n onOpenChange(false)\n }}\n >\n Confirm\n </Button>\n </div>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\nfunction SignatureFieldOverlay({\n field,\n onOpen,\n}: {\n field: SignatureField\n onOpen: () => void\n}) {\n return (\n <button\n type="button"\n className={cn(\n "absolute z-20 overflow-hidden rounded-[3px] border border-blue-500/70 transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",\n field.imageDataUrl\n ? "bg-transparent shadow-none hover:bg-blue-500/5"\n : "bg-blue-500/10 hover:bg-blue-500/15"\n )}\n style={bboxToStyle(field.bbox)}\n onClick={onOpen}\n >\n {field.imageDataUrl ? (\n <img\n src={field.imageDataUrl}\n alt=""\n className="size-full object-contain"\n draggable={false}\n />\n ) : (\n <span className="flex size-full items-center justify-center gap-1.5 px-2 text-[11px] font-medium text-blue-700 dark:text-blue-300">\n <HugeiconsIcon icon={Pen01Icon} className="size-3.5" />\n Signature\n </span>\n )}\n </button>\n )\n}\n\nasync function downloadSignedPdf({\n file,\n field,\n}: {\n file: string\n field: SignatureField\n}) {\n const { PDFDocument } = await import("pdf-lib")\n const existingPdfBytes = await fetch(file).then((response) =>\n response.arrayBuffer()\n )\n const pdfDocument = await PDFDocument.load(existingPdfBytes)\n const page = pdfDocument.getPage(field.page - 1)\n\n if (field.imageDataUrl) {\n const signatureImage = await pdfDocument.embedPng(field.imageDataUrl)\n const { width: pageWidth, height: pageHeight } = page.getSize()\n const scaleX = pageWidth / PAGE_WIDTH\n const scaleY = pageHeight / PAGE_HEIGHT\n const fieldWidth = field.bbox.width * scaleX\n const fieldHeight = field.bbox.height * scaleY\n const imageAspectRatio = signatureImage.width / signatureImage.height\n const fieldAspectRatio = fieldWidth / fieldHeight\n const drawWidth =\n fieldAspectRatio > imageAspectRatio\n ? fieldHeight * imageAspectRatio\n : fieldWidth\n const drawHeight =\n fieldAspectRatio > imageAspectRatio\n ? fieldHeight\n : fieldWidth / imageAspectRatio\n const fieldX = field.bbox.x * scaleX\n const fieldY = pageHeight - (field.bbox.y + field.bbox.height) * scaleY\n\n page.drawImage(signatureImage, {\n x: fieldX + (fieldWidth - drawWidth) / 2,\n y: fieldY + (fieldHeight - drawHeight) / 2,\n width: drawWidth,\n height: drawHeight,\n })\n }\n\n const bytes = await pdfDocument.save()\n const blob = new Blob([new Uint8Array(bytes)], { type: "application/pdf" })\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n anchor.href = url\n anchor.download = "signed-document.pdf"\n anchor.click()\n URL.revokeObjectURL(url)\n}\n\nfunction SignatureFieldsPanel({\n field,\n className,\n canExport,\n isDownloading,\n onSign,\n onClear,\n onDownload,\n}: {\n field: SignatureField\n className?: string\n canExport: boolean\n isDownloading: boolean\n onSign: () => void\n onClear: () => void\n onDownload: () => void\n}) {\n return (\n <aside className={cn("flex min-h-0 flex-col bg-background", className)}>\n <ScrollArea className="min-h-0 flex-1" scrollFade>\n <div className="space-y-4 p-4">\n <div className="space-y-1">\n <h3 className="text-sm font-medium">Signature fields</h3>\n <p className="text-xs text-muted-foreground">\n Review fields, collect signatures, and export a signed PDF.\n </p>\n </div>\n <div className="rounded-lg border bg-background p-3">\n <div className="flex items-start gap-3">\n <div className="grid size-9 shrink-0 place-items-center rounded-md bg-blue-500/10 text-blue-600 dark:text-blue-300">\n <HugeiconsIcon icon={FilePenIcon} className="size-4" />\n </div>\n <div className="min-w-0 flex-1">\n <div className="flex items-center justify-between gap-2">\n <div className="text-sm font-medium">{field.label}</div>\n <div\n className={cn(\n "rounded-full px-2 py-0.5 text-xs",\n field.imageDataUrl\n ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-300"\n : "bg-muted text-muted-foreground"\n )}\n >\n {field.imageDataUrl ? "Signed" : "Unsigned"}\n </div>\n </div>\n <div className="mt-2 text-xs text-muted-foreground">\n {Math.round(field.bbox.width)} x{" "}\n {Math.round(field.bbox.height)} on page {field.page}\n </div>\n <div className="mt-3 flex gap-2">\n <Button\n type="button"\n size="sm"\n variant={field.imageDataUrl ? "outline" : "default"}\n className="flex-1"\n onClick={onSign}\n >\n <HugeiconsIcon icon={Pen01Icon} className="size-4" />\n {field.imageDataUrl ? "Edit" : "Sign"}\n </Button>\n {field.imageDataUrl ? (\n <Button\n type="button"\n size="sm"\n variant="outline"\n onClick={onClear}\n >\n Clear\n </Button>\n ) : null}\n </div>\n </div>\n </div>\n </div>\n <Button\n type="button"\n className="w-full"\n disabled={!canExport || isDownloading}\n onClick={onDownload}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n {isDownloading ? "Exporting..." : "Export signed PDF"}\n </Button>\n </div>\n </ScrollArea>\n </aside>\n )\n}\n\nexport function ESignatureBlock({ file }: { file?: string }) {\n const [field, setField] = React.useState<SignatureField>(INITIAL_FIELD)\n const [dialogOpen, setDialogOpen] = React.useState(false)\n const [isDownloading, setIsDownloading] = React.useState(false)\n\n const handleDownload = React.useCallback(async () => {\n if (!file || !field.imageDataUrl) return\n\n setIsDownloading(true)\n try {\n await downloadSignedPdf({ file, field })\n } finally {\n setIsDownloading(false)\n }\n }, [field, file])\n\n return (\n <>\n <PdfBlockResizableShell\n autoSaveId="pdf-block-e-signature"\n left={\n <PDFViewer\n file={file}\n defaultZoom={DEFAULT_ZOOM}\n pageWidth={PAGE_WIDTH}\n pageHeight={PAGE_HEIGHT}\n toolbarActions={\n <Button\n type="button"\n size="sm"\n variant="outline"\n disabled={!file || !field.imageDataUrl || isDownloading}\n onClick={handleDownload}\n >\n <HugeiconsIcon icon={Download01Icon} className="size-4" />\n Download\n </Button>\n }\n renderPageOverlay={({ pageNumber }) =>\n pageNumber === field.page ? (\n <SignatureFieldOverlay\n field={field}\n onOpen={() => setDialogOpen(true)}\n />\n ) : null\n }\n />\n }\n right={\n <SignatureFieldsPanel\n field={field}\n canExport={Boolean(file && field.imageDataUrl)}\n isDownloading={isDownloading}\n onSign={() => setDialogOpen(true)}\n onClear={() =>\n setField((previousField) => ({\n ...previousField,\n imageDataUrl: undefined,\n }))\n }\n onDownload={handleDownload}\n />\n }\n />\n <SignatureDialog\n open={dialogOpen}\n fieldBbox={field.bbox}\n initialValue={field.imageDataUrl}\n onOpenChange={setDialogOpen}\n onConfirm={(imageDataUrl) => {\n setField((previousField) => ({ ...previousField, imageDataUrl }))\n }}\n />\n </>\n )\n}\n'export function ESignatureSource() {return <HighlightedCodeBlock code={eSignatureSourceCode} />diff --git a/apps/v4/components/file-thumbnail-docs.tsx b/apps/v4/components/file-thumbnail-docs.tsxindex 2ce59a8..67bf420 100644--- a/apps/v4/components/file-thumbnail-docs.tsx+++ b/apps/v4/components/file-thumbnail-docs.tsx@@ -246,7 +246,7 @@ export function FileThumbnailGrid() {}`const fileThumbnailSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n useDocxEditor,\n useDocxViewerThumbnails,\n} from "@extend-ai/react-docx"\nimport {\n useXlsxViewer,\n useXlsxViewerController,\n useXlsxViewerThumbnails,\n XlsxViewerProvider,\n} from "@extend-ai/react-xlsx"\nimport { File01Icon, FileImageIcon } from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport type * as ReactPdf from "react-pdf"\n\nimport { cn } from "@/lib/utils"\n\nexport type ThumbnailSource = string | File | Blob\n\nexport type ThumbnailFile = {\n name: string\n type: string\n size?: string | number\n source?: ThumbnailSource\n url?: string\n}\n\nexport type FileThumbnailProps = {\n file: ThumbnailFile | File\n className?: string\n previewAspectRatio?: number\n previewClassName?: string\n previewContent?: React.ReactNode\n previewImageUrl?: string | null\n source?: ThumbnailSource\n thumbnailWidth?: number\n generationDelayMs?: number\n renderDocumentPreview?: boolean\n isLoading?: boolean\n hasError?: boolean\n showMetadata?: boolean\n}\n\ntype NormalizedThumbnailFile = {\n name: string\n type: string\n size?: string | number\n source?: ThumbnailSource\n url?: string\n}\n\ntype ReactPdfModule = typeof ReactPdf\n\nfunction isBlobLike(value: unknown): value is Blob {\n return typeof Blob !== "undefined" && value instanceof Blob\n}\n\nfunction isFileLike(value: unknown): value is File {\n return typeof File !== "undefined" && value instanceof File\n}\n\nfunction normalizeFile(file: ThumbnailFile | File): NormalizedThumbnailFile {\n return {\n name: file.name,\n size:\n typeof file.size === "number"\n ? formatBytes(file.size)\n : (file.size as string | undefined),\n source: isFileLike(file) ? file : (file as ThumbnailFile).source,\n type: file.type,\n url: (file as ThumbnailFile).url,\n }\n}\n\nfunction getThumbnailSource(\n file: NormalizedThumbnailFile,\n source?: ThumbnailSource\n): ThumbnailSource | undefined {\n return source ?? file.source ?? file.url\n}\n\nfunction formatBytes(bytes: number) {\n if (!Number.isFinite(bytes) || bytes <= 0) return undefined\n\n const units = ["B", "KB", "MB", "GB"]\n let value = bytes\n let unitIndex = 0\n\n while (value >= 1024 && unitIndex < units.length - 1) {\n value /= 1024\n unitIndex += 1\n }\n\n const formatted =\n value >= 10 || unitIndex === 0 ? Math.round(value) : value.toFixed(1)\n return `${formatted} ${units[unitIndex]}`\n}\n\nfunction isImageFile(file: NormalizedThumbnailFile) {\n return file.type.startsWith("image/")\n}\n\nfunction isPdfFile(file: NormalizedThumbnailFile) {\n return (\n file.type === "application/pdf" || file.name.toLowerCase().endsWith(".pdf")\n )\n}\n\nfunction isDocxFile(file: NormalizedThumbnailFile) {\n return (\n file.type ===\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||\n file.name.toLowerCase().endsWith(".docx")\n )\n}\n\nfunction isXlsxFile(file: NormalizedThumbnailFile) {\n const fileName = file.name.toLowerCase()\n\n return (\n file.type ===\n "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||\n file.type === "application/vnd.ms-excel" ||\n fileName.endsWith(".xlsx") ||\n fileName.endsWith(".xls")\n )\n}\n\nfunction FileKindIcon({ file }: { file: NormalizedThumbnailFile }) {\n const icon = isImageFile(file) ? FileImageIcon : File01Icon\n\n return <HugeiconsIcon icon={icon} className="size-4" />\n}\n\nfunction useThumbnailActivation(delayMs: number) {\n const [isActive, setIsActive] = React.useState(delayMs <= 0)\n\n React.useEffect(() => {\n if (delayMs <= 0) {\n setIsActive(true)\n return\n }\n\n setIsActive(false)\n const timeout = window.setTimeout(() => {\n setIsActive(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeout)\n }, [delayMs])\n\n return isActive\n}\n\nfunction useObjectUrl() {\n const [objectUrl, setObjectUrl] = React.useState<string | null>(null)\n\n const updateObjectUrl = React.useCallback((blob: Blob) => {\n const nextUrl = URL.createObjectURL(blob)\n setObjectUrl((currentUrl) => {\n if (currentUrl) URL.revokeObjectURL(currentUrl)\n return nextUrl\n })\n }, [])\n\n React.useEffect(() => {\n return () => {\n if (objectUrl) URL.revokeObjectURL(objectUrl)\n }\n }, [objectUrl])\n\n return { objectUrl, updateObjectUrl }\n}\n\nfunction useSourceObjectUrl(source: ThumbnailSource | undefined) {\n const [objectUrl, setObjectUrl] = React.useState<string | null>(null)\n\n React.useEffect(() => {\n if (!source || typeof source === "string") {\n setObjectUrl(null)\n return\n }\n\n const nextUrl = URL.createObjectURL(source)\n setObjectUrl(nextUrl)\n\n return () => URL.revokeObjectURL(nextUrl)\n }, [source])\n\n if (!source) return undefined\n return typeof source === "string" ? source : (objectUrl ?? undefined)\n}\n\nasync function sourceToFile(\n source: ThumbnailSource,\n file: NormalizedThumbnailFile\n) {\n if (isFileLike(source)) return source\n\n if (isBlobLike(source)) {\n return new File([source], file.name, {\n type: source.type || file.type,\n })\n }\n\n const response = await fetch(source)\n if (!response.ok) {\n throw new Error(`Failed to fetch ${file.name} (${response.status})`)\n }\n\n const blob = await response.blob()\n\n return new File([blob], file.name, {\n type: blob.type || file.type,\n })\n}\n\nfunction canvasToBlob(canvas: HTMLCanvasElement | null) {\n if (!canvas) return Promise.resolve<Blob | null>(null)\n\n return new Promise<Blob | null>((resolve) => {\n const blobFromDataUrl = async () => {\n try {\n const dataUrl = canvas.toDataURL("image/png")\n const response = await fetch(dataUrl)\n return await response.blob()\n } catch {\n return null\n }\n }\n\n try {\n if (typeof canvas.toBlob === "function") {\n canvas.toBlob((blob) => {\n if (blob) {\n resolve(blob)\n return\n }\n\n void blobFromDataUrl().then(resolve)\n }, "image/png")\n return\n }\n\n void blobFromDataUrl().then(resolve)\n } catch {\n resolve(null)\n }\n })\n}\n\nfunction canvasHasVisiblePixels(canvas: HTMLCanvasElement) {\n const context = canvas.getContext("2d")\n if (!context || canvas.width <= 0 || canvas.height <= 0) return false\n\n try {\n const { data } = context.getImageData(0, 0, canvas.width, canvas.height)\n\n for (let index = 3; index < data.length; index += 4) {\n if (data[index] > 0) return true\n }\n\n return false\n } catch {\n return true\n }\n}\n\nexport function FileThumbnailLoadingOverlay() {\n return (\n <div\n aria-hidden="true"\n className="absolute inset-0 z-10 overflow-hidden bg-muted"\n >\n <div className="absolute inset-0 bg-muted" />\n <div className="absolute inset-0 animate-pulse bg-background/55 motion-reduce:animate-none" />\n </div>\n )\n}\n\nfunction FileThumbnailShell({\n file,\n className,\n previewAspectRatio,\n previewClassName,\n previewContent,\n previewImageUrl,\n isLoading = false,\n hasError = false,\n showMetadata = true,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n previewAspectRatio?: number\n previewClassName?: string\n previewContent?: React.ReactNode\n previewImageUrl?: string | null\n isLoading?: boolean\n hasError?: boolean\n showMetadata?: boolean\n}) {\n const imageRef = React.useRef<HTMLImageElement | null>(null)\n const [isImageLoading, setIsImageLoading] = React.useState(\n Boolean(previewImageUrl)\n )\n const [imageFailed, setImageFailed] = React.useState(false)\n const showLoading = isLoading || isImageLoading\n const hasPreviewContent = Boolean(previewContent)\n const showFallback =\n !showLoading &&\n (hasError || imageFailed || (!previewImageUrl && !hasPreviewContent))\n const markImageLoaded = React.useCallback((image: HTMLImageElement) => {\n const didLoad = image.naturalWidth > 0 && image.naturalHeight > 0\n\n setImageFailed(!didLoad)\n setIsImageLoading(false)\n }, [])\n\n React.useEffect(() => {\n setIsImageLoading(Boolean(previewImageUrl))\n setImageFailed(false)\n }, [previewImageUrl])\n\n React.useEffect(() => {\n const image = imageRef.current\n\n if (!image || !previewImageUrl) return\n\n if (image.complete) {\n markImageLoaded(image)\n }\n }, [markImageLoaded, previewImageUrl])\n\n return (\n <div\n className={cn(\n "group overflow-hidden rounded-lg border bg-background text-foreground",\n className\n )}\n >\n <div\n className={cn(\n "relative aspect-square overflow-hidden bg-muted",\n previewClassName\n )}\n style={\n previewAspectRatio\n ? { aspectRatio: String(previewAspectRatio) }\n : undefined\n }\n >\n {previewImageUrl ? (\n <img\n ref={imageRef}\n src={previewImageUrl}\n alt=""\n draggable={false}\n loading="lazy"\n decoding="async"\n className={cn(\n "size-full object-cover transition-[opacity,filter,transform] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",\n showLoading\n ? "scale-[1.01] opacity-0 blur-sm"\n : "blur-0 scale-100 opacity-100"\n )}\n onLoad={(event) => {\n markImageLoaded(event.currentTarget)\n }}\n onError={() => {\n setImageFailed(true)\n setIsImageLoading(false)\n }}\n />\n ) : null}\n {previewContent ? (\n <div\n className={cn(\n "size-full transition-[opacity,filter,transform] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",\n showLoading\n ? "scale-[1.01] opacity-0 blur-sm"\n : "blur-0 scale-100 opacity-100"\n )}\n >\n {previewContent}\n </div>\n ) : null}\n {showLoading ? <FileThumbnailLoadingOverlay /> : null}\n {showFallback ? (\n <div className="absolute inset-0 grid place-items-center bg-muted text-muted-foreground">\n <FileKindIcon file={file} />\n </div>\n ) : null}\n </div>\n {showMetadata ? (\n <div className="flex items-center gap-2 border-t px-3 py-2">\n <div className="flex size-7 shrink-0 items-center justify-center rounded-md border bg-muted text-muted-foreground">\n <FileKindIcon file={file} />\n </div>\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">{file.name}</div>\n <div className="truncate text-xs text-muted-foreground">\n {file.size ?? file.type}\n </div>\n </div>\n </div>\n ) : null}\n </div>\n )\n}\n\nfunction ImageFileThumbnail({\n className,\n file,\n hasError,\n isLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n}: {\n className?: string\n file: NormalizedThumbnailFile\n hasError?: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata?: boolean\n source: ThumbnailSource\n}) {\n const imageUrl = useSourceObjectUrl(source)\n\n return (\n <FileThumbnailShell\n file={file}\n previewImageUrl={imageUrl}\n isLoading={isLoading || !imageUrl}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n}\n\nfunction PdfFileThumbnail({\n file,\n className,\n hasError: externalHasError,\n isActive,\n isLoading: externalIsLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n hasError?: boolean\n isActive: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata: boolean\n source: ThumbnailSource\n thumbnailWidth: number\n}) {\n const sourceUrl = useSourceObjectUrl(source)\n const [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null)\n const [isLoading, setIsLoading] = React.useState(true)\n const [hasError, setHasError] = React.useState(false)\n const rootRef = React.useRef<HTMLDivElement | null>(null)\n const { objectUrl, updateObjectUrl } = useObjectUrl()\n const shouldRenderPdf =\n isActive && sourceUrl && reactPdf && !objectUrl && !hasError\n const capturePdfCanvas = React.useCallback(() => {\n const canvas = rootRef.current?.querySelector("canvas") ?? null\n\n void canvasToBlob(canvas).then((blob) => {\n if (!blob) {\n setHasError(true)\n setIsLoading(false)\n return\n }\n\n updateObjectUrl(blob)\n setHasError(false)\n setIsLoading(false)\n })\n }, [updateObjectUrl])\n\n React.useEffect(() => {\n setIsLoading(true)\n setHasError(false)\n }, [sourceUrl])\n\n React.useEffect(() => {\n if (!isActive || reactPdf || objectUrl) return\n\n let isMounted = true\n setIsLoading(true)\n setHasError(false)\n\n void import("react-pdf")\n .then((module) => {\n module.pdfjs.GlobalWorkerOptions.workerSrc = `https://unpkg.com/pdfjs-dist@${module.pdfjs.version}/legacy/build/pdf.worker.min.mjs`\n if (isMounted) setReactPdf(module)\n })\n .catch(() => {\n if (isMounted) {\n setHasError(true)\n setIsLoading(false)\n }\n })\n\n return () => {\n isMounted = false\n }\n }, [isActive, objectUrl, reactPdf])\n\n return (\n <>\n <FileThumbnailShell\n file={file}\n previewImageUrl={objectUrl}\n isLoading={Boolean(externalIsLoading || (isLoading && !objectUrl))}\n hasError={Boolean(externalHasError || hasError)}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n {shouldRenderPdf ? (\n <div\n ref={rootRef}\n aria-hidden="true"\n className="pointer-events-none fixed top-0 left-[-10000px] w-[560px] overflow-hidden bg-white"\n >\n <reactPdf.Document\n file={sourceUrl}\n loading={null}\n error={null}\n noData={null}\n onLoadError={() => {\n setHasError(true)\n setIsLoading(false)\n }}\n >\n <reactPdf.Thumbnail\n pageNumber={1}\n width={thumbnailWidth}\n loading={null}\n error={null}\n onRenderSuccess={() => {\n window.requestAnimationFrame(() => {\n capturePdfCanvas()\n })\n }}\n onRenderError={() => {\n setHasError(true)\n setIsLoading(false)\n }}\n />\n </reactPdf.Document>\n </div>\n ) : null}\n </>\n )\n}\n\nfunction DocxFileThumbnail({\n file,\n className,\n hasError: externalHasError,\n isActive,\n isLoading: externalIsLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n hasError?: boolean\n isActive: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata: boolean\n source: ThumbnailSource\n thumbnailWidth: number\n}) {\n const editor = useDocxEditor({\n initialDocumentTheme: "light",\n initialFileName: file.name,\n })\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: thumbnailWidth,\n maxWidth: thumbnailWidth,\n },\n }),\n [thumbnailWidth]\n )\n const { thumbnails } = useDocxViewerThumbnails(editor, thumbnailOptions)\n const firstThumbnail = thumbnails[0]\n const [hasError, setHasError] = React.useState(false)\n const [isReady, setIsReady] = React.useState(false)\n const [thumbnailSize, setThumbnailSize] = React.useState<{\n height: number\n width: number\n } | null>(null)\n const [thumbnailCanvas, setThumbnailCanvas] =\n React.useState<HTMLCanvasElement | null>(null)\n const editorRef = React.useRef(editor)\n const importedDocxKeyRef = React.useRef<string | null>(null)\n const hiddenDocxViewerRef = React.useRef<HTMLDivElement | null>(null)\n\n React.useEffect(() => {\n editorRef.current = editor\n }, [editor])\n\n React.useEffect(() => {\n if (!isActive) return\n\n const docxKey =\n typeof source === "string"\n ? `${file.name}:${source}`\n : `${file.name}:${source.size}:${source.type}`\n\n if (importedDocxKeyRef.current === docxKey) return\n\n let isCurrent = true\n importedDocxKeyRef.current = docxKey\n setHasError(false)\n setIsReady(false)\n\n async function loadDocx() {\n try {\n const docxFile = await sourceToFile(source, file)\n await editorRef.current.importDocxFile(docxFile)\n } catch {\n if (isCurrent && importedDocxKeyRef.current === docxKey) {\n setHasError(true)\n }\n }\n }\n\n void loadDocx()\n\n return () => {\n isCurrent = false\n }\n }, [file, isActive, source])\n\n React.useEffect(() => {\n if (!firstThumbnail) {\n setThumbnailSize(null)\n return\n }\n\n setThumbnailSize((currentSize) => {\n if (\n currentSize?.height === firstThumbnail.pixelHeightPx &&\n currentSize.width === firstThumbnail.pixelWidthPx\n ) {\n return currentSize\n }\n\n return {\n height: firstThumbnail.pixelHeightPx,\n width: firstThumbnail.pixelWidthPx,\n }\n })\n\n if (firstThumbnail?.status === "error") {\n setHasError(true)\n }\n }, [\n firstThumbnail,\n firstThumbnail?.pixelHeightPx,\n firstThumbnail?.pixelWidthPx,\n firstThumbnail?.status,\n ])\n\n const attachThumbnailCanvas = React.useCallback(\n (canvas: HTMLCanvasElement | null) => {\n setThumbnailCanvas(canvas)\n if (canvas) firstThumbnail?.canvasRef(canvas)\n },\n [firstThumbnail]\n )\n\n React.useEffect(() => {\n if (\n !isActive ||\n !firstThumbnail ||\n !thumbnailCanvas ||\n isReady ||\n hasError\n ) {\n return\n }\n\n let isCurrent = true\n let timeoutId: number | undefined\n let attempts = 0\n\n const getRenderedPageSurface = () => {\n const pageSurface = hiddenDocxViewerRef.current?.querySelector(\n \'[data-docx-page-surface="true"]\'\n )\n\n if (!pageSurface) return null\n\n const hasText = Boolean(pageSurface.textContent?.trim())\n const hasEmbeddedContent = Boolean(\n pageSurface.querySelector("canvas,img,svg,table")\n )\n\n return hasText || hasEmbeddedContent ? pageSurface : null\n }\n\n const checkThumbnail = () => {\n if (!isCurrent) return\n\n if (canvasHasVisiblePixels(thumbnailCanvas)) {\n setIsReady(true)\n return\n }\n\n if (!getRenderedPageSurface()) {\n attempts += 1\n\n if (attempts > 50) {\n setIsReady(true)\n return\n }\n\n timeoutId = window.setTimeout(checkThumbnail, 100)\n return\n }\n\n attempts += 1\n\n if (attempts > 50) {\n setIsReady(true)\n return\n }\n\n timeoutId = window.setTimeout(checkThumbnail, 100)\n }\n\n checkThumbnail()\n\n return () => {\n isCurrent = false\n if (timeoutId !== undefined) window.clearTimeout(timeoutId)\n }\n }, [\n firstThumbnail,\n firstThumbnail?.isMounted,\n hasError,\n isActive,\n isReady,\n thumbnailCanvas,\n ])\n\n const previewContent = thumbnailSize ? (\n <canvas\n ref={attachThumbnailCanvas}\n width={thumbnailSize.width}\n height={thumbnailSize.height}\n className="!size-full bg-white object-cover object-top"\n />\n ) : null\n\n return (\n <>\n <FileThumbnailShell\n file={file}\n previewContent={previewContent}\n isLoading={Boolean(externalIsLoading || (!isReady && !hasError))}\n hasError={Boolean(externalHasError || hasError)}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={cn("bg-white", previewClassName)}\n showMetadata={showMetadata}\n />\n {isActive && !hasError ? (\n <div\n ref={hiddenDocxViewerRef}\n aria-hidden="true"\n className="pointer-events-none fixed top-[100vh] left-0 -z-10 h-[1056px] w-[816px] overflow-hidden bg-white"\n >\n <div className="w-[816px]">\n <DocxEditorViewer\n editor={editor}\n mode="read-only"\n pageBackgroundColor="#ffffff"\n pageGapBackgroundColor="transparent"\n visiblePageRange={{ endPageIndex: 0, startPageIndex: 0 }}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n />\n </div>\n </div>\n ) : null}\n </>\n )\n}\n\nfunction XlsxFileThumbnail({\n file,\n className,\n hasError: externalHasError,\n isActive,\n isLoading: externalIsLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n hasError?: boolean\n isActive: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata: boolean\n source: ThumbnailSource\n thumbnailWidth: number\n}) {\n const sourceUrl = useSourceObjectUrl(source)\n const [imageUrl, setImageUrl] = React.useState<string | null>(null)\n const [hasError, setHasError] = React.useState(false)\n\n React.useEffect(() => {\n setImageUrl(null)\n setHasError(false)\n }, [sourceUrl])\n\n return (\n <>\n <FileThumbnailShell\n file={file}\n previewImageUrl={imageUrl}\n isLoading={Boolean(externalIsLoading || (!imageUrl && !hasError))}\n hasError={Boolean(externalHasError || hasError)}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={cn(\n "bg-white [&>img]:object-left-top",\n previewClassName\n )}\n showMetadata={showMetadata}\n />\n {isActive && sourceUrl && !imageUrl && !hasError ? (\n <XlsxThumbnailGenerator\n file={file}\n sourceUrl={sourceUrl}\n thumbnailWidth={thumbnailWidth}\n onError={() => setHasError(true)}\n onImageUrl={setImageUrl}\n />\n ) : null}\n </>\n )\n}\n\nfunction XlsxThumbnailGenerator({\n file,\n onError,\n onImageUrl,\n sourceUrl,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n onError: () => void\n onImageUrl: (url: string) => void\n sourceUrl: string\n thumbnailWidth: number\n}) {\n const controller = useXlsxViewerController(\n React.useMemo(\n () => ({\n fileName: file.name,\n readOnly: true,\n src: sourceUrl,\n useWorker: true,\n }),\n [file.name, sourceUrl]\n )\n )\n\n return (\n <XlsxViewerProvider controller={controller}>\n <XlsxThumbnailGeneratorContent\n thumbnailWidth={thumbnailWidth}\n onError={onError}\n onImageUrl={onImageUrl}\n />\n </XlsxViewerProvider>\n )\n}\n\nfunction XlsxThumbnailGeneratorContent({\n onError,\n onImageUrl,\n thumbnailWidth,\n}: {\n onError: () => void\n onImageUrl: (url: string) => void\n thumbnailWidth: number\n}) {\n const controller = useXlsxViewer()\n const thumbnailOptions = React.useMemo(\n () => ({\n includeHeaders: true,\n resolution: {\n maxHeight: thumbnailWidth,\n maxWidth: thumbnailWidth,\n },\n }),\n [thumbnailWidth]\n )\n const { thumbnails } = useXlsxViewerThumbnails(thumbnailOptions)\n const firstThumbnail = thumbnails[0]\n\n React.useEffect(() => {\n if (controller.error) {\n onError()\n return\n }\n\n if (!firstThumbnail) return\n\n const canvas = document.createElement("canvas")\n\n if (!firstThumbnail.paint(canvas)) return\n\n onImageUrl(canvas.toDataURL("image/png"))\n }, [controller.error, firstThumbnail, onError, onImageUrl])\n\n return null\n}\n\nexport function FileThumbnail({\n file: rawFile,\n className,\n previewAspectRatio,\n previewClassName,\n previewContent,\n previewImageUrl,\n source: explicitSource,\n thumbnailWidth,\n generationDelayMs = 0,\n renderDocumentPreview = true,\n isLoading = false,\n hasError = false,\n showMetadata = true,\n}: FileThumbnailProps) {\n const file = React.useMemo(() => normalizeFile(rawFile), [rawFile])\n const source = getThumbnailSource(file, explicitSource)\n const isActive = useThumbnailActivation(generationDelayMs)\n\n if (previewImageUrl || previewContent || !renderDocumentPreview || !source) {\n return (\n <FileThumbnailShell\n file={file}\n previewImageUrl={previewImageUrl}\n previewContent={previewContent}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n }\n\n if (isImageFile(file)) {\n return (\n <ImageFileThumbnail\n file={file}\n source={source}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n }\n\n if (isPdfFile(file)) {\n return (\n <PdfFileThumbnail\n file={file}\n source={source}\n isActive={isActive}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n thumbnailWidth={thumbnailWidth ?? 520}\n />\n )\n }\n\n if (isDocxFile(file)) {\n return (\n <DocxFileThumbnail\n file={file}\n source={source}\n isActive={isActive}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n thumbnailWidth={thumbnailWidth ?? 520}\n />\n )\n }\n\n if (isXlsxFile(file)) {\n return (\n <XlsxFileThumbnail\n file={file}\n source={source}\n isActive={isActive}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n thumbnailWidth={thumbnailWidth ?? 680}\n />\n )\n }\n\n return (\n <FileThumbnailShell\n file={file}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n useDocxEditor,\n useDocxViewerThumbnails,\n} from "@extend-ai/react-docx"\nimport {\n useXlsxViewer,\n useXlsxViewerController,\n useXlsxViewerThumbnails,\n XlsxViewerProvider,\n} from "@extend-ai/react-xlsx"\nimport { File01Icon, FileImageIcon } from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport type * as ReactPdf from "react-pdf"\n\nimport { cn } from "@/lib/utils"\n\nexport type ThumbnailSource = string | File | Blob\n\nexport type ThumbnailFile = {\n name: string\n type: string\n size?: string | number\n source?: ThumbnailSource\n url?: string\n}\n\nexport type FileThumbnailProps = {\n file: ThumbnailFile | File\n className?: string\n previewAspectRatio?: number\n previewClassName?: string\n previewContent?: React.ReactNode\n previewImageUrl?: string | null\n source?: ThumbnailSource\n thumbnailWidth?: number\n generationDelayMs?: number\n renderDocumentPreview?: boolean\n isLoading?: boolean\n hasError?: boolean\n showMetadata?: boolean\n}\n\ntype NormalizedThumbnailFile = {\n name: string\n type: string\n size?: string | number\n source?: ThumbnailSource\n url?: string\n}\n\ntype ReactPdfModule = typeof ReactPdf\n\nfunction isBlobLike(value: unknown): value is Blob {\n return typeof Blob !== "undefined" && value instanceof Blob\n}\n\nfunction isFileLike(value: unknown): value is File {\n return typeof File !== "undefined" && value instanceof File\n}\n\nfunction normalizeFile(file: ThumbnailFile | File): NormalizedThumbnailFile {\n return {\n name: file.name,\n size:\n typeof file.size === "number"\n ? formatBytes(file.size)\n : (file.size as string | undefined),\n source: isFileLike(file) ? file : (file as ThumbnailFile).source,\n type: file.type,\n url: (file as ThumbnailFile).url,\n }\n}\n\nfunction getThumbnailSource(\n file: NormalizedThumbnailFile,\n source?: ThumbnailSource\n): ThumbnailSource | undefined {\n return source ?? file.source ?? file.url\n}\n\nfunction formatBytes(bytes: number) {\n if (!Number.isFinite(bytes) || bytes <= 0) return undefined\n\n const units = ["B", "KB", "MB", "GB"]\n let value = bytes\n let unitIndex = 0\n\n while (value >= 1024 && unitIndex < units.length - 1) {\n value /= 1024\n unitIndex += 1\n }\n\n const formatted =\n value >= 10 || unitIndex === 0 ? Math.round(value) : value.toFixed(1)\n return `${formatted} ${units[unitIndex]}`\n}\n\nfunction isImageFile(file: NormalizedThumbnailFile) {\n return file.type.startsWith("image/")\n}\n\nfunction isPdfFile(file: NormalizedThumbnailFile) {\n return (\n file.type === "application/pdf" || file.name.toLowerCase().endsWith(".pdf")\n )\n}\n\nfunction isDocxFile(file: NormalizedThumbnailFile) {\n return (\n file.type ===\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||\n file.name.toLowerCase().endsWith(".docx")\n )\n}\n\nfunction isXlsxFile(file: NormalizedThumbnailFile) {\n const fileName = file.name.toLowerCase()\n\n return (\n file.type ===\n "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||\n file.type === "application/vnd.ms-excel" ||\n fileName.endsWith(".xlsx") ||\n fileName.endsWith(".xls")\n )\n}\n\nfunction FileKindIcon({ file }: { file: NormalizedThumbnailFile }) {\n const icon = isImageFile(file) ? FileImageIcon : File01Icon\n\n return <HugeiconsIcon icon={icon} className="size-4" />\n}\n\nfunction useThumbnailActivation(delayMs: number) {\n const [isActive, setIsActive] = React.useState(delayMs <= 0)\n\n React.useEffect(() => {\n if (delayMs <= 0) {\n setIsActive(true)\n return\n }\n\n setIsActive(false)\n const timeout = window.setTimeout(() => {\n setIsActive(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeout)\n }, [delayMs])\n\n return isActive\n}\n\nfunction useObjectUrl() {\n const [objectUrl, setObjectUrl] = React.useState<string | null>(null)\n\n const updateObjectUrl = React.useCallback((blob: Blob) => {\n const nextUrl = URL.createObjectURL(blob)\n setObjectUrl((currentUrl) => {\n if (currentUrl) URL.revokeObjectURL(currentUrl)\n return nextUrl\n })\n }, [])\n\n React.useEffect(() => {\n return () => {\n if (objectUrl) URL.revokeObjectURL(objectUrl)\n }\n }, [objectUrl])\n\n return { objectUrl, updateObjectUrl }\n}\n\nfunction useSourceObjectUrl(source: ThumbnailSource | undefined) {\n const [objectUrl, setObjectUrl] = React.useState<string | null>(null)\n\n React.useEffect(() => {\n if (!source || typeof source === "string") {\n setObjectUrl(null)\n return\n }\n\n const nextUrl = URL.createObjectURL(source)\n setObjectUrl(nextUrl)\n\n return () => URL.revokeObjectURL(nextUrl)\n }, [source])\n\n if (!source) return undefined\n return typeof source === "string" ? source : (objectUrl ?? undefined)\n}\n\nasync function sourceToFile(\n source: ThumbnailSource,\n file: NormalizedThumbnailFile\n) {\n if (isFileLike(source)) return source\n\n if (isBlobLike(source)) {\n return new File([source], file.name, {\n type: source.type || file.type,\n })\n }\n\n const response = await fetch(source)\n if (!response.ok) {\n throw new Error(`Failed to fetch ${file.name} (${response.status})`)\n }\n\n const blob = await response.blob()\n\n return new File([blob], file.name, {\n type: blob.type || file.type,\n })\n}\n\nfunction canvasToBlob(canvas: HTMLCanvasElement | null) {\n if (!canvas) return Promise.resolve<Blob | null>(null)\n\n return new Promise<Blob | null>((resolve) => {\n const blobFromDataUrl = async () => {\n try {\n const dataUrl = canvas.toDataURL("image/png")\n const response = await fetch(dataUrl)\n return await response.blob()\n } catch {\n return null\n }\n }\n\n try {\n if (typeof canvas.toBlob === "function") {\n canvas.toBlob((blob) => {\n if (blob) {\n resolve(blob)\n return\n }\n\n void blobFromDataUrl().then(resolve)\n }, "image/png")\n return\n }\n\n void blobFromDataUrl().then(resolve)\n } catch {\n resolve(null)\n }\n })\n}\n\nfunction canvasHasVisiblePixels(canvas: HTMLCanvasElement) {\n const context = canvas.getContext("2d")\n if (!context || canvas.width <= 0 || canvas.height <= 0) return false\n\n try {\n const { data } = context.getImageData(0, 0, canvas.width, canvas.height)\n\n for (let index = 3; index < data.length; index += 4) {\n if (data[index] > 0) return true\n }\n\n return false\n } catch {\n return true\n }\n}\n\nexport function FileThumbnailLoadingOverlay() {\n return (\n <div\n aria-hidden="true"\n className="absolute inset-0 z-10 overflow-hidden bg-muted"\n >\n <div className="absolute inset-0 bg-muted" />\n <div className="absolute inset-0 animate-pulse bg-background/55 motion-reduce:animate-none" />\n </div>\n )\n}\n\nfunction FileThumbnailShell({\n file,\n className,\n previewAspectRatio,\n previewClassName,\n previewContent,\n previewImageUrl,\n isLoading = false,\n hasError = false,\n showMetadata = true,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n previewAspectRatio?: number\n previewClassName?: string\n previewContent?: React.ReactNode\n previewImageUrl?: string | null\n isLoading?: boolean\n hasError?: boolean\n showMetadata?: boolean\n}) {\n const imageRef = React.useRef<HTMLImageElement | null>(null)\n const revealFrameRef = React.useRef<number | null>(null)\n const [loadedPreviewImageUrl, setLoadedPreviewImageUrl] = React.useState<\n string | null\n >(null)\n const [failedPreviewImageUrl, setFailedPreviewImageUrl] = React.useState<\n string | null\n >(null)\n const imageFailed = Boolean(\n previewImageUrl && failedPreviewImageUrl === previewImageUrl\n )\n const isImageLoading = Boolean(\n previewImageUrl && loadedPreviewImageUrl !== previewImageUrl && !imageFailed\n )\n const showLoading = isLoading || isImageLoading\n const hasPreviewContent = Boolean(previewContent)\n const showFallback =\n !showLoading &&\n (hasError || imageFailed || (!previewImageUrl && !hasPreviewContent))\n const cancelImageReveal = React.useCallback(() => {\n if (revealFrameRef.current === null) return\n\n window.cancelAnimationFrame(revealFrameRef.current)\n revealFrameRef.current = null\n }, [])\n const markImageLoaded = React.useCallback(\n (image: HTMLImageElement, imageUrl: string | null | undefined) => {\n if (!imageUrl) return\n\n const didLoad = image.naturalWidth > 0 && image.naturalHeight > 0\n\n setFailedPreviewImageUrl(didLoad ? null : imageUrl)\n if (didLoad) {\n cancelImageReveal()\n revealFrameRef.current = window.requestAnimationFrame(() => {\n revealFrameRef.current = window.requestAnimationFrame(() => {\n setLoadedPreviewImageUrl(imageUrl)\n revealFrameRef.current = null\n })\n })\n }\n },\n [cancelImageReveal]\n )\n\n React.useEffect(() => {\n cancelImageReveal()\n\n if (previewImageUrl) return\n\n setLoadedPreviewImageUrl(null)\n setFailedPreviewImageUrl(null)\n }, [cancelImageReveal, previewImageUrl])\n\n React.useEffect(() => cancelImageReveal, [cancelImageReveal])\n\n React.useEffect(() => {\n const image = imageRef.current\n\n if (!image || !previewImageUrl) return\n\n if (image.complete) {\n markImageLoaded(image, previewImageUrl)\n }\n }, [markImageLoaded, previewImageUrl])\n\n return (\n <div\n className={cn(\n "group overflow-hidden rounded-lg border bg-background text-foreground",\n className\n )}\n >\n <div\n className={cn(\n "relative aspect-square overflow-hidden bg-muted [contain:layout_paint]",\n previewClassName\n )}\n style={\n previewAspectRatio\n ? { aspectRatio: String(previewAspectRatio) }\n : undefined\n }\n >\n {previewImageUrl ? (\n <img\n ref={imageRef}\n src={previewImageUrl}\n alt=""\n draggable={false}\n loading="lazy"\n decoding="async"\n className={cn(\n "absolute inset-0 block size-full object-cover transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",\n showLoading ? "opacity-0 blur-sm" : "blur-0 opacity-100"\n )}\n onLoad={(event) => {\n markImageLoaded(event.currentTarget, previewImageUrl)\n }}\n onError={() => {\n if (previewImageUrl) {\n cancelImageReveal()\n setFailedPreviewImageUrl(previewImageUrl)\n setLoadedPreviewImageUrl((currentUrl) =>\n currentUrl === previewImageUrl ? null : currentUrl\n )\n }\n }}\n />\n ) : null}\n {previewContent ? (\n <div\n className={cn(\n "absolute inset-0 size-full transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",\n showLoading ? "opacity-0 blur-sm" : "blur-0 opacity-100"\n )}\n >\n {previewContent}\n </div>\n ) : null}\n {showLoading ? <FileThumbnailLoadingOverlay /> : null}\n {showFallback ? (\n <div className="absolute inset-0 grid place-items-center bg-muted text-muted-foreground">\n <FileKindIcon file={file} />\n </div>\n ) : null}\n </div>\n {showMetadata ? (\n <div className="flex items-center gap-2 border-t px-3 py-2">\n <div className="flex size-7 shrink-0 items-center justify-center rounded-md border bg-muted text-muted-foreground">\n <FileKindIcon file={file} />\n </div>\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">{file.name}</div>\n <div className="truncate text-xs text-muted-foreground">\n {file.size ?? file.type}\n </div>\n </div>\n </div>\n ) : null}\n </div>\n )\n}\n\nfunction ImageFileThumbnail({\n className,\n file,\n hasError,\n isLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n}: {\n className?: string\n file: NormalizedThumbnailFile\n hasError?: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata?: boolean\n source: ThumbnailSource\n}) {\n const imageUrl = useSourceObjectUrl(source)\n\n return (\n <FileThumbnailShell\n file={file}\n previewImageUrl={imageUrl}\n isLoading={isLoading || !imageUrl}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n}\n\nfunction PdfFileThumbnail({\n file,\n className,\n hasError: externalHasError,\n isActive,\n isLoading: externalIsLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n hasError?: boolean\n isActive: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata: boolean\n source: ThumbnailSource\n thumbnailWidth: number\n}) {\n const sourceUrl = useSourceObjectUrl(source)\n const [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null)\n const [isLoading, setIsLoading] = React.useState(true)\n const [hasError, setHasError] = React.useState(false)\n const rootRef = React.useRef<HTMLDivElement | null>(null)\n const { objectUrl, updateObjectUrl } = useObjectUrl()\n const shouldRenderPdf =\n isActive && sourceUrl && reactPdf && !objectUrl && !hasError\n const capturePdfCanvas = React.useCallback(() => {\n const canvas = rootRef.current?.querySelector("canvas") ?? null\n\n void canvasToBlob(canvas).then((blob) => {\n if (!blob) {\n setHasError(true)\n setIsLoading(false)\n return\n }\n\n updateObjectUrl(blob)\n setHasError(false)\n setIsLoading(false)\n })\n }, [updateObjectUrl])\n\n React.useEffect(() => {\n setIsLoading(true)\n setHasError(false)\n }, [sourceUrl])\n\n React.useEffect(() => {\n if (!isActive || reactPdf || objectUrl) return\n\n let isMounted = true\n setIsLoading(true)\n setHasError(false)\n\n void import("react-pdf")\n .then((module) => {\n module.pdfjs.GlobalWorkerOptions.workerSrc = `https://unpkg.com/pdfjs-dist@${module.pdfjs.version}/legacy/build/pdf.worker.min.mjs`\n if (isMounted) setReactPdf(module)\n })\n .catch(() => {\n if (isMounted) {\n setHasError(true)\n setIsLoading(false)\n }\n })\n\n return () => {\n isMounted = false\n }\n }, [isActive, objectUrl, reactPdf])\n\n return (\n <>\n <FileThumbnailShell\n file={file}\n previewImageUrl={objectUrl}\n isLoading={Boolean(externalIsLoading || (isLoading && !objectUrl))}\n hasError={Boolean(externalHasError || hasError)}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n {shouldRenderPdf ? (\n <div\n ref={rootRef}\n aria-hidden="true"\n className="pointer-events-none fixed top-0 left-0 -z-10 w-[560px] overflow-hidden bg-white opacity-0 [contain:layout_paint]"\n >\n <reactPdf.Document\n file={sourceUrl}\n loading={null}\n error={null}\n noData={null}\n onLoadError={() => {\n setHasError(true)\n setIsLoading(false)\n }}\n >\n <reactPdf.Thumbnail\n pageNumber={1}\n width={thumbnailWidth}\n loading={null}\n error={null}\n onRenderSuccess={() => {\n window.requestAnimationFrame(() => {\n capturePdfCanvas()\n })\n }}\n onRenderError={() => {\n setHasError(true)\n setIsLoading(false)\n }}\n />\n </reactPdf.Document>\n </div>\n ) : null}\n </>\n )\n}\n\nfunction DocxFileThumbnail({\n file,\n className,\n hasError: externalHasError,\n isActive,\n isLoading: externalIsLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n hasError?: boolean\n isActive: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata: boolean\n source: ThumbnailSource\n thumbnailWidth: number\n}) {\n const editor = useDocxEditor({\n initialDocumentTheme: "light",\n initialFileName: file.name,\n })\n const thumbnailOptions = React.useMemo(\n () => ({\n pixelRatio: 2,\n resolution: {\n maxHeight: thumbnailWidth,\n maxWidth: thumbnailWidth,\n },\n }),\n [thumbnailWidth]\n )\n const { thumbnails } = useDocxViewerThumbnails(editor, thumbnailOptions)\n const firstThumbnail = thumbnails[0]\n const [hasError, setHasError] = React.useState(false)\n const [isReady, setIsReady] = React.useState(false)\n const [thumbnailSize, setThumbnailSize] = React.useState<{\n height: number\n width: number\n } | null>(null)\n const [thumbnailCanvas, setThumbnailCanvas] =\n React.useState<HTMLCanvasElement | null>(null)\n const editorRef = React.useRef(editor)\n const importedDocxKeyRef = React.useRef<string | null>(null)\n const hiddenDocxViewerRef = React.useRef<HTMLDivElement | null>(null)\n\n React.useEffect(() => {\n editorRef.current = editor\n }, [editor])\n\n React.useEffect(() => {\n if (!isActive) return\n\n const docxKey =\n typeof source === "string"\n ? `${file.name}:${source}`\n : `${file.name}:${source.size}:${source.type}`\n\n if (importedDocxKeyRef.current === docxKey) return\n\n let isCurrent = true\n importedDocxKeyRef.current = docxKey\n setHasError(false)\n setIsReady(false)\n\n async function loadDocx() {\n try {\n const docxFile = await sourceToFile(source, file)\n await editorRef.current.importDocxFile(docxFile)\n } catch {\n if (isCurrent && importedDocxKeyRef.current === docxKey) {\n setHasError(true)\n }\n }\n }\n\n void loadDocx()\n\n return () => {\n isCurrent = false\n }\n }, [file, isActive, source])\n\n React.useEffect(() => {\n if (!firstThumbnail) {\n setThumbnailSize(null)\n return\n }\n\n setThumbnailSize((currentSize) => {\n if (\n currentSize?.height === firstThumbnail.pixelHeightPx &&\n currentSize.width === firstThumbnail.pixelWidthPx\n ) {\n return currentSize\n }\n\n return {\n height: firstThumbnail.pixelHeightPx,\n width: firstThumbnail.pixelWidthPx,\n }\n })\n\n if (firstThumbnail?.status === "error") {\n setHasError(true)\n }\n }, [\n firstThumbnail,\n firstThumbnail?.pixelHeightPx,\n firstThumbnail?.pixelWidthPx,\n firstThumbnail?.status,\n ])\n\n const attachThumbnailCanvas = React.useCallback(\n (canvas: HTMLCanvasElement | null) => {\n setThumbnailCanvas(canvas)\n if (canvas) firstThumbnail?.canvasRef(canvas)\n },\n [firstThumbnail]\n )\n\n React.useEffect(() => {\n if (\n !isActive ||\n !firstThumbnail ||\n !thumbnailCanvas ||\n isReady ||\n hasError\n ) {\n return\n }\n\n let isCurrent = true\n let timeoutId: number | undefined\n let attempts = 0\n\n const getRenderedPageSurface = () => {\n const pageSurface = hiddenDocxViewerRef.current?.querySelector(\n \'[data-docx-page-surface="true"]\'\n )\n\n if (!pageSurface) return null\n\n const hasText = Boolean(pageSurface.textContent?.trim())\n const hasEmbeddedContent = Boolean(\n pageSurface.querySelector("canvas,img,svg,table")\n )\n\n return hasText || hasEmbeddedContent ? pageSurface : null\n }\n\n const checkThumbnail = () => {\n if (!isCurrent) return\n\n if (canvasHasVisiblePixels(thumbnailCanvas)) {\n setIsReady(true)\n return\n }\n\n if (!getRenderedPageSurface()) {\n attempts += 1\n\n if (attempts > 50) {\n setIsReady(true)\n return\n }\n\n timeoutId = window.setTimeout(checkThumbnail, 100)\n return\n }\n\n attempts += 1\n\n if (attempts > 50) {\n setIsReady(true)\n return\n }\n\n timeoutId = window.setTimeout(checkThumbnail, 100)\n }\n\n checkThumbnail()\n\n return () => {\n isCurrent = false\n if (timeoutId !== undefined) window.clearTimeout(timeoutId)\n }\n }, [\n firstThumbnail,\n firstThumbnail?.isMounted,\n hasError,\n isActive,\n isReady,\n thumbnailCanvas,\n ])\n\n const previewContent = thumbnailSize ? (\n <canvas\n ref={attachThumbnailCanvas}\n width={thumbnailSize.width}\n height={thumbnailSize.height}\n className="!size-full bg-white object-cover object-top"\n />\n ) : null\n\n return (\n <>\n <FileThumbnailShell\n file={file}\n previewContent={previewContent}\n isLoading={Boolean(externalIsLoading || (!isReady && !hasError))}\n hasError={Boolean(externalHasError || hasError)}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={cn("bg-white", previewClassName)}\n showMetadata={showMetadata}\n />\n {isActive && !hasError ? (\n <div\n ref={hiddenDocxViewerRef}\n aria-hidden="true"\n className="pointer-events-none fixed top-0 left-0 -z-10 h-[1056px] w-[816px] overflow-hidden bg-white opacity-0 [contain:layout_paint]"\n >\n <div className="w-[816px]">\n <DocxEditorViewer\n editor={editor}\n mode="read-only"\n pageBackgroundColor="#ffffff"\n pageGapBackgroundColor="transparent"\n visiblePageRange={{ endPageIndex: 0, startPageIndex: 0 }}\n pageVirtualization={{ enabled: false }}\n deferInitialPaginationPaint={false}\n />\n </div>\n </div>\n ) : null}\n </>\n )\n}\n\nfunction XlsxFileThumbnail({\n file,\n className,\n hasError: externalHasError,\n isActive,\n isLoading: externalIsLoading,\n previewClassName,\n previewAspectRatio,\n showMetadata,\n source,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n className?: string\n hasError?: boolean\n isActive: boolean\n isLoading?: boolean\n previewAspectRatio?: number\n previewClassName?: string\n showMetadata: boolean\n source: ThumbnailSource\n thumbnailWidth: number\n}) {\n const sourceUrl = useSourceObjectUrl(source)\n const [imageUrl, setImageUrl] = React.useState<string | null>(null)\n const [hasError, setHasError] = React.useState(false)\n\n React.useEffect(() => {\n setImageUrl(null)\n setHasError(false)\n }, [sourceUrl])\n\n return (\n <>\n <FileThumbnailShell\n file={file}\n previewImageUrl={imageUrl}\n isLoading={Boolean(externalIsLoading || (!imageUrl && !hasError))}\n hasError={Boolean(externalHasError || hasError)}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={cn(\n "bg-white [&>img]:object-left-top",\n previewClassName\n )}\n showMetadata={showMetadata}\n />\n {isActive && sourceUrl && !imageUrl && !hasError ? (\n <XlsxThumbnailGenerator\n file={file}\n sourceUrl={sourceUrl}\n thumbnailWidth={thumbnailWidth}\n onError={() => setHasError(true)}\n onImageUrl={setImageUrl}\n />\n ) : null}\n </>\n )\n}\n\nfunction XlsxThumbnailGenerator({\n file,\n onError,\n onImageUrl,\n sourceUrl,\n thumbnailWidth,\n}: {\n file: NormalizedThumbnailFile\n onError: () => void\n onImageUrl: (url: string) => void\n sourceUrl: string\n thumbnailWidth: number\n}) {\n const controller = useXlsxViewerController(\n React.useMemo(\n () => ({\n fileName: file.name,\n readOnly: true,\n src: sourceUrl,\n useWorker: true,\n }),\n [file.name, sourceUrl]\n )\n )\n\n return (\n <XlsxViewerProvider controller={controller}>\n <XlsxThumbnailGeneratorContent\n thumbnailWidth={thumbnailWidth}\n onError={onError}\n onImageUrl={onImageUrl}\n />\n </XlsxViewerProvider>\n )\n}\n\nfunction XlsxThumbnailGeneratorContent({\n onError,\n onImageUrl,\n thumbnailWidth,\n}: {\n onError: () => void\n onImageUrl: (url: string) => void\n thumbnailWidth: number\n}) {\n const controller = useXlsxViewer()\n const thumbnailOptions = React.useMemo(\n () => ({\n includeHeaders: true,\n resolution: {\n maxHeight: thumbnailWidth,\n maxWidth: thumbnailWidth,\n },\n }),\n [thumbnailWidth]\n )\n const { thumbnails } = useXlsxViewerThumbnails(thumbnailOptions)\n const firstThumbnail = thumbnails[0]\n\n React.useEffect(() => {\n if (controller.error) {\n onError()\n return\n }\n\n if (!firstThumbnail) return\n\n const canvas = document.createElement("canvas")\n\n if (!firstThumbnail.paint(canvas)) return\n\n onImageUrl(canvas.toDataURL("image/png"))\n }, [controller.error, firstThumbnail, onError, onImageUrl])\n\n return null\n}\n\nexport function FileThumbnail({\n file: rawFile,\n className,\n previewAspectRatio,\n previewClassName,\n previewContent,\n previewImageUrl,\n source: explicitSource,\n thumbnailWidth,\n generationDelayMs = 0,\n renderDocumentPreview = true,\n isLoading = false,\n hasError = false,\n showMetadata = true,\n}: FileThumbnailProps) {\n const file = React.useMemo(() => normalizeFile(rawFile), [rawFile])\n const source = getThumbnailSource(file, explicitSource)\n const isActive = useThumbnailActivation(generationDelayMs)\n\n if (previewImageUrl || previewContent || !renderDocumentPreview || !source) {\n return (\n <FileThumbnailShell\n file={file}\n previewImageUrl={previewImageUrl}\n previewContent={previewContent}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n }\n\n if (isImageFile(file)) {\n return (\n <ImageFileThumbnail\n file={file}\n source={source}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n }\n\n if (isPdfFile(file)) {\n return (\n <PdfFileThumbnail\n file={file}\n source={source}\n isActive={isActive}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n thumbnailWidth={thumbnailWidth ?? 520}\n />\n )\n }\n\n if (isDocxFile(file)) {\n return (\n <DocxFileThumbnail\n file={file}\n source={source}\n isActive={isActive}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n thumbnailWidth={thumbnailWidth ?? 520}\n />\n )\n }\n\n if (isXlsxFile(file)) {\n return (\n <XlsxFileThumbnail\n file={file}\n source={source}\n isActive={isActive}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n thumbnailWidth={thumbnailWidth ?? 680}\n />\n )\n }\n\n return (\n <FileThumbnailShell\n file={file}\n isLoading={isLoading}\n hasError={hasError}\n className={className}\n previewAspectRatio={previewAspectRatio}\n previewClassName={previewClassName}\n showMetadata={showMetadata}\n />\n )\n}\n'export function FileThumbnailSource() {return <HighlightedCodeBlock code={fileThumbnailSourceCode} />diff --git a/apps/v4/components/file-upload-docs.tsx b/apps/v4/components/file-upload-docs.tsxindex 4bd57f1..606440e 100644--- a/apps/v4/components/file-upload-docs.tsx+++ b/apps/v4/components/file-upload-docs.tsx@@ -125,7 +125,8 @@ function UploadIconCluster({"absolute top-1/2 left-1/2 grid size-12 place-items-center rounded-xl bg-background text-muted-foreground transition-[transform,color,background-color] duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] before:rounded-[calc(var(--radius-xl)-1px)]","motion-reduce:transition-none",index === 1 && "z-10",- isDragging && "bg-accent text-foreground"+ isDragging &&+ "bg-popover text-foreground shadow-md shadow-black/10 not-dark:bg-clip-border dark:shadow-black/25")}style={{transform: singleIcon@@ -201,7 +202,7 @@ export function FileUpload({"motion-reduce:transition-none",isDragging? "border-foreground/40 bg-accent/35"- : "border-border hover:border-foreground/30 hover:bg-muted/35"+ : "border-foreground/20 hover:border-foreground/35 hover:bg-muted/35 dark:border-foreground/25 dark:hover:border-foreground/40")}onDragEnter={(event) => {event.preventDefault()@@ -379,7 +380,7 @@ export function FileUploadExample() {}`const fileUploadUsageCode =- '"use client"\n\nimport * as React from "react"\nimport {\n FileImageIcon,\n FileSpreadsheetIcon,\n FileUploadIcon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { BorderBeam } from "border-beam"\n\nimport { cn } from "@/lib/utils"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Card } from "@/registry/new-york-v4/ui/card"\n\ntype FileUploadItem = {\n id: string\n name: string\n type: string\n size: number\n url: string\n}\n\ntype AcceptedFileType = {\n label: string\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n}\n\ntype FileUploadProps = {\n accept?: string\n acceptedFileTypes?: AcceptedFileType[]\n borderBeamTheme?: React.ComponentProps<typeof BorderBeam>["theme"]\n browseLabel?: string\n className?: string\n description?: string\n draggingLabel?: string\n multiple?: boolean\n showBorderBeam?: boolean\n showFileList?: boolean\n title?: string\n onFilesAccepted?: (files: File[]) => void\n onFilesChange?: (files: FileUploadItem[]) => void\n}\n\nconst ACCEPTED_FILE_TYPES: AcceptedFileType[] = [\n { label: "Image", icon: FileImageIcon },\n { label: "PDF", icon: FileUploadIcon },\n { label: "Sheet", icon: FileSpreadsheetIcon },\n]\nconst ICON_TRANSFORMS = [\n {\n idle: "translate(-78%, -50%) rotate(-8deg)",\n active: "translate(-114%, -50%) rotate(-12deg) scale(1.08)",\n },\n {\n idle: "translate(-50%, -50%) rotate(0deg)",\n active: "translate(-50%, -50%) rotate(0deg) scale(1.18)",\n },\n {\n idle: "translate(-22%, -50%) rotate(8deg)",\n active: "translate(14%, -50%) rotate(12deg) scale(1.08)",\n },\n]\n\nfunction formatBytes(bytes: number) {\n if (bytes === 0) return "0 B"\n\n const units = ["B", "KB", "MB", "GB"]\n const index = Math.min(\n Math.floor(Math.log(bytes) / Math.log(1024)),\n units.length - 1\n )\n\n return `${(bytes / 1024 ** index).toFixed(index === 0 ? 0 : 1)} ${\n units[index]\n }`\n}\n\nfunction matchesAccept(file: File, accept?: string) {\n if (!accept) return true\n\n return accept.split(",").some((rawToken) => {\n const token = rawToken.trim().toLowerCase()\n\n if (!token) return false\n if (token.startsWith(".")) return file.name.toLowerCase().endsWith(token)\n if (token.endsWith("/*")) {\n return file.type.toLowerCase().startsWith(token.slice(0, -1))\n }\n\n return file.type.toLowerCase() === token\n })\n}\n\nfunction toUploadItems(files: FileList | File[]): FileUploadItem[] {\n return Array.from(files).map((file) => ({\n id: `${file.name}-${file.size}-${file.lastModified}`,\n name: file.name,\n type: file.type || "Unknown type",\n size: file.size,\n url: URL.createObjectURL(file),\n }))\n}\n\nfunction UploadIconCluster({\n acceptedFileTypes,\n isDragging,\n}: {\n acceptedFileTypes: AcceptedFileType[]\n isDragging: boolean\n}) {\n const singleIcon = acceptedFileTypes.length === 1\n\n return (\n <div className="relative h-14 w-36">\n {acceptedFileTypes.map((item, index) => (\n <Card\n key={item.label}\n className={cn(\n "absolute top-1/2 left-1/2 grid size-12 place-items-center rounded-xl bg-background text-muted-foreground transition-[transform,color,background-color] duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] before:rounded-[calc(var(--radius-xl)-1px)]",\n "motion-reduce:transition-none",\n index === 1 && "z-10",\n isDragging && "bg-accent text-foreground"\n )}\n style={{\n transform: singleIcon\n ? `translate(-50%, -50%) scale(${isDragging ? 1.14 : 1})`\n : isDragging\n ? ICON_TRANSFORMS[index]?.active\n : ICON_TRANSFORMS[index]?.idle,\n }}\n >\n <HugeiconsIcon icon={item.icon} className="size-5" />\n </Card>\n ))}\n </div>\n )\n}\n\nexport function FileUpload({\n accept,\n acceptedFileTypes = ACCEPTED_FILE_TYPES,\n borderBeamTheme = "light",\n browseLabel = "Browse files",\n className,\n description = "PDF, DOCX, XLSX, CSV, PNG, or JPG",\n draggingLabel = "Drop to add",\n multiple = true,\n showBorderBeam = true,\n showFileList = true,\n title = "Click to upload or drop files",\n onFilesAccepted,\n onFilesChange,\n}: FileUploadProps) {\n const dragDepthRef = React.useRef(0)\n const [isDragging, setIsDragging] = React.useState(false)\n const [files, setFiles] = React.useState<FileUploadItem[]>([])\n const [rejectionMessage, setRejectionMessage] = React.useState<string | null>(\n null\n )\n\n const commitFiles = React.useCallback(\n (nextFiles: FileList | File[]) => {\n const acceptedFiles = Array.from(nextFiles)\n .filter((file) => matchesAccept(file, accept))\n .slice(0, multiple ? undefined : 1)\n\n if (acceptedFiles.length === 0) {\n setRejectionMessage("This file type is not supported here.")\n return\n }\n\n setRejectionMessage(null)\n onFilesAccepted?.(acceptedFiles)\n\n const items = toUploadItems(acceptedFiles)\n setFiles((previousFiles) => {\n previousFiles.forEach((file) => URL.revokeObjectURL(file.url))\n return items\n })\n onFilesChange?.(items)\n },\n [accept, multiple, onFilesAccepted, onFilesChange]\n )\n\n React.useEffect(() => {\n return () => {\n files.forEach((file) => URL.revokeObjectURL(file.url))\n }\n }, [files])\n\n const dropzone = (\n <label\n className={cn(\n "relative flex min-h-64 cursor-pointer flex-col items-center justify-center gap-5 overflow-hidden rounded-[1.125rem] border border-dashed bg-background px-6 py-10 text-center transition-[border-color,background-color] duration-200 ease-out",\n "motion-reduce:transition-none",\n isDragging\n ? "border-foreground/40 bg-accent/35"\n : "border-border hover:border-foreground/30 hover:bg-muted/35"\n )}\n onDragEnter={(event) => {\n event.preventDefault()\n dragDepthRef.current += 1\n setIsDragging(true)\n }}\n onDragLeave={(event) => {\n event.preventDefault()\n dragDepthRef.current = Math.max(0, dragDepthRef.current - 1)\n if (dragDepthRef.current === 0) setIsDragging(false)\n }}\n onDragOver={(event) => event.preventDefault()}\n onDrop={(event) => {\n event.preventDefault()\n dragDepthRef.current = 0\n setIsDragging(false)\n if (event.dataTransfer.files.length > 0) {\n commitFiles(event.dataTransfer.files)\n }\n }}\n >\n <UploadIconCluster\n acceptedFileTypes={acceptedFileTypes}\n isDragging={isDragging}\n />\n <div className="space-y-1">\n <div className="text-sm font-medium">{title}</div>\n <div className="text-xs text-muted-foreground">{description}</div>\n {rejectionMessage ? (\n <div className="text-xs text-destructive">{rejectionMessage}</div>\n ) : null}\n </div>\n <div className="inline-flex items-center gap-2 rounded-full border bg-background px-3 py-1 text-xs text-muted-foreground">\n <HugeiconsIcon icon={Upload01Icon} className="size-3.5" />\n <span>{isDragging ? draggingLabel : browseLabel}</span>\n </div>\n <input\n type="file"\n accept={accept}\n multiple={multiple}\n className="sr-only"\n onChange={(event) => {\n if (event.target.files) {\n commitFiles(event.target.files)\n event.currentTarget.value = ""\n }\n }}\n />\n </label>\n )\n\n return (\n <div className={cn("space-y-3", className)}>\n {showBorderBeam ? (\n <BorderBeam\n active={isDragging}\n borderRadius={18}\n brightness={2.4}\n className="rounded-[1.125rem]"\n colorVariant="ocean"\n duration={2.4}\n size="md"\n strength={1}\n theme={borderBeamTheme}\n >\n {dropzone}\n </BorderBeam>\n ) : (\n dropzone\n )}\n {showFileList && files.length > 0 ? (\n <div className="rounded-xl border bg-background">\n {files.map((file) => (\n <div\n key={file.id}\n className="flex items-center gap-3 border-b px-3 py-2.5 last:border-b-0"\n >\n <FileThumbnail\n file={{\n name: file.name,\n type: file.type,\n size: formatBytes(file.size),\n }}\n previewImageUrl={\n file.type.startsWith("image/") ? file.url : null\n }\n className="size-10 shrink-0 rounded-lg"\n showMetadata={false}\n />\n <div className="min-w-0 flex-1">\n <div className="truncate text-sm font-medium">{file.name}</div>\n <div className="truncate text-xs text-muted-foreground">\n {file.type} - {formatBytes(file.size)}\n </div>\n </div>\n <div className="rounded-full bg-muted px-2 py-1 text-xs text-muted-foreground">\n Ready\n </div>\n </div>\n ))}\n </div>\n ) : null}\n </div>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n FileImageIcon,\n FileSpreadsheetIcon,\n FileUploadIcon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { BorderBeam } from "border-beam"\n\nimport { cn } from "@/lib/utils"\nimport { FileThumbnail } from "@/components/ui/file-thumbnail"\nimport { Card } from "@/registry/new-york-v4/ui/card"\n\ntype FileUploadItem = {\n id: string\n name: string\n type: string\n size: number\n url: string\n}\n\ntype AcceptedFileType = {\n label: string\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n}\n\ntype FileUploadProps = {\n accept?: string\n acceptedFileTypes?: AcceptedFileType[]\n borderBeamTheme?: React.ComponentProps<typeof BorderBeam>["theme"]\n browseLabel?: string\n className?: string\n description?: string\n draggingLabel?: string\n multiple?: boolean\n showBorderBeam?: boolean\n showFileList?: boolean\n title?: string\n onFilesAccepted?: (files: File[]) => void\n onFilesChange?: (files: FileUploadItem[]) => void\n}\n\nconst ACCEPTED_FILE_TYPES: AcceptedFileType[] = [\n { label: "Image", icon: FileImageIcon },\n { label: "PDF", icon: FileUploadIcon },\n { label: "Sheet", icon: FileSpreadsheetIcon },\n]\nconst ICON_TRANSFORMS = [\n {\n idle: "translate(-78%, -50%) rotate(-8deg)",\n active: "translate(-114%, -50%) rotate(-12deg) scale(1.08)",\n },\n {\n idle: "translate(-50%, -50%) rotate(0deg)",\n active: "translate(-50%, -50%) rotate(0deg) scale(1.18)",\n },\n {\n idle: "translate(-22%, -50%) rotate(8deg)",\n active: "translate(14%, -50%) rotate(12deg) scale(1.08)",\n },\n]\n\nfunction formatBytes(bytes: number) {\n if (bytes === 0) return "0 B"\n\n const units = ["B", "KB", "MB", "GB"]\n const index = Math.min(\n Math.floor(Math.log(bytes) / Math.log(1024)),\n units.length - 1\n )\n\n return `${(bytes / 1024 ** index).toFixed(index === 0 ? 0 : 1)} ${\n units[index]\n }`\n}\n\nfunction matchesAccept(file: File, accept?: string) {\n if (!accept) return true\n\n return accept.split(",").some((rawToken) => {\n const token = rawToken.trim().toLowerCase()\n\n if (!token) return false\n if (token.startsWith(".")) return file.name.toLowerCase().endsWith(token)\n if (token.endsWith("/*")) {\n return file.type.toLowerCase().startsWith(token.slice(0, -1))\n }\n\n return file.type.toLowerCase() === token\n })\n}\n\nfunction toUploadItems(files: FileList | File[]): FileUploadItem[] {\n return Array.from(files).map((file) => ({\n id: `${file.name}-${file.size}-${file.lastModified}`,\n name: file.name,\n type: file.type || "Unknown type",\n size: file.size,\n url: URL.createObjectURL(file),\n }))\n}\n\nfunction UploadIconCluster({\n acceptedFileTypes,\n isDragging,\n}: {\n acceptedFileTypes: AcceptedFileType[]\n isDragging: boolean\n}) {\n const singleIcon = acceptedFileTypes.length === 1\n\n return (\n <div className="relative h-14 w-36">\n {acceptedFileTypes.map((item, index) => (\n <Card\n key={item.label}\n className={cn(\n "absolute top-1/2 left-1/2 grid size-12 place-items-center rounded-xl bg-background text-muted-foreground transition-[transform,color,background-color] duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] before:rounded-[calc(var(--radius-xl)-1px)]",\n "motion-reduce:transition-none",\n index === 1 && "z-10",\n isDragging &&\n "bg-popover text-foreground shadow-md shadow-black/10 not-dark:bg-clip-border dark:shadow-black/25"\n )}\n style={{\n transform: singleIcon\n ? `translate(-50%, -50%) scale(${isDragging ? 1.14 : 1})`\n : isDragging\n ? ICON_TRANSFORMS[index]?.active\n : ICON_TRANSFORMS[index]?.idle,\n }}\n >\n <HugeiconsIcon icon={item.icon} className="size-5" />\n </Card>\n ))}\n </div>\n )\n}\n\nexport function FileUpload({\n accept,\n acceptedFileTypes = ACCEPTED_FILE_TYPES,\n borderBeamTheme = "light",\n browseLabel = "Browse files",\n className,\n description = "PDF, DOCX, XLSX, CSV, PNG, or JPG",\n draggingLabel = "Drop to add",\n multiple = true,\n showBorderBeam = true,\n showFileList = true,\n title = "Click to upload or drop files",\n onFilesAccepted,\n onFilesChange,\n}: FileUploadProps) {\n const dragDepthRef = React.useRef(0)\n const [isDragging, setIsDragging] = React.useState(false)\n const [files, setFiles] = React.useState<FileUploadItem[]>([])\n const [rejectionMessage, setRejectionMessage] = React.useState<string | null>(\n null\n )\n\n const commitFiles = React.useCallback(\n (nextFiles: FileList | File[]) => {\n const acceptedFiles = Array.from(nextFiles)\n .filter((file) => matchesAccept(file, accept))\n .slice(0, multiple ? undefined : 1)\n\n if (acceptedFiles.length === 0) {\n setRejectionMessage("This file type is not supported here.")\n return\n }\n\n setRejectionMessage(null)\n onFilesAccepted?.(acceptedFiles)\n\n const items = toUploadItems(acceptedFiles)\n setFiles((previousFiles) => {\n previousFiles.forEach((file) => URL.revokeObjectURL(file.url))\n return items\n })\n onFilesChange?.(items)\n },\n [accept, multiple, onFilesAccepted, onFilesChange]\n )\n\n React.useEffect(() => {\n return () => {\n files.forEach((file) => URL.revokeObjectURL(file.url))\n }\n }, [files])\n\n const dropzone = (\n <label\n className={cn(\n "relative flex min-h-64 cursor-pointer flex-col items-center justify-center gap-5 overflow-hidden rounded-[1.125rem] border border-dashed bg-background px-6 py-10 text-center transition-[border-color,background-color] duration-200 ease-out",\n "motion-reduce:transition-none",\n isDragging\n ? "border-foreground/40 bg-accent/35"\n : "border-foreground/20 hover:border-foreground/35 hover:bg-muted/35 dark:border-foreground/25 dark:hover:border-foreground/40"\n )}\n onDragEnter={(event) => {\n event.preventDefault()\n dragDepthRef.current += 1\n setIsDragging(true)\n }}\n onDragLeave={(event) => {\n event.preventDefault()\n dragDepthRef.current = Math.max(0, dragDepthRef.current - 1)\n if (dragDepthRef.current === 0) setIsDragging(false)\n }}\n onDragOver={(event) => event.preventDefault()}\n onDrop={(event) => {\n event.preventDefault()\n dragDepthRef.current = 0\n setIsDragging(false)\n if (event.dataTransfer.files.length > 0) {\n commitFiles(event.dataTransfer.files)\n }\n }}\n >\n <UploadIconCluster\n acceptedFileTypes={acceptedFileTypes}\n isDragging={isDragging}\n />\n <div className="space-y-1">\n <div className="text-sm font-medium">{title}</div>\n <div className="text-xs text-muted-foreground">{description}</div>\n {rejectionMessage ? (\n <div className="text-xs text-destructive">{rejectionMessage}</div>\n ) : null}\n </div>\n <div className="inline-flex items-center gap-2 rounded-full border bg-background px-3 py-1 text-xs text-muted-foreground">\n <HugeiconsIcon icon={Upload01Icon} className="size-3.5" />\n <span>{isDragging ? draggingLabel : browseLabel}</span>\n </div>\n <input\n type="file"\n accept={accept}\n multiple={multiple}\n className="sr-only"\n onChange={(event) => {\n if (event.target.files) {\n commitFiles(event.target.files)\n event.currentTarget.value = ""\n }\n }}\n />\n </label>\n )\n\n return (\n <div className={cn("space-y-3", className)}>\n {showBorderBeam ? (\n <BorderBeam\n active={isDragging}\n borderRadius={18}\n brightness={2.4}\n className="rounded-[1.125rem]"\n colorVariant="ocean"\n duration={2.4}\n size="md"\n strength={1}\n theme={borderBeamTheme}\n >\n {dropzone}\n </BorderBeam>\n ) : (\n dropzone\n )}\n {showFileList && files.length > 0 ? (\n <div className="rounded-xl border bg-background">\n {files.map((file) => (\n <div\n key={file.id}\n className="flex items-center gap-3 border-b px-3 py-2.5 last:border-b-0"\n >\n <FileThumbnail\n file={{\n name: file.name,\n type: file.type,\n size: formatBytes(file.size),\n }}\n previewImageUrl={\n file.type.startsWith("image/") ? file.url : null\n }\n className="size-10 shrink-0 rounded-lg"\n showMetadata={false}\n />\n <div className="min-w-0 flex-1">\n <div className="truncate text-sm font-medium">{file.name}</div>\n <div className="truncate text-xs text-muted-foreground">\n {file.type} - {formatBytes(file.size)}\n </div>\n </div>\n <div className="rounded-full bg-muted px-2 py-1 text-xs text-muted-foreground">\n Ready\n </div>\n </div>\n ))}\n </div>\n ) : null}\n </div>\n )\n}\n'export function FileUploadSource() {return <HighlightedCodeBlock code={fileUploadUsageCode} />diff --git a/apps/v4/components/human-review-block-expected-output.json b/apps/v4/components/human-review-block-expected-output.jsonnew file mode 100644index 0000000..d35dd30--- /dev/null+++ b/apps/v4/components/human-review-block-expected-output.json@@ -0,0 +1,1086 @@+{+ "transactions": [+ {+ "date": "2021-10-01",+ "amount": 8465,+ "category": "Deposits and Additions",+ "description": "American Express Settlement 4098628803 CCD ID: 1134992250"+ },+ {+ "date": "2021-10-04",+ "amount": 7750,+ "category": "Deposits and Additions",+ "description": "Fed Wire Credit Via: Intercredit Bank N.A./067011812 B/O: Alexton International Limited Tortola, Virgin Islands Ref: Chase Nyc/Ctr/Bnf=ELEGANT CABINETRY, INC 331384612/Ac-000000042313 Rfb=O/B Intercredit Obi=Mantenimiento. FRANKLIN VALERIO Imad: 0404Qmgft001002628 Trn: 4644109094Ff"+ },+ {+ "date": "2021-10-05",+ "amount": 9524,+ "category": "Deposits and Additions",+ "description": "Fed Wire Credit Via: Biscayne Bank/066015767 B/O: Ernesto Andres Estrada Guayaquil Ecuador 000000000 Ref: Chase Nyc/Ctr/Bnf=ELEGANT CABINETRY, INC 331384612/Ac-000000042313 Rfb=O/B Biscayne Bk Obi=Ref Mantenimiento Del Bote Abril 11 Invoice N Imad: 0405Qmgft003000505 Trn: 1571509095Ff"+ },+ {+ "date": "2021-10-08",+ "amount": 9750,+ "category": "Deposits and Additions",+ "description": "Fed Wire Credit Via: Intercredit Bank N.A./067011812 B/O: Alexton International Limited Tortola, Virgin Islands Ref: Chase Nyc/Ctr/Bnf=ELEGANT CABINETRY, INC 331384612/Ac-000000042313 Rfb=O/B Intercredit Obi=Mantenimiento. FRANKLIN VALERIO Imad: 0408Qmgft007002614 Trn: 4924109098Ff"+ },+ {+ "date": "2021-10-12",+ "amount": 716.92,+ "category": "Deposits and Additions",+ "description": "Merch Svc Bkcrd Dep 899000001725249 CCD ID: 1246827607"+ },+ {+ "date": "2021-10-12",+ "amount": 300,+ "category": "Deposits and Additions",+ "description": "Merchant Bnkcd Deposit 434367702884 CCD ID: 8752044092"+ },+ {+ "date": "2021-10-13",+ "amount": 139.63,+ "category": "Deposits and Additions",+ "description": "Card Purchase Return 10/11 U R* Kmart 04295 North Miami FL Card 6657"+ },+ {+ "date": "2021-10-15",+ "amount": 8750,+ "category": "Deposits and Additions",+ "description": "Fed Wire Credit Via: Intercredit Bank N.A./067011812 B/O: Alexton International Limited Tortola, Virgin Islands Ref: Chase Nyc/Ctr/Bnf=ELEGANT CABINETRY, INC 331384612/Ac-000000042313 Rfb=O/B Intercredit Obi=Mantenimiento. FRANKLIN VALERIO Imad: 0415Qmgft004003424 Trn: 6654909105Ff"+ },+ {+ "date": "2021-10-18",+ "amount": 582.7,+ "category": "Deposits and Additions",+ "description": "Card Purchase Return 10/15 U R* Kvh Industries 401-8452400 RI Card 6657"+ },+ {+ "date": "2021-10-18",+ "amount": 806.31,+ "category": "Deposits and Additions",+ "description": "Merch Svc Bkcrd Dep 899000001725249 CCD ID: 1246827607"+ },+ {+ "date": "2021-10-19",+ "amount": 4.75,+ "category": "Deposits and Additions",+ "description": "Partial Refund: Annual Fee, Ultimate Rewards Card Ending IN 6657"+ },+ {+ "date": "2021-10-19",+ "amount": 8060,+ "category": "Deposits and Additions",+ "description": "Paymentech Deposit 5322298 CCD ID: 1020401225"+ },+ {+ "date": "2021-10-21",+ "amount": 19772.13,+ "category": "Deposits and Additions",+ "description": "American Express Settlement 4098628803 CCD ID: 1134992250"+ },+ {+ "date": "2021-10-22",+ "amount": 7750,+ "category": "Deposits and Additions",+ "description": "Fed Wire Credit Via: Intercredit Bank N.A./067011812 B/O: Alexton International Limited Tortola, Virgin Islands Ref: Chase Nyc/Ctr/Bnf=ELEGANT CABINETRY, INC 331384612/Ac-000000042313 Rfb=O/B Intercredit Obi=Mantenimiento. FRANKLIN VALERIO Imad: 0422Qmgft008000100 Trn: 0692509112Ff"+ },+ {+ "date": "2021-10-25",+ "amount": 9529.1,+ "category": "Deposits and Additions",+ "description": "American Express Settlement 4098628803 CCD ID: 1134992250"+ },+ {+ "date": "2021-10-29",+ "amount": 8750,+ "category": "Deposits and Additions",+ "description": "Fed Wire Credit Via: Intercredit Bank N.A./067011812 B/O: Alexton International Limited Tortola Virgin Islands Ref: Chase Nyc/Ctr/Bnf=ELEGANT CABINETRY, INC 331384612/Ac-000000042313 Rfb=O/B Intercredit Obi=Mantenimiento. FRANKLIN VALERIO Imad: 0429Qmgft015003211 Trn: 5801309119Ff"+ },+ {+ "date": "2021-10-05",+ "amount": -821.01,+ "category": "Checks Paid",+ "description": "Check 1012"+ },+ {+ "date": "2021-10-01",+ "amount": -20.91,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 09/28 U R* Magicjack 561-5 561-5942140 FL Card 6657"+ },+ {+ "date": "2021-10-01",+ "amount": -15.33,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 09/30 U R* M And R Sweet Candy Miami FL Card 6657"+ },+ {+ "date": "2021-10-01",+ "amount": -453.46,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/01 U R* Sprint *Wireles 800-639-611 VA Card 6657"+ },+ {+ "date": "2021-10-01",+ "amount": -19.58,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 09/31 U R* LA Baguette Miami FL Card 6657"+ },+ {+ "date": "2021-10-01",+ "amount": -303,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Non-Chase ATM Withdraw 10/01 *Bay Point Miami FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -97.5,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/01 U R* Hostgator Com 713-5745287 TX Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -6.31,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/01 U R* Burger King #33 Miami FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -19.78,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/01 Subway 00008995 Miami FL Card 7969"+ },+ {+ "date": "2021-10-04",+ "amount": -70.71,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/01 Publix #794 Miami Shores FL Card 7969"+ },+ {+ "date": "2021-10-04",+ "amount": -8.06,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/02 U R* Google*Goog3543 [email protected] CA Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -2.99,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/02 U R* 7-Eleven 10529 Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -14.32,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/02 U R* LA Baguette Miami FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -187.02,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/02 Kmart 04295 North Miami FL Card 7969"+ },+ {+ "date": "2021-10-04",+ "amount": -14.74,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/02 Burger King #3711 Miami Shores FL Card 7969"+ },+ {+ "date": "2021-10-04",+ "amount": -10.13,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/02 U R* Wendys #1713 Q Miami FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -88.1,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/03 Publix #794 Miami Shores FL Card 7969"+ },+ {+ "date": "2021-10-04",+ "amount": -22,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Non-Chase ATM Withdraw 10/04 9050 Biscayne Blvd Miami Shores FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -2000,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase With Pin 10/04 Buchwald Jewele/36 N.E Miami FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -202.5,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Non-Chase ATM Withdraw 10/04 36 NE 1 St Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -202.5,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Non-Chase ATM Withdraw 10/04 36 NE 1 St Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -132.11,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Recurring Card Purchase 10/02 U R* 8X8, Inc. 888-8 888-8988733 CA Card 6657"+ },+ {+ "date": "2021-10-05",+ "amount": -9.81,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/03 Mcdonald's F11511 Miami FL Card 7969"+ },+ {+ "date": "2021-10-05",+ "amount": -31.68,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/03 U R* Latin Cafe Miami FL Card 6657"+ },+ {+ "date": "2021-10-05",+ "amount": -68.41,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/03 Toys R US #8709 N Miami Beach FL Card 7969"+ },+ {+ "date": "2021-10-05",+ "amount": -31.11,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/03 Cvspharmacy #4249 Q03 Miami FL Card 7969"+ },+ {+ "date": "2021-10-05",+ "amount": -16.96,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/04 U R* Steves Pizza North Miami FL Card 6657"+ },+ {+ "date": "2021-10-05",+ "amount": -265.05,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/04 U R* Paypal *Elsnert 402-935-773 CA Card 6657"+ },+ {+ "date": "2021-10-05",+ "amount": -6.61,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/04 Mcdonald's F11511 Miami FL Card 7969"+ },+ {+ "date": "2021-10-05",+ "amount": -26.93,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/04 U R* Cafe Nosh Miami FL Card 6657"+ },+ {+ "date": "2021-10-05",+ "amount": -127.56,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase With Pin 10/05 Costco Whse #0182 North Miami FL Card 6657"+ },+ {+ "date": "2021-10-05",+ "amount": -275,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase With Pin 10/05 Costco Whse #0182 North Miami FL Card 6657"+ },+ {+ "date": "2021-10-06",+ "amount": -419.01,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/04 U R* Padron Cigars 305-6432117 FL Card 6657"+ },+ {+ "date": "2021-10-06",+ "amount": -11.75,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/04 NETFLIX Inc#1224 Miami Shore FL Card 7969"+ },+ {+ "date": "2021-10-06",+ "amount": -26.48,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/04 Papa John's #0428 305-754-2666 FL Card 7969"+ },+ {+ "date": "2021-10-06",+ "amount": -18.87,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/05 U R* New York Bagel Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-06",+ "amount": -331.57,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/05 Bass Pro Shops Dania FL Card 7969"+ },+ {+ "date": "2021-10-07",+ "amount": -67.12,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/05 Hess 09565 N. Bay Villag FL Card 7969"+ },+ {+ "date": "2021-10-07",+ "amount": -16.1,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/05 Pollo Tropical #15 North Miami FL Card 7969"+ },+ {+ "date": "2021-10-07",+ "amount": -12.81,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/05 U R* Navarro Discount PHA Miami FL Card 6657"+ },+ {+ "date": "2021-10-07",+ "amount": -92.47,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/06 U R* Miami Beach Gol Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-07",+ "amount": -116.85,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/06 U R* Publix #794 Miami Shores FL Card 6657"+ },+ {+ "date": "2021-10-07",+ "amount": -564,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Recurring Card Purchase 10/06 U R* Kwon Jae-Hwa Ta 305-759-667 FL Card 6657"+ },+ {+ "date": "2021-10-08",+ "amount": -38.83,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/06 U R* Miami Beach Gol Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-08",+ "amount": -15.04,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/06 U R* Deco Drive Ciga Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-08",+ "amount": -34.3,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/07 U R* Los Ranchos Restaura Miami FL Card 6657"+ },+ {+ "date": "2021-10-08",+ "amount": -3,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/08 U R* Miami Beach Met Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-08",+ "amount": -5.16,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/07 Sabor Tropical #4 Miami FL Card 7969"+ },+ {+ "date": "2021-10-11",+ "amount": -13.45,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/07 U R* LA Sandwicherie Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -13.88,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/07 U R* NETFLIX Inc Miami Shore FL Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -24.95,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/09 U R* Peoplefinders.C 800-718-899 CA Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -36.38,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/08 U R* Capt Harrys Fishing Miami FL Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -9150,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/08 U R* Kvh Industries 401-8458168 RI Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -43.14,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/09 U R* Bertoni Lounge N. Miami FL Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -12.52,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/09 U R* Taco Rico South Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -12,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/08 U R* Harlen Cigars C Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -24,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/08 U R* Paypal *Naugleb 402-935-773 CA Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -259.03,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/10 U R* Google*Goog2305 [email protected] CA Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -55.09,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/09 U R* Latin Cafe Miami FL Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -37.97,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/10 Publix #794 Miami Shores FL Card 7969"+ },+ {+ "date": "2021-10-11",+ "amount": -25.68,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/10 U R* Biscayne Blvd Stn Miami FL Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -5.34,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/10 U R* Cracker Barrel Florida City FL Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -42.57,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/10 U R* Cracker Barrel Florida City FL Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -49.18,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/10 Cracker Barrel #545 Florida City FL Card 7969"+ },+ {+ "date": "2021-10-11",+ "amount": -8.04,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/10 U R* Mcdonald's F5090 Tavernier FL Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -10.69,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Recurring Card Purchase 10/09 U R* Best Buy 0000 Aventura FL Card 6657"+ },+ {+ "date": "2021-10-11",+ "amount": -7.48,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Recurring Card Purchase 10/09 U R* Best Buy 0000 Aventura FL Card 6657"+ },+ {+ "date": "2021-10-12",+ "amount": -79.4,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/10 U R* Sunset Grille & Ra Marathon FL Card 6657"+ },+ {+ "date": "2021-10-12",+ "amount": -17.74,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/10 U R* Exxonmobil 9674 Marathon FL Card 6657"+ },+ {+ "date": "2021-10-12",+ "amount": -61.9,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/10 U R* Exxonmobil 9674 Marathon FL Card 6657"+ },+ {+ "date": "2021-10-12",+ "amount": -11.1,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/10 U R* Walgreens #1148 Florida Cit FL Card 6657"+ },+ {+ "date": "2021-10-12",+ "amount": -17.11,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/10 U R* Walgreens #1148 Florida Cit FL Card 6657"+ },+ {+ "date": "2021-10-12",+ "amount": -1.16,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/10 U R* Exxonmobil 9 Florida Cit FL Card 6657"+ },+ {+ "date": "2021-10-12",+ "amount": -22.03,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/11 U R* Bagels & Company Inc Miami FL Card 6657"+ },+ {+ "date": "2021-10-12",+ "amount": -5.4,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/11 U R* Petco 2744 6 North Miami FL Card 6657"+ },+ {+ "date": "2021-10-12",+ "amount": -25,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/11 U R* Natl Vessel Doc Falling Wat WV Card 6657"+ },+ {+ "date": "2021-10-13",+ "amount": -641.34,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/11 U R* Kmart 04295 North Miami FL Card 6657"+ },+ {+ "date": "2021-10-13",+ "amount": -21.47,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/12 U R* Mcdonald's F11511 Miami FL Card 6657"+ },+ {+ "date": "2021-10-13",+ "amount": -123.5,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Non-Chase ATM Withdraw 10/13 401 Biscayne Blvd Miami FL Card 6657"+ },+ {+ "date": "2021-10-13",+ "amount": -103.5,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Non-Chase ATM Withdraw 10/13 401 Biscayne Blvd Miami FL Card 6657"+ },+ {+ "date": "2021-10-14",+ "amount": -26.64,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/12 U R* Kabobji Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-14",+ "amount": -10.03,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/12 U R* Deco Drive Ciga Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-14",+ "amount": -21.27,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/13 U R* New York Bagel Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-14",+ "amount": -83,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Non-Chase ATM Withdraw 10/14 *Washington Avenue Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-15",+ "amount": -26.64,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/13 U R* LA Baguette Miami FL Card 6657"+ },+ {+ "date": "2021-10-15",+ "amount": -21.38,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/14 U R* Steves Pizza North Miami FL Card 6657"+ },+ {+ "date": "2021-10-15",+ "amount": -114.61,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/14 Target 000103 North Miami FL Card 7969"+ },+ {+ "date": "2021-10-18",+ "amount": -257.27,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/15 Hotels.Com US 800-219-4606 WA Card 7969"+ },+ {+ "date": "2021-10-18",+ "amount": -12.49,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/15 U R* Mcdonald's F143 Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-18",+ "amount": -5.1,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/15 U R* Mcdonald's F143 Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-18",+ "amount": -54.69,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/15 Walgreens #3173 Miami Shores FL Card 7969"+ },+ {+ "date": "2021-10-18",+ "amount": -92.68,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/15 Publix #794 Miami Shores FL Card 7969"+ },+ {+ "date": "2021-10-18",+ "amount": -71.61,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/16 Asha Quik Mart Miami FL Card 7969"+ },+ {+ "date": "2021-10-18",+ "amount": -39,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/16 Denny's #7455 North Miami FL Card 7969"+ },+ {+ "date": "2021-10-18",+ "amount": -28.04,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/17 Steak-N-Shake#0563 Q9 Hallandale FL Card 7969"+ },+ {+ "date": "2021-10-19",+ "amount": -12,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/17 Amc Stubs 010964 816-2214000 MO Card 7969"+ },+ {+ "date": "2021-10-19",+ "amount": -36,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/17 Amc Aventura 201005883 Aventura FL Card 7969"+ },+ {+ "date": "2021-10-19",+ "amount": -35.25,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/17 Amc Aventura 201005883 Aventura FL Card 7969"+ },+ {+ "date": "2021-10-19",+ "amount": -52,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/18 Metropcs 877-315-6074 TX Card 7969"+ },+ {+ "date": "2021-10-20",+ "amount": -11.95,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/19 U R* Paypams.Com 052 877-7267586 CO Card 6657"+ },+ {+ "date": "2021-10-20",+ "amount": -16.95,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/19 U R* Paypams.Com 052 877-7267586 CO Card 6657"+ },+ {+ "date": "2021-10-20",+ "amount": -9.95,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/19 U R* Paypams.Com 052 877-7267586 CO Card 6657"+ },+ {+ "date": "2021-10-20",+ "amount": -12.29,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/19 Fedex Office #0772 Miami FL Card 7969"+ },+ {+ "date": "2021-10-21",+ "amount": -183.43,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/20 U R* Clubflyers.Com 305-591-7600 FL Card 6657"+ },+ {+ "date": "2021-10-21",+ "amount": -129.72,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/19 Office Depot #25 N Miami FL Card 7969"+ },+ {+ "date": "2021-10-21",+ "amount": -9.07,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/20 Walgreens #3173 Miami Shores FL Card 7969"+ },+ {+ "date": "2021-10-22",+ "amount": -44.74,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/21 Publix #794 Miami Shores FL Card 7969"+ },+ {+ "date": "2021-10-22",+ "amount": -18.18,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Recurring Card Purchase 10/21 V.Com 866-692-2789 TX Card 7969"+ },+ {+ "date": "2021-10-25",+ "amount": -25,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/19 U R* Skype Communicat Luxembourg Card 6657"+ },+ {+ "date": "2021-10-25",+ "amount": -44.1,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/19 U R* Sampson Cay Club Encampment WY Card 6657"+ },+ {+ "date": "2021-10-25",+ "amount": -10,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/21 Exxonmobil 76638758 Aventura FL Card 7969"+ },+ {+ "date": "2021-10-25",+ "amount": -69.08,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/22 7-Eleven 30015 North Miami FL Card 7969"+ },+ {+ "date": "2021-10-25",+ "amount": -16.95,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Recurring Card Purchase 10/24 J2 *Efax Plus Servic 323-817-320 CA Card 7969"+ },+ {+ "date": "2021-10-25",+ "amount": -14.99,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Recurring Card Purchase 10/23 U R* Yousendit Inc 866-5587363 CA Card 6657"+ },+ {+ "date": "2021-10-25",+ "amount": -10,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Recurring Card Purchase 10/22 U R* Sunpass Operati 888-8655352 FL Card 6657"+ },+ {+ "date": "2021-10-26",+ "amount": -62.05,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/24 Hess 09574 Lake Buena VI FL Card 7969"+ },+ {+ "date": "2021-10-26",+ "amount": -114.44,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/26 U R* Comcast Cable C 800-Comcast FL Card 6657"+ },+ {+ "date": "2021-10-26",+ "amount": -10,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Recurring Card Purchase 10/24 U R* Sunpass Operati 888-8655352 FL Card 6657"+ },+ {+ "date": "2021-10-27",+ "amount": -64.42,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/26 Publix #794 Miami Shores FL Card 7969"+ },+ {+ "date": "2021-10-28",+ "amount": -76456.67,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/27 Kitchen Solvers of MIA FL Card 6657"+ },+ {+ "date": "2021-10-29",+ "amount": -7.47,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/27 Pollo Tropical #15 North Miami FL Card 7969"+ },+ {+ "date": "2021-10-29",+ "amount": -2.95,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/28 U R* Google *Future Google.Com/C CA Card 6657"+ },+ {+ "date": "2021-10-29",+ "amount": -82651,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/28 Lignin Custom Woodwork Miami FL Card 6657"+ },+ {+ "date": "2021-10-29",+ "amount": -21.76,+ "category": "ATM & Debit Card Withdrawals",+ "description": "Card Purchase 10/28 Walgreens #2790 Miami FL Card 7969"+ },+ {+ "date": "2021-10-01",+ "amount": -4.95,+ "category": "Electronic Withdrawals",+ "description": "American Express Collection 4098628803 CCD ID: 1134992250"+ },+ {+ "date": "2021-10-04",+ "amount": -12.53,+ "category": "Electronic Withdrawals",+ "description": "Merch Svc Bkcrd Fees 899000001725249 CCD ID: 1246827607"+ },+ {+ "date": "2021-10-05",+ "amount": -275.17,+ "category": "Electronic Withdrawals",+ "description": "Merchant Bnkcd Fee 434367702884 CCD ID: 8752044092"+ },+ {+ "date": "2021-10-05",+ "amount": -224.42,+ "category": "Electronic Withdrawals",+ "description": "American Express Axp Discnt 4098628803 CCD ID: 1134992250"+ },+ {+ "date": "2021-10-06",+ "amount": -560,+ "category": "Electronic Withdrawals",+ "description": "Paypal Inst Xfer 582J24Uh8Nzwn Web ID: Paypalsi66"+ },+ {+ "date": "2021-10-06",+ "amount": -30,+ "category": "Electronic Withdrawals",+ "description": "Paypal Inst Xfer 582J24Uhrurlq Web ID: Paypalsi66"+ },+ {+ "date": "2021-10-07",+ "amount": -375,+ "category": "Electronic Withdrawals",+ "description": "10/07 Online Payment 1075219852 To Anthony Robinson"+ },+ {+ "date": "2021-10-13",+ "amount": -405,+ "category": "Electronic Withdrawals",+ "description": "Rcg Infosoft Pvt Iat Paypal 582J24Uyuzl7J Web ID: 770510487C"+ },+ {+ "date": "2021-10-13",+ "amount": -49.99,+ "category": "Electronic Withdrawals",+ "description": "Paypal Inst Xfer 582J24Uy5E9H8 Web ID: Paypalsi66"+ },+ {+ "date": "2021-10-19",+ "amount": -1656.25,+ "category": "Electronic Withdrawals",+ "description": "10/19 Online Payment 1085065424 To Maritime Coverage"+ },+ {+ "date": "2021-10-20",+ "amount": -100,+ "category": "Electronic Withdrawals",+ "description": "Paymentech Fin ADJ 5322298 CCD ID: 1020401225"+ },+ {+ "date": "2021-10-21",+ "amount": -1100,+ "category": "Electronic Withdrawals",+ "description": "10/21 Online Payment 1086464662 To Ford Motor Credit"+ },+ {+ "date": "2021-10-21",+ "amount": -700,+ "category": "Electronic Withdrawals",+ "description": "10/21 Online Payment 1086464663 To Ford Motor Credit"+ },+ {+ "date": "2021-10-21",+ "amount": -2010,+ "category": "Electronic Withdrawals",+ "description": "10/21 Online Payment 1086474572 To Keybank"+ },+ {+ "date": "2021-10-21",+ "amount": -154.83,+ "category": "Electronic Withdrawals",+ "description": "Fpl Direct Debit Elec Pymt 1206922419 Webi Web ID: 3590247775"+ },+ {+ "date": "2021-10-26",+ "amount": -383.36,+ "category": "Electronic Withdrawals",+ "description": "Security Natl IN Ins Paymt G00 3487914 02 PPD ID: 2650109120"+ },+ {+ "date": "2021-10-28",+ "amount": -9.99,+ "category": "Electronic Withdrawals",+ "description": "Vbbcom Limited Iat Paypal 582J24Vy689Aw Web ID: 770510487C"+ },+ {+ "date": "2021-10-01",+ "amount": -2,+ "category": "Fees and Other Withdrawals",+ "description": "Non-Chase ATM Fee-With"+ },+ {+ "date": "2021-10-04",+ "amount": -15,+ "category": "Fees and Other Withdrawals",+ "description": "Incoming Domestic Wire Fee"+ },+ {+ "date": "2021-10-04",+ "amount": -8,+ "category": "Fees and Other Withdrawals",+ "description": "Non-Chase ATM Fee-With"+ },+ {+ "date": "2021-10-04",+ "amount": -16,+ "category": "Fees and Other Withdrawals",+ "description": "Non-Chase ATM Fee-With"+ },+ {+ "date": "2021-10-04",+ "amount": -2,+ "category": "Fees and Other Withdrawals",+ "description": "Non-Chase ATM Fee-With"+ },+ {+ "date": "2021-10-05",+ "amount": -15,+ "category": "Fees and Other Withdrawals",+ "description": "Incoming Domestic Wire Fee"+ },+ {+ "date": "2021-10-08",+ "amount": -1000,+ "category": "Fees and Other Withdrawals",+ "description": "10/08 Withdrawal"+ },+ {+ "date": "2021-10-08",+ "amount": -15,+ "category": "Fees and Other Withdrawals",+ "description": "Incoming Domestic Wire Fee"+ },+ {+ "date": "2021-10-11",+ "amount": -1000,+ "category": "Fees and Other Withdrawals",+ "description": "10/11 Withdrawal"+ },+ {+ "date": "2021-10-12",+ "amount": -1000,+ "category": "Fees and Other Withdrawals",+ "description": "10/12 Withdrawal"+ },+ {+ "date": "2021-10-13",+ "amount": -8,+ "category": "Fees and Other Withdrawals",+ "description": "Non-Chase ATM Fee-With"+ },+ {+ "date": "2021-10-13",+ "amount": -4,+ "category": "Fees and Other Withdrawals",+ "description": "Non-Chase ATM Fee-With"+ },+ {+ "date": "2021-10-14",+ "amount": -2,+ "category": "Fees and Other Withdrawals",+ "description": "Non-Chase ATM Fee-With"+ },+ {+ "date": "2021-10-15",+ "amount": -15,+ "category": "Fees and Other Withdrawals",+ "description": "Incoming Domestic Wire Fee"+ },+ {+ "date": "2021-10-18",+ "amount": -500,+ "category": "Fees and Other Withdrawals",+ "description": "10/18 Withdrawal"+ },+ {+ "date": "2021-10-18",+ "amount": -700,+ "category": "Fees and Other Withdrawals",+ "description": "10/18 Withdrawal"+ },+ {+ "date": "2021-10-18",+ "amount": -1200,+ "category": "Fees and Other Withdrawals",+ "description": "10/18 Withdrawal"+ },+ {+ "date": "2021-10-18",+ "amount": -24,+ "category": "Fees and Other Withdrawals",+ "description": "Official Checks Charge"+ },+ {+ "date": "2021-10-18",+ "amount": -8,+ "category": "Fees and Other Withdrawals",+ "description": "Official Checks Charge"+ },+ {+ "date": "2021-10-21",+ "amount": -1500,+ "category": "Fees and Other Withdrawals",+ "description": "10/21 Withdrawal"+ },+ {+ "date": "2021-10-22",+ "amount": -15,+ "category": "Fees and Other Withdrawals",+ "description": "Incoming Domestic Wire Fee"+ },+ {+ "date": "2021-10-29",+ "amount": -15,+ "category": "Fees and Other Withdrawals",+ "description": "Incoming Domestic Wire Fee"+ }+ ],+ "ending_balance": 60015.89,+ "account_details": {+ "holder_name": "ELEGANT CABINETRY, INC",+ "account_type": "Chase BusinessSelect Checking",+ "account_last_four": "3986"+ },+ "statement_period": "October 01, 2021 through October 31, 2021",+ "overdraft_protection_enabled": null+}diff --git a/apps/v4/components/human-review-block-output.json b/apps/v4/components/human-review-block-output.jsonnew file mode 100644index 0000000..ec3b0ea--- /dev/null+++ b/apps/v4/components/human-review-block-output.json@@ -0,0 +1,2546 @@+{+ "value": {+ "transactions": [+ {+ "date": "2021-10-01",+ "amount": -20.91,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 09/28 U R* Magicjack 561-5 561-5942140 FL Card 6657"+ },+ {+ "date": "2021-10-01",+ "amount": -15.33,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 09/30 U R* M And R Sweet Candy Miami FL Card 6657"+ },+ {+ "date": "2021-10-01",+ "amount": -453.46,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/01 U R* Sprint *Wireles 800-639-611 VA Card 6657"+ },+ {+ "date": "2021-10-01",+ "amount": -19.58,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 09/31 U R* LA Baguette Miami FL Card 6657"+ },+ {+ "date": "2021-10-01",+ "amount": -303,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Non-Chase ATM Withdraw 10/01 *Bay Point Miami FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -97.5,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/01 U R* Hostgator Com 713-5745287 TX Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -6.31,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/01 U R* Burger King #33 Miami FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -19.78,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/01 Subway 00008995 Miami FL Card 7969"+ },+ {+ "date": "2021-10-04",+ "amount": -70.71,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/01 Publix #794 Miami Shores FL Card 7969"+ },+ {+ "date": "2021-10-04",+ "amount": -8.06,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/02 U R* Google*Goog3543 [email protected] CA Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -2.99,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/02 U R* 7-Eleven 10529 Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -14.32,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/02 U R* LA Baguette Miami FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -187.02,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/02 Kmart 04295 North Miami FL Card 7969"+ },+ {+ "date": "2021-10-04",+ "amount": -14.74,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/02 Burger King #3711 Miami Shores FL Card 7969"+ },+ {+ "date": "2021-10-04",+ "amount": -10.13,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/02 U R* Wendys #1713 Q Miami FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -88.1,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/03 Publix #794 Miami Shores FL Card 7969"+ },+ {+ "date": "2021-10-04",+ "amount": -22,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Non-Chase ATM Withdraw 10/04 9050 Biscayne Blvd Miami Shores FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -2000,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase With Pin 10/04 Buchwald Jewele/36 N.E Miami FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -202.5,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Non-Chase ATM Withdraw 10/04 36 NE 1 St Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -202.5,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Non-Chase ATM Withdraw 10/04 36 NE 1 St Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-04",+ "amount": -132.11,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Recurring Card Purchase 10/02 U R* 8X8, Inc. 888-8 888-8988733 CA Card 6657"+ },+ {+ "date": "2021-10-05",+ "amount": -9.81,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/03 Mcdonald's F11511 Miami FL Card 7969"+ },+ {+ "date": "2021-10-05",+ "amount": -31.68,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/03 U R* Latin Cafe Miami FL Card 6657"+ },+ {+ "date": "2021-10-05",+ "amount": -68.41,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/03 Toys R US #8709 N Miami Beach FL Card 7969"+ },+ {+ "date": "2021-10-05",+ "amount": -31.11,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/03 Cvspharmacy #4249 Q03 Miami FL Card 7969"+ },+ {+ "date": "2021-10-05",+ "amount": -16.96,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/04 U R* Steves Pizza North Miami FL Card 6657"+ },+ {+ "date": "2021-10-05",+ "amount": -265.05,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/04 U R* Paypal *Elsnert 402-935-773 CA Card 6657"+ },+ {+ "date": "2021-10-05",+ "amount": -6.61,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/04 Mcdonald's F11511 Miami FL Card 7969"+ },+ {+ "date": "2021-10-05",+ "amount": -26.93,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/04 U R* Cafe Nosh Miami FL Card 6657"+ },+ {+ "date": "2021-10-05",+ "amount": -127.56,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase With Pin 10/05 Costco Whse #0182 North Miami FL Card 6657"+ },+ {+ "date": "2021-10-05",+ "amount": -275,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase With Pin 10/05 Costco Whse #0182 North Miami FL Card 6657"+ },+ {+ "date": "2021-10-06",+ "amount": -419.01,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/04 U R* Padron Cigars 305-6432117 FL Card 6657"+ },+ {+ "date": "2021-10-06",+ "amount": -11.75,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/04 NETFLIX Inc#1224 Miami Shore FL Card 7969"+ },+ {+ "date": "2021-10-06",+ "amount": -26.48,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/04 Papa John's #0428 305-754-2666 FL Card 7969"+ },+ {+ "date": "2021-10-06",+ "amount": -18.87,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/05 U R* New York Bagel Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-06",+ "amount": -331.57,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/05 Bass Pro Shops Dania FL Card 7969"+ },+ {+ "date": "2021-10-07",+ "amount": -67.12,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/05 Hess 09565 N. Bay Villag FL Card 7969"+ },+ {+ "date": "2021-10-07",+ "amount": -16.1,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/05 Pollo Tropical #15 North Miami FL Card 7969"+ },+ {+ "date": "2021-10-07",+ "amount": -12.81,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/05 U R* Navarro Discount PHA Miami FL Card 6657"+ },+ {+ "date": "2021-10-07",+ "amount": -92.47,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/06 U R* Miami Beach Gol Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-07",+ "amount": -116.85,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/06 U R* Publix #794 Miami Shores FL Card 6657"+ },+ {+ "date": "2021-10-07",+ "amount": -564,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Recurring Card Purchase 10/06 U R* Kwon Jae-Hwa Ta 305-759-667 FL Card 6657"+ },+ {+ "date": "2021-10-08",+ "amount": -38.83,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/06 U R* Miami Beach Gol Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-08",+ "amount": -15.04,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/06 U R* Deco Drive Ciga Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-08",+ "amount": -34.3,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/07 U R* Los Ranchos Restaura Miami FL Card 6657"+ },+ {+ "date": "2021-10-08",+ "amount": -3,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/08 U R* Miami Beach Met Miami Beach FL Card 6657"+ },+ {+ "date": "2021-10-08",+ "amount": -5.16,+ "category": "ATM & DEBIT CARD WITHDRAWALS",+ "description": "Card Purchase 10/07 Sabor Tropical #4 Miami FL Card 7969"+ }+ ],+ "ending_balance": null,+ "account_details": {+ "holder_name": null,+ "account_type": null,+ "account_last_four": "3986"+ },+ "statement_period": "October 01, 2021 through October 31, 2021",+ "overdraft_protection_enabled": null+ },+ "metadata": {+ "transactions": {+ "citations": [],+ "ocrConfidence": 0.916,+ "logprobsConfidence": null+ },+ "ending_balance": {+ "citations": [],+ "logprobsConfidence": null+ },+ "account_details": {+ "citations": [],+ "ocrConfidence": 0.992,+ "logprobsConfidence": null+ },+ "transactions[0]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.7696,+ "y": 130.2048+ },+ {+ "x": 536.6952,+ "y": 130.2048+ },+ {+ "x": 536.6952,+ "y": 143.2512+ },+ {+ "x": 26.7696,+ "y": 143.2512+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/01 | Card Purchase 09/28 U R* Magicjack 561-5 561-5942140 FL Card 6657 | $20.91 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[1]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 143.2512+ },+ {+ "x": 536.6952,+ "y": 143.2512+ },+ {+ "x": 536.6952,+ "y": 156.2976+ },+ {+ "x": 26.1216,+ "y": 156.2976+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/01 | Card Purchase 09/30 U R* M And R Sweet Candy Miami FL Card 6657 | 15.33 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[2]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 156.2976+ },+ {+ "x": 536.6952,+ "y": 156.2976+ },+ {+ "x": 536.6952,+ "y": 169.9992+ },+ {+ "x": 26.1216,+ "y": 169.9992+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/01 | Card Purchase 10/01 U R* Sprint *Wireles 800-639-611 VA Card 6657 | 453.46 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[3]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 169.344+ },+ {+ "x": 536.6952,+ "y": 169.344+ },+ {+ "x": 536.6952,+ "y": 182.3904+ },+ {+ "x": 26.1216,+ "y": 182.3904+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/01 | Card Purchase 09/31 U R* LA Baguette Miami FL Card 6657 | 19.58 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[4]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 182.3904+ },+ {+ "x": 536.6952,+ "y": 182.3904+ },+ {+ "x": 536.6952,+ "y": 195.4368+ },+ {+ "x": 26.1216,+ "y": 195.4368+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/01 | Non-Chase ATM Withdraw 10/01 *Bay Point Miami FL Card 6657 | 303.00 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[5]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 195.4368+ },+ {+ "x": 536.6952,+ "y": 195.4368+ },+ {+ "x": 536.6952,+ "y": 208.49040000000002+ },+ {+ "x": 26.1216,+ "y": 208.49040000000002+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/04 | Card Purchase 10/01 U R* Hostgator Com 713-5745287 TX Card 6657 | 97.50 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[6]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 208.49040000000002+ },+ {+ "x": 536.6952,+ "y": 208.49040000000002+ },+ {+ "x": 536.6952,+ "y": 222.1848+ },+ {+ "x": 26.1216,+ "y": 222.1848+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/04 | Card Purchase 10/01 U R* Burger King #33 Miami FL Card 6657 | 6.31 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[7]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 222.1848+ },+ {+ "x": 536.6952,+ "y": 222.1848+ },+ {+ "x": 536.6952,+ "y": 235.23839999999998+ },+ {+ "x": 26.1216,+ "y": 235.23839999999998+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/04 | Card Purchase 10/01 Subway 00008995 Miami FL Card 7969 | 19.78 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[8]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 235.23839999999998+ },+ {+ "x": 536.6952,+ "y": 235.23839999999998+ },+ {+ "x": 536.6952,+ "y": 248.9328+ },+ {+ "x": 26.1216,+ "y": 248.9328+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/04 | Card Purchase 10/01 Publix #794 Miami Shores FL Card 7969 | 70.71 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[9]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 247.62959999999998+ },+ {+ "x": 536.6952,+ "y": 247.62959999999998+ },+ {+ "x": 536.6952,+ "y": 261.9864+ },+ {+ "x": 26.1216,+ "y": 261.9864+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/04 | Card Purchase 10/02 U R* Google*Goog3543 [email protected] CA Card 6657 | 8.06 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "statement_period": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 358.9632,+ "y": 46.497600000000006+ },+ {+ "x": 515.1816,+ "y": 46.5048+ },+ {+ "x": 515.1816,+ "y": 68.47919999999999+ },+ {+ "x": 358.956,+ "y": 68.4648+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "October 01, 2021 through October 31, 2021 Account Number: 000000710753986"+ }+ ],+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[10]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 261.9864+ },+ {+ "x": 536.6952,+ "y": 261.9864+ },+ {+ "x": 536.6952,+ "y": 275.0328+ },+ {+ "x": 26.1216,+ "y": 275.0328+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/04 | Card Purchase 10/02 U R* 7-Eleven 10529 Miami Beach FL Card 6657 | 2.99 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[11]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 275.0328+ },+ {+ "x": 536.6952,+ "y": 275.0328+ },+ {+ "x": 536.6952,+ "y": 288.0792+ },+ {+ "x": 26.1216,+ "y": 288.0792+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/04 | Card Purchase 10/02 U R* LA Baguette Miami FL Card 6657 | 14.32 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[12]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 288.0792+ },+ {+ "x": 536.6952,+ "y": 288.0792+ },+ {+ "x": 536.6952,+ "y": 301.12559999999996+ },+ {+ "x": 26.1216,+ "y": 301.12559999999996+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/04 | Card Purchase 10/02 Kmart 04295 North Miami FL Card 7969 | 187.02 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[13]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 300.4704+ },+ {+ "x": 536.6952,+ "y": 300.4704+ },+ {+ "x": 536.6952,+ "y": 314.8272+ },+ {+ "x": 26.1216,+ "y": 314.8272+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/04 | Card Purchase 10/02 Burger King #3711 Miami Shores FL Card 7969 | 14.74 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[14]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 314.8272+ },+ {+ "x": 536.6952,+ "y": 314.8272+ },+ {+ "x": 536.6952,+ "y": 327.8736+ },+ {+ "x": 26.1216,+ "y": 327.8736+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/04 | Card Purchase 10/02 U R* Wendys #1713 Q Miami FL Card 6657 | 10.13 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[15]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 327.8736+ },+ {+ "x": 536.6952,+ "y": 327.8736+ },+ {+ "x": 536.6952,+ "y": 340.92+ },+ {+ "x": 26.1216,+ "y": 340.92+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/04 | Card Purchase 10/03 Publix #794 Miami Shores FL Card 7969 | 88.10 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[16]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 340.92+ },+ {+ "x": 536.6952,+ "y": 340.92+ },+ {+ "x": 536.6952,+ "y": 353.9664+ },+ {+ "x": 26.1216,+ "y": 353.9664+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/04 | Non-Chase ATM Withdraw 10/04 9050 Biscayne Blvd Miami Shores FL Card 6657 | 22.00 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[17]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 353.9664+ },+ {+ "x": 536.6952,+ "y": 353.9664+ },+ {+ "x": 536.6952,+ "y": 367.66799999999995+ },+ {+ "x": 26.1216,+ "y": 367.66799999999995+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/04 | Card Purchase With Pin 10/04 Buchwald Jewele/36 N.E Miami FL Card 6657 | 2,000.00 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[18]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.122,+ "y": 367.668+ },+ {+ "x": 536.695,+ "y": 367.668+ },+ {+ "x": 536.695,+ "y": 380.714+ },+ {+ "x": 26.122,+ "y": 380.714+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "10/04 Non-Chase ATM Withdraw 10/04 36 NE 1 St Miami Beach FL Card 6657 202.50"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[19]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.122,+ "y": 367.668+ },+ {+ "x": 536.695,+ "y": 367.668+ },+ {+ "x": 536.695,+ "y": 380.714+ },+ {+ "x": 26.122,+ "y": 380.714+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "10/04 Non-Chase ATM Withdraw 10/04 36 NE 1 St Miami Beach FL Card 6657 202.50"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[20]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 393.76079999999996+ },+ {+ "x": 536.6952,+ "y": 393.76079999999996+ },+ {+ "x": 536.6952,+ "y": 406.8144+ },+ {+ "x": 26.1216,+ "y": 406.8144+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/04 | Recurring Card Purchase 10/02 U R* 8X8, Inc. 888-8 888-8988733 CA Card 6657 | 132.11 |"+ }+ ],+ "ocrConfidence": 0.916,+ "logprobsConfidence": null+ },+ "transactions[21]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 406.8144+ },+ {+ "x": 536.6952,+ "y": 406.8144+ },+ {+ "x": 536.6952,+ "y": 419.86080000000004+ },+ {+ "x": 26.1216,+ "y": 419.86080000000004+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/05 | Card Purchase 10/03 Mcdonald's F11511 Miami FL Card 7969 | 9.81 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[22]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 419.2056+ },+ {+ "x": 536.6952,+ "y": 419.2056+ },+ {+ "x": 536.6952,+ "y": 433.5624+ },+ {+ "x": 26.1216,+ "y": 433.5624+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/05 | Card Purchase 10/03 U R* Latin Cafe Miami FL Card 6657 | 31.68 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[23]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 433.5624+ },+ {+ "x": 536.6952,+ "y": 433.5624+ },+ {+ "x": 536.6952,+ "y": 446.6088+ },+ {+ "x": 26.1216,+ "y": 446.6088+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/05 | Card Purchase 10/03 Toys R US #8709 N Miami Beach FL Card 7969 | 68.41 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[24]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 446.6088+ },+ {+ "x": 536.6952,+ "y": 446.6088+ },+ {+ "x": 536.6952,+ "y": 459.65520000000004+ },+ {+ "x": 26.1216,+ "y": 459.65520000000004+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/05 | Card Purchase 10/03 Cvspharmacy #4249 Q03 Miami FL Card 7969 | 31.11 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[25]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 459.65520000000004+ },+ {+ "x": 536.6952,+ "y": 459.65520000000004+ },+ {+ "x": 536.6952,+ "y": 472.7016+ },+ {+ "x": 26.1216,+ "y": 472.7016+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/05 | Card Purchase | 10/04 U R* Steves Pizza North Miami FL Card 6657 | 16.96 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[26]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 472.7016+ },+ {+ "x": 536.6952,+ "y": 472.7016+ },+ {+ "x": 536.6952,+ "y": 486.4032+ },+ {+ "x": 26.1216,+ "y": 486.4032+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/05 | Card Purchase | 10/04 U R* Paypal *Elsnert 402-935-773 CA Card 6657 | 265.05 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[27]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 486.4032+ },+ {+ "x": 536.6952,+ "y": 486.4032+ },+ {+ "x": 536.6952,+ "y": 499.4496+ },+ {+ "x": 26.1216,+ "y": 499.4496+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/05 | Card Purchase 10/04 Mcdonald's F11511 Miami FL Card 7969 | 6.61 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[28]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 499.4496+ },+ {+ "x": 536.6952,+ "y": 499.4496+ },+ {+ "x": 536.6952,+ "y": 512.496+ },+ {+ "x": 26.1216,+ "y": 512.496+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/05 | Card Purchase 10/04 U R* Cafe Nosh Miami FL Card 6657 | 26.93 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[29]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 512.496+ },+ {+ "x": 536.6952,+ "y": 512.496+ },+ {+ "x": 536.6952,+ "y": 526.1976+ },+ {+ "x": 26.1216,+ "y": 526.1976+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/05 | Card Purchase With Pin 10/05 Costco Whse #0182 North Miami FL Card 6657 | 127.56 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[30]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 524.8944+ },+ {+ "x": 536.6952,+ "y": 524.8944+ },+ {+ "x": 536.6952,+ "y": 539.2439999999999+ },+ {+ "x": 26.1216,+ "y": 539.2439999999999+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/05 | Card Purchase With Pin 10/05 Costco Whse #0182 North Miami FL Card 6657 | 275.00 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[31]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 537.9408+ },+ {+ "x": 536.6952,+ "y": 537.9408+ },+ {+ "x": 536.6952,+ "y": 552.2904+ },+ {+ "x": 26.1216,+ "y": 552.2904+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/06 | Card Purchase 10/04 U R* Padron Cigars 305-6432117 FL Card 6657 | 419.01 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[32]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 552.2904+ },+ {+ "x": 536.6952,+ "y": 552.2904+ },+ {+ "x": 536.6952,+ "y": 565.344+ },+ {+ "x": 26.1216,+ "y": 565.344+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/06 | Card Purchase 10/04 NETFLIX Inc#1224 Miami Shore FL Card 7969 | 11.75 |"+ }+ ],+ "ocrConfidence": 0.963,+ "logprobsConfidence": null+ },+ "transactions[33]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 565.344+ },+ {+ "x": 536.6952,+ "y": 565.344+ },+ {+ "x": 536.6952,+ "y": 578.3904+ },+ {+ "x": 26.1216,+ "y": 578.3904+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/06 | Card Purchase | 10/04 Papa John's #0428 305-754-2666 FL Card 7969 | 26.48 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[34]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 578.3904+ },+ {+ "x": 536.6952,+ "y": 578.3904+ },+ {+ "x": 536.6952,+ "y": 592.0848+ },+ {+ "x": 26.1216,+ "y": 592.0848+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/06 | Card Purchase 10/05 U R* New York Bagel Miami Beach FL Card 6657 | 18.87 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[35]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 592.0848+ },+ {+ "x": 536.6952,+ "y": 592.0848+ },+ {+ "x": 536.6952,+ "y": 605.1384+ },+ {+ "x": 26.1216,+ "y": 605.1384+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/06 | Card Purchase 10/05 Bass Pro Shops Dania FL Card 7969 | 331.57 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[36]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 605.1384+ },+ {+ "x": 536.6952,+ "y": 605.1384+ },+ {+ "x": 536.6952,+ "y": 618.8328+ },+ {+ "x": 26.1216,+ "y": 618.8328+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/07 | Card Purchase 10/05 Hess 09565 N. Bay Villag FL Card 7969 | 67.12 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[37]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 617.5296000000001+ },+ {+ "x": 536.6952,+ "y": 617.5296000000001+ },+ {+ "x": 536.6952,+ "y": 631.2312+ },+ {+ "x": 26.1216,+ "y": 631.2312+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/07 | Card Purchase 10/05 Pollo Tropical #15 North Miami FL Card 7969 | 16.10 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[38]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 631.2312+ },+ {+ "x": 536.6952,+ "y": 631.2312+ },+ {+ "x": 536.6952,+ "y": 644.9328+ },+ {+ "x": 26.1216,+ "y": 644.9328+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/07 | Card Purchase 10/05 U R* Navarro Discount PHA Miami FL Card 6657 | 12.81 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[39]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 644.2776+ },+ {+ "x": 536.6952,+ "y": 644.2776+ },+ {+ "x": 536.6952,+ "y": 657.3240000000001+ },+ {+ "x": 26.1216,+ "y": 657.3240000000001+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/07 | Card Purchase 10/06 U R* Miami Beach Gol Miami Beach FL Card 6657 | 92.47 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[40]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 26.1216,+ "y": 657.3240000000001+ },+ {+ "x": 536.6952,+ "y": 657.3240000000001+ },+ {+ "x": 536.6952,+ "y": 671.0256+ },+ {+ "x": 26.1216,+ "y": 671.0256+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/07 | Card Purchase 10/06 U R* Publix #794 Miami Shores FL Card 6657 | 116.85 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[41]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 25.4664,+ "y": 671.0256+ },+ {+ "x": 536.6952,+ "y": 671.0256+ },+ {+ "x": 536.6952,+ "y": 684.7271999999999+ },+ {+ "x": 25.4664,+ "y": 684.7271999999999+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/07 | Recurring Card Purchase 10/06 U R* Kwon Jae-Hwa Ta 305-759-667 FL Card 6657 | 564.00 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[42]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 25.4664,+ "y": 683.4240000000001+ },+ {+ "x": 536.6952,+ "y": 683.4240000000001+ },+ {+ "x": 536.6952,+ "y": 697.1184+ },+ {+ "x": 25.4664,+ "y": 697.1184+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/08 | Card Purchase 10/06 U R* Miami Beach Gol Miami Beach FL Card 6657 | 38.83 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[43]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 25.4664,+ "y": 697.1184+ },+ {+ "x": 536.6952,+ "y": 697.1184+ },+ {+ "x": 536.6952,+ "y": 710.82+ },+ {+ "x": 25.4664,+ "y": 710.82+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/08 | Card Purchase 10/06 U R* Deco Drive Ciga Miami Beach FL Card 6657 | 15.04 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[44]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 25.4664,+ "y": 710.172+ },+ {+ "x": 536.6952,+ "y": 710.172+ },+ {+ "x": 536.6952,+ "y": 723.8663999999999+ },+ {+ "x": 25.4664,+ "y": 723.8663999999999+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/08 | Card Purchase | 10/07 U R* Los Ranchos Restaura Miami FL Card 6657 | 34.30 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[45]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 25.4664,+ "y": 723.8663999999999+ },+ {+ "x": 536.6952,+ "y": 723.8663999999999+ },+ {+ "x": 536.6952,+ "y": 736.92+ },+ {+ "x": 25.4664,+ "y": 736.92+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/08 | Card Purchase | 10/08 U R* Miami Beach Met Miami Beach FL Card 6657 | 3.00 |"+ }+ ],+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[46]": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 25.4664,+ "y": 736.92+ },+ {+ "x": 536.6952,+ "y": 736.92+ },+ {+ "x": 536.6952,+ "y": 749.9664+ },+ {+ "x": 25.4664,+ "y": 749.9664+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "| 10/08 | Card Purchase | 10/07 Sabor Tropical #4 Miami FL Card 7969 | 5.16 |"+ }+ ],+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[0].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[1].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[2].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[3].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[4].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[5].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[6].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[7].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[8].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[9].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[10].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[11].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[12].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[13].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[14].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[15].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[16].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[17].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[18].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[19].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[20].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[21].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[22].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[23].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[24].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[25].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[26].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[27].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[28].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[29].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[30].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[31].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[32].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[33].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[34].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[35].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[36].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[37].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[38].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[39].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[40].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[41].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[42].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[43].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[44].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[45].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[46].date": {+ "ocrConfidence": 0.99,+ "logprobsConfidence": null+ },+ "transactions[0].amount": {+ "ocrConfidence": 0.995,+ "logprobsConfidence": null+ },+ "transactions[1].amount": {+ "ocrConfidence": 0.992,+ "logprobsConfidence": null+ },+ "transactions[2].amount": {+ "ocrConfidence": 0.998,+ "logprobsConfidence": null+ },+ "transactions[3].amount": {+ "ocrConfidence": 0.996,+ "logprobsConfidence": null+ },+ "transactions[4].amount": {+ "ocrConfidence": 0.987,+ "logprobsConfidence": null+ },+ "transactions[5].amount": {+ "ocrConfidence": 0.997,+ "logprobsConfidence": null+ },+ "transactions[6].amount": {+ "ocrConfidence": 0.992,+ "logprobsConfidence": null+ },+ "transactions[7].amount": {+ "ocrConfidence": 0.995,+ "logprobsConfidence": null+ },+ "transactions[8].amount": {+ "ocrConfidence": 0.997,+ "logprobsConfidence": null+ },+ "transactions[9].amount": {+ "ocrConfidence": 0.992,+ "logprobsConfidence": null+ },+ "transactions[10].amount": {+ "ocrConfidence": 0.986,+ "logprobsConfidence": null+ },+ "transactions[11].amount": {+ "ocrConfidence": 0.995,+ "logprobsConfidence": null+ },+ "transactions[12].amount": {+ "ocrConfidence": 0.998,+ "logprobsConfidence": null+ },+ "transactions[13].amount": {+ "ocrConfidence": 0.998,+ "logprobsConfidence": null+ },+ "transactions[14].amount": {+ "ocrConfidence": 0.998,+ "logprobsConfidence": null+ },+ "transactions[15].amount": {+ "ocrConfidence": 0.998,+ "logprobsConfidence": null+ },+ "transactions[16].amount": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[17].amount": {+ "ocrConfidence": 0.998,+ "logprobsConfidence": null+ },+ "transactions[18].amount": {+ "ocrConfidence": 0.995,+ "logprobsConfidence": null+ },+ "transactions[19].amount": {+ "ocrConfidence": 0.995,+ "logprobsConfidence": null+ },+ "transactions[20].amount": {+ "ocrConfidence": 0.997,+ "logprobsConfidence": null+ },+ "transactions[21].amount": {+ "ocrConfidence": 0.992,+ "logprobsConfidence": null+ },+ "transactions[22].amount": {+ "ocrConfidence": 0.998,+ "logprobsConfidence": null+ },+ "transactions[23].amount": {+ "ocrConfidence": 0.997,+ "logprobsConfidence": null+ },+ "transactions[24].amount": {+ "ocrConfidence": 0.996,+ "logprobsConfidence": null+ },+ "transactions[25].amount": {+ "ocrConfidence": 0.998,+ "logprobsConfidence": null+ },+ "transactions[26].amount": {+ "ocrConfidence": 0.997,+ "logprobsConfidence": null+ },+ "transactions[27].amount": {+ "ocrConfidence": 0.992,+ "logprobsConfidence": null+ },+ "transactions[28].amount": {+ "ocrConfidence": 0.998,+ "logprobsConfidence": null+ },+ "transactions[29].amount": {+ "ocrConfidence": 0.998,+ "logprobsConfidence": null+ },+ "transactions[30].amount": {+ "ocrConfidence": 0.992,+ "logprobsConfidence": null+ },+ "transactions[31].amount": {+ "ocrConfidence": 0.997,+ "logprobsConfidence": null+ },+ "transactions[32].amount": {+ "ocrConfidence": 0.997,+ "logprobsConfidence": null+ },+ "transactions[33].amount": {+ "ocrConfidence": 0.997,+ "logprobsConfidence": null+ },+ "transactions[34].amount": {+ "ocrConfidence": 0.998,+ "logprobsConfidence": null+ },+ "transactions[35].amount": {+ "ocrConfidence": 0.995,+ "logprobsConfidence": null+ },+ "transactions[36].amount": {+ "ocrConfidence": 0.995,+ "logprobsConfidence": null+ },+ "transactions[37].amount": {+ "ocrConfidence": 0.998,+ "logprobsConfidence": null+ },+ "transactions[38].amount": {+ "ocrConfidence": 0.996,+ "logprobsConfidence": null+ },+ "transactions[39].amount": {+ "ocrConfidence": 0.997,+ "logprobsConfidence": null+ },+ "transactions[40].amount": {+ "ocrConfidence": 0.998,+ "logprobsConfidence": null+ },+ "transactions[41].amount": {+ "ocrConfidence": 0.977,+ "logprobsConfidence": null+ },+ "transactions[42].amount": {+ "ocrConfidence": 0.995,+ "logprobsConfidence": null+ },+ "transactions[43].amount": {+ "ocrConfidence": 0.998,+ "logprobsConfidence": null+ },+ "transactions[44].amount": {+ "ocrConfidence": 0.998,+ "logprobsConfidence": null+ },+ "transactions[45].amount": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[46].amount": {+ "ocrConfidence": 0.983,+ "logprobsConfidence": null+ },+ "transactions[0].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[1].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[2].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[3].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[4].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[5].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[6].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[7].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[8].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[9].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[10].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[11].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[12].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[13].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[14].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[15].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[16].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[17].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[18].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[19].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[20].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[21].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[22].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[23].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[24].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[25].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[26].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[27].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[28].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[29].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[30].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[31].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[32].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[33].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[34].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[35].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[36].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[37].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[38].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[39].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[40].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[41].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[42].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[43].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[44].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[45].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "transactions[46].category": {+ "ocrConfidence": 0.989,+ "logprobsConfidence": null+ },+ "account_details.holder_name": {+ "citations": [],+ "logprobsConfidence": null+ },+ "transactions[0].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[1].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[2].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[3].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[4].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[5].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[6].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[7].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[8].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[9].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "account_details.account_type": {+ "citations": [],+ "logprobsConfidence": null+ },+ "overdraft_protection_enabled": {+ "citations": [],+ "logprobsConfidence": null+ },+ "transactions[10].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[11].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[12].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[13].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[14].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[15].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[16].description": {+ "ocrConfidence": 0.948,+ "logprobsConfidence": null+ },+ "transactions[17].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[18].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[19].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[20].description": {+ "ocrConfidence": 0.916,+ "logprobsConfidence": null+ },+ "transactions[21].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[22].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[23].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[24].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[25].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[26].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[27].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[28].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[29].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[30].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[31].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[32].description": {+ "ocrConfidence": 0.963,+ "logprobsConfidence": null+ },+ "transactions[33].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[34].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[35].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[36].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[37].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "transactions[38].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[39].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[40].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[41].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[42].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[43].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[44].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[45].description": {+ "ocrConfidence": 0.932,+ "logprobsConfidence": null+ },+ "transactions[46].description": {+ "ocrConfidence": 0.971,+ "logprobsConfidence": null+ },+ "account_details.account_last_four": {+ "citations": [+ {+ "page": 1,+ "polygon": [+ {+ "x": 358.963,+ "y": 46.498+ },+ {+ "x": 515.182,+ "y": 46.505+ },+ {+ "x": 515.182,+ "y": 68.479+ },+ {+ "x": 358.956,+ "y": 68.465+ }+ ],+ "pageWidth": 612,+ "pageHeight": 792,+ "referenceText": "October 01, 2021 through October 31, 2021 Account Number: 000000710753986"+ }+ ],+ "ocrConfidence": 0.992,+ "logprobsConfidence": null+ }+ }+}\ No newline at end of filediff --git a/apps/v4/components/human-review-docs.tsx b/apps/v4/components/human-review-docs.tsxindex d7e6090..19b87e0 100644--- a/apps/v4/components/human-review-docs.tsx+++ b/apps/v4/components/human-review-docs.tsx@@ -5,9 +5,11 @@ import {DataEditor,emptyGridSelection,GridCellKind,+ TextCellEntry,type EditableGridCell,type GridCell,type GridColumn,+ type GridMouseEventArgs,type GridSelection,type Item,type NumberCell,@@ -53,6 +55,8 @@ import {TooltipTrigger,} from "@/registry/new-york-v4/ui/tooltip"+import blockReviewOutput from "./human-review-block-output.json"+import "@glideapps/glide-data-grid/dist/index.css"type JsonPrimitive = string | number | boolean | null@@ -81,10 +85,8 @@ type ReviewFieldDefinition = {schema: ReviewFieldSchemaactual: JsonValueexpected: JsonValue- location?: {- page: number- area: HighlightArea- }+ location?: ReviewLocation+ metadataPath?: string}type HighlightArea = {@@ -94,7 +96,49 @@ type HighlightArea = {height: number}+type ReviewLocation = {+ page: number+ area: HighlightArea+}++type HumanReviewBlockTransaction = {+ date: string+ amount: number+ category: string+ description: string+}++type HumanReviewBlockOutput = {+ transactions: HumanReviewBlockTransaction[]+ ending_balance: number | null+ account_details: {+ holder_name: string | null+ account_type: string | null+ account_last_four: string | null+ }+ statement_period: string+ overdraft_protection_enabled: boolean | null+}++type HumanReviewBlockCitation = {+ page: number+ polygon?: Array<{ x: number; y: number }>+ pageWidth: number+ pageHeight: number+ referenceText?: string+}++type HumanReviewBlockMetadataEntry = {+ citations?: HumanReviewBlockCitation[]+}++type HumanReviewBlockRawOutput = {+ value: HumanReviewBlockOutput+ metadata: Record<string, HumanReviewBlockMetadataEntry>+}+const PDF_URL = "/samples/attention.pdf"+const BLOCK_REVIEW_PDF_URL = "/samples/bank-statement-x4uhhi7t.pdf"const DEFAULT_ZOOM = 0.75const REVIEW_HIGHLIGHT_STYLE ="border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_10%)]"@@ -221,110 +265,73 @@ function useHumanReviewGridTheme() {const REVIEW_SCHEMA: ReviewFieldDefinition[] = [{- key: "vendor_name",+ key: "statement_period",schema: {type: "string",- title: "Vendor name",- description: "Supplier shown on the invoice header.",+ title: "Statement period",+ description: "Date range covered by the bank statement.",},- actual: "Acme Supplies LLC",- expected: "Acme Supply LLC",+ actual: "Jan 1-31, 2026",+ expected: "January 1-31, 2026",location: {page: 1,area: { left: 31, top: 30, width: 40, height: 5.8 },},},{- key: "line_items",+ key: "transactions",schema: {type: "array",- title: "Line items",- description: "Invoice rows with nested allocation details.",+ title: "Transactions",+ description: "Posted account activity during the statement period.",items: {type: "object",properties: {+ date: {+ type: "string",+ title: "Date",+ },description: {type: "string",title: "Description",},- quantity: {- type: "number",- title: "Qty",- },- unit_price: {+ amount: {type: "number",- title: "Unit price",+ title: "Amount",},- tax_detail: {- type: "object",- title: "Tax detail",- properties: {- code: {- type: "string",- title: "Code",- },- jurisdiction: {- type: "string",- title: "Jurisdiction",- },- },- },- allocations: {- type: "array",- title: "Allocations",- items: {- type: "object",- properties: {- department: {- type: "string",- title: "Department",- },- percent: {- type: "number",- title: "Percent",- },- },- },+ category: {+ type: "string",+ title: "Category",},},},},actual: [{- description: "Transformer implementation support",- quantity: 2,- unit_price: 4200,- tax_detail: { code: "TX-CA", jurisdiction: "CA" },- allocations: [- { department: "Research", percent: 70 },- { department: "Platform", percent: 20 },- ],+ date: "2026-01-03",+ description: "ACH CREDIT PAYROLL",+ amount: 4250,+ category: "Deposit",},{- description: "Attention model review",- quantity: 1,- unit_price: 4080,- tax_detail: { code: "TX-NY", jurisdiction: "NY" },- allocations: [{ department: "Research", percent: 100 }],+ date: "2026-01-12",+ description: "POS PURCHASE GROCERY MART",+ amount: -86.42,+ category: "Debit",},],expected: [{- description: "Transformer implementation support",- quantity: 2,- unit_price: 4200,- tax_detail: { code: "TX-CA", jurisdiction: "CA" },- allocations: [- { department: "Research", percent: 70 },- { department: "Platform", percent: 30 },- ],+ date: "2026-01-03",+ description: "ACH CREDIT PAYROLL",+ amount: 4250,+ category: "Deposit",},{- description: "Attention model review",- quantity: 1,- unit_price: 4080.75,- tax_detail: { code: "TX-NY", jurisdiction: "NY" },- allocations: [{ department: "Research", percent: 100 }],+ date: "2026-01-12",+ description: "POS PURCHASE GROCERY MART",+ amount: -68.42,+ category: "Debit",},],location: {@@ -333,39 +340,25 @@ const REVIEW_SCHEMA: ReviewFieldDefinition[] = [},},{- key: "total_amount",+ key: "ending_balance",schema: {type: "number",- title: "Total amount",- description: "Final amount due including tax.",+ title: "Ending balance",+ description: "Final account balance at the end of the statement period.",},- actual: 12480,- expected: 12480.75,+ actual: 12840.18,+ expected: 12858.18,location: {page: 1,area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },},},{- key: "payment_terms",- schema: {- type: "string",- title: "Payment terms",- enum: ["Due on receipt", "Net 15", "Net 30"],- },- actual: "Net 15",- expected: "Net 30",- location: {- page: 1,- area: { left: 13.5, top: 55.5, width: 73.5, height: 7.5 },- },- },- {- key: "requires_review",+ key: "overdraft_protection_enabled",schema: {type: "boolean",- title: "Requires review",- description: "Whether a human should verify this document before export.",+ title: "Overdraft protection enabled",+ description: "Whether overdraft protection is enabled for the account.",},actual: false,expected: true,@@ -375,51 +368,327 @@ const REVIEW_SCHEMA: ReviewFieldDefinition[] = [},},{- key: "remittance",+ key: "account_details",schema: {type: "object",- title: "Remittance details",- description: "Payment destination used for invoice reconciliation.",+ title: "Account details",+ description: "Account owner and identifying details from the statement.",properties: {- account_holder: {+ holder_name: {type: "string",- title: "Account holder",+ title: "Holder name",},- routing_number: {+ account_last_four: {type: "string",- title: "Routing number",+ title: "Account last four",},- verified: {- type: "boolean",- title: "Verified",+ account_type: {+ type: "string",+ title: "Account type",},},},actual: {- account_holder: "Acme Supplies LLC",- routing_number: "021000021",- verified: false,+ holder_name: "Jordan Lee",+ account_last_four: "4821",+ account_type: "Checking",},expected: {- account_holder: "Acme Supply LLC",- routing_number: "021000021",- verified: true,+ holder_name: "Jordan Lee",+ account_last_four: "4821",+ account_type: "Premier Checking",},},]-const INITIAL_EXPECTED_VALUES = REVIEW_SCHEMA.reduce<JsonObject>(- (values, field) => {+const BLOCK_REVIEW_OUTPUT = blockReviewOutput as HumanReviewBlockRawOutput+const BLOCK_REVIEW_EXPECTED_OUTPUT = BLOCK_REVIEW_OUTPUT.value+const BLOCK_REVIEW_METADATA = BLOCK_REVIEW_OUTPUT.metadata+const BLOCK_REVIEW_FIRST_INCLUDED_SOURCE_PAGE = 1+const BLOCK_REVIEW_LAST_INCLUDED_SOURCE_PAGE = 1++function getBlockReviewPdfPage(sourcePage: number) {+ if (+ sourcePage < BLOCK_REVIEW_FIRST_INCLUDED_SOURCE_PAGE ||+ sourcePage > BLOCK_REVIEW_LAST_INCLUDED_SOURCE_PAGE+ ) {+ return undefined+ }++ return sourcePage - BLOCK_REVIEW_FIRST_INCLUDED_SOURCE_PAGE + 1+}++function getCitationLocation(+ citation: HumanReviewBlockCitation+): ReviewLocation | undefined {+ const polygon = citation.polygon+ if (!polygon?.length || !citation.pageWidth || !citation.pageHeight) {+ return undefined+ }++ const xs = polygon.map((point) => point.x)+ const ys = polygon.map((point) => point.y)+ const left = Math.min(...xs)+ const top = Math.min(...ys)+ const right = Math.max(...xs)+ const bottom = Math.max(...ys)++ return {+ page: citation.page,+ area: {+ left: (left / citation.pageWidth) * 100,+ top: (top / citation.pageHeight) * 100,+ width: ((right - left) / citation.pageWidth) * 100,+ height: ((bottom - top) / citation.pageHeight) * 100,+ },+ }+}++function normalizeCitationSearchText(value: unknown) {+ return String(value ?? "")+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, " ")+ .trim()+}++function getTransactionDateSearchText(value: unknown) {+ if (typeof value !== "string") return null++ const match = value.match(/^(\d{4})-(\d{2})-(\d{2})$/)+ return match ? `${match[2]} ${match[3]}` : normalizeCitationSearchText(value)+}++function getNumberSearchTexts(value: unknown) {+ if (typeof value !== "number") return []++ const absoluteValue = Math.abs(value)++ return [+ absoluteValue.toString(),+ absoluteValue.toFixed(2),+ absoluteValue.toLocaleString("en-US", {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ }),+ ].map(normalizeCitationSearchText)+}++function citationMatchesTransaction(+ citation: HumanReviewBlockCitation | undefined,+ transaction: JsonValue+) {+ if (!citation?.referenceText || !isJsonObject(transaction)) return false++ const referenceText = normalizeCitationSearchText(citation.referenceText)+ const dateText = getTransactionDateSearchText(transaction.date)+ const descriptionText = normalizeCitationSearchText(transaction.description)+ .split(" ")+ .slice(0, 4)+ .join(" ")+ const amountTexts = getNumberSearchTexts(transaction.amount)++ return (+ Boolean(dateText && referenceText.includes(dateText)) &&+ Boolean(descriptionText && referenceText.includes(descriptionText)) &&+ amountTexts.some((amountText) => referenceText.includes(amountText))+ )+}++function resolveBlockReviewArrayItemMetadataPath(+ metadataPath: string,+ rowIndex: number,+ rowValue: JsonValue+) {+ if (metadataPath !== "transactions") return `${metadataPath}[${rowIndex}]`++ const rowMetadataPath = `${metadataPath}[${rowIndex}]`+ const rowCitation = BLOCK_REVIEW_METADATA[rowMetadataPath]?.citations?.find(+ (candidate) => candidate.polygon?.length+ )++ if (citationMatchesTransaction(rowCitation, rowValue)) {+ return rowMetadataPath+ }++ const matchedEntry = Object.entries(BLOCK_REVIEW_METADATA).find(+ ([candidatePath, entry]) =>+ candidatePath.startsWith(`${metadataPath}[`) &&+ !candidatePath.includes(".") &&+ citationMatchesTransaction(+ entry.citations?.find((candidate) => candidate.polygon?.length),+ rowValue+ )+ )++ return matchedEntry?.[0]+}++function getBlockReviewLocation(metadataPath: string | undefined) {+ if (!metadataPath) return undefined++ const citation = BLOCK_REVIEW_METADATA[metadataPath]?.citations?.find(+ (candidate) => candidate.polygon?.length+ )+ const localPage = citation ? getBlockReviewPdfPage(citation.page) : undefined++ if (!citation || localPage === undefined) return undefined++ const location = getCitationLocation(citation)++ return location ? { ...location, page: localPage } : undefined+}++function getReviewFieldLocation(+ field: ReviewFieldDefinition | undefined,+ resolveLocation?: (metadataPath: string) => ReviewLocation | undefined+) {+ if (!field) return undefined++ return (+ field.location ??+ resolveLocation?.(field.metadataPath ?? field.key) ??+ undefined+ )+}++function getReviewLocationKey(location: ReviewLocation | undefined) {+ if (!location) return null++ const { area } = location+ return [location.page, area.left, area.top, area.width, area.height].join(":")+}++const BLOCK_REVIEW_ACTUAL_OUTPUT = {+ ...BLOCK_REVIEW_EXPECTED_OUTPUT,+ transactions: BLOCK_REVIEW_EXPECTED_OUTPUT.transactions.map(+ (transaction, index) => {+ if (index === 0) {+ return {+ ...transaction,+ category: "Card Activity",+ }+ }++ if (index === 15) {+ return {+ ...transaction,+ category: "Retail Spend",+ }+ }++ if (index === 28) {+ return {+ ...transaction,+ category: "Food & Dining",+ }+ }++ return transaction+ }+ ),+ account_details: {+ ...BLOCK_REVIEW_EXPECTED_OUTPUT.account_details,+ account_type: "Chase Business Checking",+ },+ statement_period: "Oct 01-31, 2021",+ overdraft_protection_enabled: false,+} satisfies HumanReviewBlockOutput++const BLOCK_REVIEW_SCHEMA: ReviewFieldDefinition[] = [+ {+ key: "transactions",+ schema: {+ type: "array",+ title: "Transactions",+ description: "Posted account activity during the statement period.",+ items: {+ type: "object",+ properties: {+ date: {+ type: "string",+ title: "Date",+ },+ description: {+ type: "string",+ title: "Description",+ },+ amount: {+ type: "number",+ title: "Amount",+ },+ category: {+ type: "string",+ title: "Category",+ },+ },+ },+ },+ actual: BLOCK_REVIEW_ACTUAL_OUTPUT.transactions,+ expected: BLOCK_REVIEW_EXPECTED_OUTPUT.transactions,+ metadataPath: "transactions",+ },+ {+ key: "account_details",+ schema: {+ type: "object",+ title: "Account details",+ description: "Account owner and identifying details from the statement.",+ properties: {+ holder_name: {+ type: "string",+ title: "Holder name",+ },+ account_type: {+ type: "string",+ title: "Account type",+ },+ account_last_four: {+ type: "string",+ title: "Account last four",+ },+ },+ },+ actual: BLOCK_REVIEW_ACTUAL_OUTPUT.account_details,+ expected: BLOCK_REVIEW_EXPECTED_OUTPUT.account_details,+ metadataPath: "account_details",+ },+ {+ key: "statement_period",+ schema: {+ type: "string",+ title: "Statement period",+ description: "Date range covered by the bank statement.",+ },+ actual: BLOCK_REVIEW_ACTUAL_OUTPUT.statement_period,+ expected: BLOCK_REVIEW_EXPECTED_OUTPUT.statement_period,+ metadataPath: "statement_period",+ },+ {+ key: "overdraft_protection_enabled",+ schema: {+ type: "boolean",+ title: "Overdraft protection enabled",+ description: "Whether overdraft protection is enabled for the account.",+ },+ actual: BLOCK_REVIEW_ACTUAL_OUTPUT.overdraft_protection_enabled,+ expected: BLOCK_REVIEW_EXPECTED_OUTPUT.overdraft_protection_enabled,+ metadataPath: "overdraft_protection_enabled",+ },+]++function getExpectedValues(fields: ReviewFieldDefinition[]) {+ return fields.reduce<JsonObject>((values, field) => {values[field.key] = field.expectedreturn values- },- {}-)+ }, {})+}-const ACTUAL_VALUES = REVIEW_SCHEMA.reduce<JsonObject>((values, field) => {- values[field.key] = field.actual- return values-}, {})+function getActualValues(fields: ReviewFieldDefinition[]) {+ return fields.reduce<JsonObject>((values, field) => {+ values[field.key] = field.actual+ return values+ }, {})+}function formatJson(value: unknown) {return JSON.stringify(value, null, 2)@@ -482,6 +751,7 @@ function countReviewFields(fields: ReviewFieldDefinition[]): number {schema,actual: getObjectValue(field.actual, key),expected: getObjectValue(field.expected, key),+ metadataPath: `${field.metadataPath ?? field.key}.${key}`,}))@@ -505,6 +775,7 @@ function findReviewField(schema,actual: getObjectValue(field.actual, key),expected: getObjectValue(field.expected, key),+ metadataPath: `${field.metadataPath ?? field.key}.${key}`,}))const childField = findReviewField(childFields, fieldKey)@@ -608,9 +879,9 @@ function HumanReviewTextOverlayEditor({validatedSelection,value,}: HumanReviewTextOverlayEditorProps) {- const inputRef = React.useRef<HTMLTextAreaElement | null>(null)const initialValue =value.kind === GridCellKind.Number ? value.displayData : value.data+ const [entryValue, setEntryValue] = React.useState(initialValue)const latestValueRef = React.useRef(initialValue)const finishedRef = React.useRef(false)@@ -655,24 +926,16 @@ function HumanReviewTextOverlayEditor({[onFinishedEditing, overlayOpenRef, readOnly, value])- React.useEffect(() => {- overlayOpenRef.current = true-- const input = inputRef.current- if (!input) {- return () => {- overlayOpenRef.current = false- }- }-- const handleInput = (event: Event) => {+ const handleEntryChange = React.useCallback(+ (event: React.ChangeEvent<HTMLTextAreaElement>) => {event.stopPropagation()- latestValueRef.current = input.value- }- const stopTextInputPropagation = (event: Event) => {- event.stopPropagation()- }- const handleKeyDown = (event: KeyboardEvent) => {+ latestValueRef.current = event.target.value+ setEntryValue(event.target.value)+ },+ []+ )+ const handleKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLTextAreaElement>) => {event.stopPropagation()if (event.key === "Escape") {@@ -691,43 +954,21 @@ function HumanReviewTextOverlayEditor({event.preventDefault()finishEditing(true, [0, 1])}- }+ },+ [finishEditing]+ )- input.addEventListener("input", handleInput)- input.addEventListener("beforeinput", stopTextInputPropagation, true)- input.addEventListener("keydown", handleKeyDown, true)-- input.focus()-- if (validatedSelection !== undefined) {- const selectionRange =- typeof validatedSelection === "number"- ? [validatedSelection, validatedSelection]- : validatedSelection- input.setSelectionRange(selectionRange[0], selectionRange[1])- } else if (isHighlighted) {- input.setSelectionRange(0, input.value.length)- } else {- input.setSelectionRange(input.value.length, input.value.length)- }+ React.useEffect(() => {+ overlayOpenRef.current = truereturn () => {- input.removeEventListener("input", handleInput)- input.removeEventListener("beforeinput", stopTextInputPropagation, true)- input.removeEventListener("keydown", handleKeyDown, true)overlayOpenRef.current = false}- }, [- finishEditing,- isHighlighted,- overlayOpenRef,- validatedSelection,- readOnly,- ])+ }, [overlayOpenRef])React.useEffect(() => {const handlePointerOutside = (event: PointerEvent | MouseEvent) => {- const input = inputRef.current+ const input = document.querySelector<HTMLTextAreaElement>(".gdg-input")const overlayRoot = input?.closest(".gdg-clip-region")if (!overlayRoot || overlayRoot.contains(event.target as Node | null)) {@@ -747,14 +988,15 @@ function HumanReviewTextOverlayEditor({}, [finishEditing])return (- <textarea- ref={inputRef}- className="gdg-input"- defaultValue={initialValue}- readOnly={readOnly}- aria-readonly={readOnly}- dir="auto"- style={{ height: "100%", minHeight: 32, resize: "none", width: "100%" }}+ <TextCellEntry+ autoFocus={!readOnly}+ disabled={readOnly}+ highlight={isHighlighted}+ value={entryValue}+ validatedSelection={validatedSelection}+ altNewline+ onChange={handleEntryChange}+ onKeyDown={handleKeyDown}/>)}@@ -1022,6 +1264,7 @@ function HumanReviewArrayValueGrid({activeNestedSide = null,activeSelectionSide = null,label,+ metadataPath,nestedStackBaseDepth = 0,readOnly = false,schema,@@ -1032,7 +1275,10 @@ function HumanReviewArrayValueGrid({viewSide = "expected",onChange,onGridSelectionChange,+ onLocationHover,onNestedStackChange,+ resolveLocation,+ resolveArrayItemMetadataPath,}: {activeNestedSide?: ArrayReviewSide | nullactiveSelectionSide?: ArrayReviewSide | null@@ -1051,10 +1297,18 @@ function HumanReviewArrayValueGrid({side: ArrayReviewSide,depth: number) => void+ onLocationHover?: (location?: ReviewLocation) => voidonNestedStackChange?: (stack: ArrayNestedView[],side: ArrayReviewSide) => void+ resolveLocation?: (metadataPath: string) => ReviewLocation | undefined+ resolveArrayItemMetadataPath?: (+ metadataPath: string,+ rowIndex: number,+ rowValue: JsonValue+ ) => string | undefined+ metadataPath?: string}) {const rows = getArrayValue(value)const itemSchema = getArrayItemSchema(schema)@@ -1222,7 +1476,7 @@ function HumanReviewArrayValueGrid({allowOverlay: false,readonly: true,cursor: "pointer",- activationBehaviorOverride: "second-click",+ activationBehaviorOverride: "double-click",themeOverride: {textDark: blueCellText,...(nestedCellTheme ?? {}),@@ -1246,7 +1500,6 @@ function HumanReviewArrayValueGrid({displayData: typeof cellValue === "number" ? String(cellValue) : "",allowOverlay: true,readonly: false,- activationBehaviorOverride: readOnly ? "single-click" : undefined,}}@@ -1266,7 +1519,6 @@ function HumanReviewArrayValueGrid({: String(cellValue),allowOverlay: true,readonly: false,- activationBehaviorOverride: readOnly ? "single-click" : undefined,}},[@@ -1341,6 +1593,52 @@ function HumanReviewArrayValueGrid({() => !fastTextOverlayOpenRef.current,[])+ const handleItemHovered = React.useCallback(+ (args: GridMouseEventArgs) => {+ if (!onLocationHover || !resolveLocation || !metadataPath) return++ if (args.kind !== "cell") {+ onLocationHover(undefined)+ return+ }++ const [col, row] = args.location+ const column = columns[col]+ const rowValue = rows[row]+ if (!column || rowValue === undefined) {+ onLocationHover(undefined)+ return+ }++ const columnId = String(column.id ?? "value")+ const rowMetadataPath = resolveArrayItemMetadataPath+ ? resolveArrayItemMetadataPath(metadataPath, row, rowValue)+ : `${metadataPath}[${row}]`+ if (!rowMetadataPath) {+ onLocationHover(undefined)+ return+ }++ const propertyMetadataPath =+ itemSchema.type === "object"+ ? `${rowMetadataPath}.${columnId}`+ : rowMetadataPath++ onLocationHover(+ resolveLocation(propertyMetadataPath) ??+ resolveLocation(rowMetadataPath)+ )+ },+ [+ columns,+ itemSchema.type,+ metadataPath,+ onLocationHover,+ resolveArrayItemMetadataPath,+ resolveLocation,+ rows,+ ]+ )const openNestedCell = React.useCallback(([col, row]: Item) => {@@ -1408,6 +1706,7 @@ function HumanReviewArrayValueGrid({return (<div+ onMouseLeave={() => onLocationHover?.(undefined)}className={cn("relative overflow-hidden rounded-md border bg-background transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:shadow-[0_0_0_1px_rgb(59_130_246_/_8%)] hover:border-blue-500/50",isActiveNestedSource &&@@ -1425,14 +1724,13 @@ function HumanReviewArrayValueGrid({columns={columns}rows={rows.length}getCellContent={getCellContent}- cellActivationBehavior={- readOnly ? "single-click" : "second-click"- }+ cellActivationBehavior="double-click"gridSelection={localGridSelection}highlightRegions={mirroredHighlightRegions}onCellEdited={updateCellValue}onCellActivated={openNestedCell}onGridSelectionChange={handleGridSelectionChange}+ onItemHovered={handleItemHovered}provideEditor={provideEditor}isOutsideClick={handleOutsideClick}rowMarkers="number"@@ -1492,6 +1790,8 @@ function HumanReviewArrayValueGrid({onChange={updateNestedValue}onGridSelectionChange={onGridSelectionChange}onNestedStackChange={onNestedStackChange}+ resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}+ resolveLocation={resolveLocation}/>) : (<HumanReviewObjectValueEditor@@ -1578,8 +1878,15 @@ type HumanReviewFieldCardProps = {readOnly?: booleanonChange: (value: JsonValue) => voidonFieldFocus?: (field: ReviewFieldDefinition) => void+ onLocationHover?: (location?: ReviewLocation) => voidonUndo: () => voidonSetNull: () => void+ resolveArrayItemMetadataPath?: (+ metadataPath: string,+ rowIndex: number,+ rowValue: JsonValue+ ) => string | undefined+ resolveLocation?: (metadataPath: string) => ReviewLocation | undefined}function areHumanReviewFieldCardPropsEqual(@@ -1593,7 +1900,11 @@ function areHumanReviewFieldCardPropsEqual(previous.active === next.active &&previous.activeFieldKey === next.activeFieldKey &&previous.readOnly === next.readOnly &&- previous.onFieldFocus === next.onFieldFocus+ previous.onFieldFocus === next.onFieldFocus &&+ previous.onLocationHover === next.onLocationHover &&+ previous.resolveArrayItemMetadataPath ===+ next.resolveArrayItemMetadataPath &&+ previous.resolveLocation === next.resolveLocation)}@@ -1611,8 +1922,11 @@ function HumanReviewFieldCardBase({readOnly = false,onChange,onFieldFocus,+ onLocationHover,onUndo,onSetNull,+ resolveArrayItemMetadataPath,+ resolveLocation,}: HumanReviewFieldCardProps) {const modified = !jsonValuesEqual(value, originalValue)const Icon = getFieldIcon(field.schema.type)@@ -1655,12 +1969,17 @@ function HumanReviewFieldCardBase({},[])+ const focusAndHoverField = React.useCallback(() => {+ onFieldFocus?.(field)+ onLocationHover?.(getReviewFieldLocation(field, resolveLocation))+ }, [field, onFieldFocus, onLocationHover, resolveLocation])return (<divtabIndex={0}- onFocusCapture={() => onFieldFocus?.(field)}- onMouseEnter={() => onFieldFocus?.(field)}+ onFocusCapture={focusAndHoverField}+ onMouseEnter={focusAndHoverField}+ onMouseLeave={() => onLocationHover?.(undefined)}className={cn("rounded-lg border bg-background p-3 transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:bg-blue-500/5 hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",active &&@@ -1743,6 +2062,7 @@ function HumanReviewFieldCardBase({schema,actual: getObjectValue(field.actual, propertyKey),expected: getObjectValue(originalValue, propertyKey),+ metadataPath: `${field.metadataPath ?? field.key}.${propertyKey}`,}return (@@ -1758,6 +2078,7 @@ function HumanReviewFieldCardBase({onChange(setObjectValue(value, propertyKey, childValue))}onFieldFocus={onFieldFocus}+ onLocationHover={onLocationHover}onUndo={() =>onChange(setObjectValue(value, propertyKey, childField.expected)@@ -1766,6 +2087,8 @@ function HumanReviewFieldCardBase({onSetNull={() =>onChange(setObjectValue(value, propertyKey, null))}+ resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}+ resolveLocation={resolveLocation}/>)})@@ -1782,7 +2105,10 @@ function HumanReviewFieldCardBase({activeNestedSide={syncedArrayNestedView.activeSide}activeSelectionSide={syncedArraySelection.activeSide}label="Actual"+ metadataPath={field.metadataPath ?? field.key}readOnly+ resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}+ resolveLocation={resolveLocation}schema={field.schema}selectionDepth={syncedArraySelection.depth}sharedGridSelection={syncedArraySelection.gridSelection}@@ -1790,13 +2116,17 @@ function HumanReviewFieldCardBase({value={field.actual}viewSide="actual"onGridSelectionChange={updateSyncedArraySelection}+ onLocationHover={onLocationHover}onNestedStackChange={updateSyncedArrayNestedView}/><HumanReviewArrayValueGridactiveNestedSide={syncedArrayNestedView.activeSide}activeSelectionSide={syncedArraySelection.activeSide}label="Expected"+ metadataPath={field.metadataPath ?? field.key}readOnly={readOnly}+ resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}+ resolveLocation={resolveLocation}schema={field.schema}selectionDepth={syncedArraySelection.depth}sharedGridSelection={syncedArraySelection.gridSelection}@@ -1805,6 +2135,7 @@ function HumanReviewFieldCardBase({viewSide="expected"onChange={onChange}onGridSelectionChange={updateSyncedArraySelection}+ onLocationHover={onLocationHover}onNestedStackChange={updateSyncedArrayNestedView}/></div>@@ -1835,15 +2166,13 @@ function HumanReviewFieldCardBase({)}-function HumanReviewHighlight({ field }: { field: ReviewFieldDefinition }) {- const area = field.location?.area-- if (!area) return null+function HumanReviewHighlight({ location }: { location: ReviewLocation }) {+ const area = location.areareturn (<divclassName={cn(- "pointer-events-none absolute z-10 rounded-[3px] border",+ "pointer-events-none absolute z-10 border",REVIEW_HIGHLIGHT_STYLE)}style={{@@ -1913,25 +2242,46 @@ function JsonDiffView({function HumanReviewPanel({activeFieldKey,className,+ fields = REVIEW_SCHEMA,onFieldFocus,+ onLocationHover,+ resolveArrayItemMetadataPath,+ resolveLocation,theme = "light",}: {activeFieldKey?: stringclassName?: string+ fields?: ReviewFieldDefinition[]onFieldFocus?: (field: ReviewFieldDefinition) => void+ onLocationHover?: (location?: ReviewLocation) => void+ resolveArrayItemMetadataPath?: (+ metadataPath: string,+ rowIndex: number,+ rowValue: JsonValue+ ) => string | undefined+ resolveLocation?: (metadataPath: string) => ReviewLocation | undefinedtheme?: HumanReviewTheme} = {}) {const [activeTab, setActiveTab] = React.useState("form")+ const actualValues = React.useMemo(() => getActualValues(fields), [fields])+ const initialExpectedValues = React.useMemo(+ () => getExpectedValues(fields),+ [fields]+ )const [expected, setExpected] = React.useState<JsonObject>(- INITIAL_EXPECTED_VALUES+ initialExpectedValues)+ React.useEffect(() => {+ setExpected(initialExpectedValues)+ }, [initialExpectedValues])+const updateValue = React.useCallback((key: string, value: JsonValue) => {setExpected((current) =>Object.is(current[key], value) ? current : { ...current, [key]: value })}, [])- const fieldCount = React.useMemo(() => countReviewFields(REVIEW_SCHEMA), [])+ const fieldCount = React.useMemo(() => countReviewFields(fields), [fields])return (<TooltipProvider delay={200}>@@ -1959,7 +2309,7 @@ function HumanReviewPanel({<TabsContent value="form" keepMounted className="min-h-0 flex-1"><ScrollArea className="h-full" scrollFade><div className="space-y-3 p-3">- {REVIEW_SCHEMA.map((field) => (+ {fields.map((field) => (<HumanReviewFieldCardkey={field.key}field={field}@@ -1972,8 +2322,11 @@ function HumanReviewPanel({activeFieldKey={activeFieldKey}onChange={(value) => updateValue(field.key, value)}onFieldFocus={onFieldFocus}+ onLocationHover={onLocationHover}onUndo={() => updateValue(field.key, field.expected)}onSetNull={() => updateValue(field.key, null)}+ resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}+ resolveLocation={resolveLocation}/>))}</div>@@ -1981,7 +2334,7 @@ function HumanReviewPanel({</TabsContent><TabsContent value="json" keepMounted className="min-h-0 flex-1"><JsonDiffView- actual={ACTUAL_VALUES}+ actual={actualValues}expected={expected}theme={theme}/>@@ -1993,12 +2346,15 @@ function HumanReviewPanel({export function HumanReviewBlock() {const { resolvedTheme } = useTheme()- const [activeFieldKey, setActiveFieldKey] = React.useState(- REVIEW_SCHEMA[0].key- )+ const fields = BLOCK_REVIEW_SCHEMA+ const [activeFieldKey, setActiveFieldKey] = React.useState(fields[0].key)+ const [hoverLocation, setHoverLocation] =+ React.useState<ReviewLocation | null>(null)const viewerRef = React.useRef<PDFViewerHandle>(null)- const activeField =- findReviewField(REVIEW_SCHEMA, activeFieldKey) ?? REVIEW_SCHEMA[0]+ const hoverLocationKeyRef = React.useRef<string | null>(null)+ const activeField = findReviewField(fields, activeFieldKey) ?? fields[0]+ const activeLocation =+ hoverLocation ?? getReviewFieldLocation(activeField, getBlockReviewLocation)const reviewTheme: HumanReviewTheme =resolvedTheme === "dark" ? "dark" : "light"@@ -2008,15 +2364,28 @@ export function HumanReviewBlock() {setActiveFieldKey(field.key)- if (field.location) {- viewerRef.current?.scrollToPageArea(- field.location.page,- field.location.area- )+ const location = getReviewFieldLocation(field, getBlockReviewLocation)+ if (location) {+ viewerRef.current?.scrollToPageArea(location.page, location.area)}},[activeFieldKey])+ const handleLocationHover = React.useCallback((location?: ReviewLocation) => {+ setHoverLocation(location ?? null)++ const locationKey = getReviewLocationKey(location)+ if (!location) {+ hoverLocationKeyRef.current = null+ return+ }+ if (locationKey === hoverLocationKeyRef.current) return++ hoverLocationKeyRef.current = locationKey+ viewerRef.current?.scrollToPageArea(location.page, location.area, {+ behavior: "auto",+ })+ }, [])return (<PdfBlockResizableShell@@ -2024,11 +2393,11 @@ export function HumanReviewBlock() {left={<PDFViewerref={viewerRef}- file={PDF_URL}+ file={BLOCK_REVIEW_PDF_URL}defaultZoom={DEFAULT_ZOOM}renderPageOverlay={({ pageNumber }) =>- activeField.location?.page === pageNumber ? (- <HumanReviewHighlight field={activeField} />+ activeLocation?.page === pageNumber ? (+ <HumanReviewHighlight location={activeLocation} />) : null}/>@@ -2037,8 +2406,12 @@ export function HumanReviewBlock() {<HumanReviewPanelactiveFieldKey={activeField.key}className="h-full min-h-0"+ fields={fields}theme={reviewTheme}onFieldFocus={focusField}+ onLocationHover={handleLocationHover}+ resolveArrayItemMetadataPath={resolveBlockReviewArrayItemMetadataPath}+ resolveLocation={getBlockReviewLocation}/>}/>@@ -2109,127 +2482,97 @@ import { HumanReviewPanel, type ReviewField } from "@/components/ui/human-reviewconst fields: ReviewField[] = [{- key: "vendor_name",- schema: {- type: "string",- title: "Vendor name",- description: "Supplier shown on the invoice header.",- },- actual: "Acme Supplies LLC",- expected: "Acme Supply LLC",- },- {- key: "total_amount",- schema: {- type: "number",- title: "Total amount",- description: "Final amount due including tax.",- },- actual: 12480,- expected: 12480.75,- },- {- key: "payment_terms",+ key: "statement_period",schema: {type: "string",- title: "Payment terms",- enum: ["Due on receipt", "Net 15", "Net 30"],+ title: "Statement period",+ description: "Date range covered by the bank statement.",},- actual: "Net 15",- expected: "Net 30",+ actual: "Jan 1-31, 2026",+ expected: "January 1-31, 2026",},{- key: "line_items",+ key: "transactions",schema: {type: "array",- title: "Line items",+ title: "Transactions",items: {type: "object",properties: {+ date: { type: "string", title: "Date" },description: { type: "string", title: "Description" },- quantity: { type: "number", title: "Qty" },- unit_price: { type: "number", title: "Unit price" },- tax_detail: {- type: "object",- title: "Tax detail",- properties: {- code: { type: "string", title: "Code" },- jurisdiction: { type: "string", title: "Jurisdiction" },- },- },- allocations: {- type: "array",- title: "Allocations",- items: {- type: "object",- properties: {- department: { type: "string", title: "Department" },- percent: { type: "number", title: "Percent" },- },- },- },+ amount: { type: "number", title: "Amount" },+ category: { type: "string", title: "Category" },},},},actual: [{- description: "Transformer implementation support",- quantity: 2,- unit_price: 4200,- tax_detail: { code: "TX-CA", jurisdiction: "CA" },- allocations: [{ department: "Platform", percent: 20 }],+ date: "2026-01-12",+ description: "POS PURCHASE GROCERY MART",+ amount: -86.42,+ category: "Debit",},],expected: [{- description: "Transformer implementation support",- quantity: 2,- unit_price: 4200,- tax_detail: { code: "TX-CA", jurisdiction: "CA" },- allocations: [{ department: "Platform", percent: 30 }],+ date: "2026-01-12",+ description: "POS PURCHASE GROCERY MART",+ amount: -68.42,+ category: "Debit",},],},{- key: "requires_review",+ key: "ending_balance",+ schema: {+ type: "number",+ title: "Ending balance",+ description: "Final account balance at the end of the statement period.",+ },+ actual: 12840.18,+ expected: 12858.18,+ },+ {+ key: "overdraft_protection_enabled",schema: {type: "boolean",- title: "Requires review",- description: "Whether a human should verify this document before export.",+ title: "Overdraft protection enabled",+ description: "Whether overdraft protection is enabled for the account.",},actual: false,expected: true,},{- key: "remittance",+ key: "account_details",schema: {type: "object",- title: "Remittance details",- description: "Payment destination used for invoice reconciliation.",+ title: "Account details",+ description: "Account owner and identifying details from the statement.",properties: {- account_holder: {+ holder_name: {type: "string",- title: "Account holder",+ title: "Holder name",},- routing_number: {+ account_last_four: {type: "string",- title: "Routing number",+ title: "Account last four",},- verified: {- type: "boolean",- title: "Verified",+ account_type: {+ type: "string",+ title: "Account type",},},},actual: {- account_holder: "Acme Supplies LLC",- routing_number: "021000021",- verified: false,+ holder_name: "Jordan Lee",+ account_last_four: "4821",+ account_type: "Checking",},expected: {- account_holder: "Acme Supply LLC",- routing_number: "021000021",- verified: true,+ holder_name: "Jordan Lee",+ account_last_four: "4821",+ account_type: "Premier Checking",},},];@@ -2250,7 +2593,8 @@ export function HumanReviewExample() {}`const humanReviewSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n DataEditor,\n emptyGridSelection,\n GridCellKind,\n type EditableGridCell,\n type GridCell,\n type GridColumn,\n type GridSelection,\n type Item,\n type NumberCell,\n type ProvideEditorComponent,\n type Rectangle,\n type TextCell,\n type Theme,\n} from "@glideapps/glide-data-grid"\nimport {\n ArrowLeft01Icon,\n CancelCircleIcon,\n FileDiffIcon,\n InputNumericIcon,\n InputTextIcon,\n SecondBracketIcon,\n SourceCodeSquareIcon,\n TextCheckIcon,\n Undo02Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { MultiFileDiff, Virtualizer } from "@pierre/diffs/react"\nimport { flushSync } from "react-dom"\n\nimport { cn } from "@/lib/utils"\nimport { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"\nimport { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"\nimport { Button } from "@/registry/new-york-v4/ui/button"\nimport { Input } from "@/registry/new-york-v4/ui/input"\nimport { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"\nimport {\n Tabs,\n TabsContent,\n TabsList,\n TabsTrigger,\n} from "@/registry/new-york-v4/ui/tabs"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nimport "@glideapps/glide-data-grid/dist/index.css"\n\nexport type JsonPrimitive = string | number | boolean | null\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray\nexport type JsonObject = { [key: string]: JsonValue }\nexport type JsonArray = JsonValue[]\nexport type SchemaPropertyType =\n | "string"\n | "number"\n | "integer"\n | "boolean"\n | "object"\n | "array"\n\nexport type ReviewFieldSchema = {\n type: SchemaPropertyType\n title?: string\n description?: string\n enum?: Array<string | number>\n properties?: Record<string, ReviewFieldSchema>\n items?: ReviewFieldSchema\n}\n\nexport type HighlightArea = {\n left: number\n top: number\n width: number\n height: number\n}\n\nexport type ReviewField = {\n key: string\n schema: ReviewFieldSchema\n actual: JsonValue\n expected: JsonValue\n location?: {\n page: number\n area: HighlightArea\n }\n}\n\nconst DEFAULT_ZOOM = 0.75\nconst REVIEW_HIGHLIGHT_STYLE =\n "border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_10%)]"\nconst DIFF_VIEWER_THEME = {\n "--diffs-light-bg": "oklch(0.985 0.002 247)",\n "--diffs-dark-bg": "oklch(0.18 0.003 247)",\n "--diffs-light": "oklch(0.22 0.01 247)",\n "--diffs-dark": "oklch(0.92 0.006 247)",\n "--diffs-bg-context-override":\n "light-dark(oklch(0.967 0.003 247), oklch(0.235 0.004 247))",\n "--diffs-bg-context-gutter-override":\n "light-dark(oklch(0.948 0.004 247), oklch(0.205 0.004 247))",\n "--diffs-bg-separator-override":\n "light-dark(oklch(0.94 0.004 247), oklch(0.255 0.005 247))",\n "--diffs-bg-buffer-override":\n "light-dark(oklch(0.955 0.004 247), oklch(0.225 0.004 247))",\n "--diffs-light-addition-color": "oklch(0.54 0.13 158)",\n "--diffs-dark-addition-color": "oklch(0.72 0.13 158)",\n "--diffs-light-deletion-color": "oklch(0.55 0.16 28)",\n "--diffs-dark-deletion-color": "oklch(0.72 0.14 28)",\n "--diffs-bg-addition-override":\n "light-dark(oklch(0.957 0.032 158), oklch(0.255 0.052 158))",\n "--diffs-bg-addition-emphasis-override":\n "light-dark(oklch(0.88 0.06 158), oklch(0.36 0.08 158))",\n "--diffs-bg-deletion-override":\n "light-dark(oklch(0.958 0.03 28), oklch(0.255 0.047 28))",\n "--diffs-bg-deletion-emphasis-override":\n "light-dark(oklch(0.9 0.052 28), oklch(0.36 0.075 28))",\n "--diffs-fg-number-override":\n "light-dark(oklch(0.56 0.018 247), oklch(0.66 0.012 247))",\n "--diffs-font-size": "12px",\n "--diffs-line-height": "20px",\n} as React.CSSProperties\n\nfunction readIsDarkTheme() {\n return (\n typeof document !== "undefined" &&\n document.documentElement.classList.contains("dark")\n )\n}\n\n// A single shared MutationObserver backs every consumer. Each grid previously\n// created its own observer (two, via useHumanReviewGridTheme), so opening a\n// nested array view spun up and tore down several observers at once.\nconst darkThemeListeners = new Set<(isDark: boolean) => void>()\nlet darkThemeObserver: MutationObserver | null = null\nlet sharedIsDarkTheme = false\n\nfunction ensureDarkThemeObserver() {\n if (\n darkThemeObserver ||\n typeof document === "undefined" ||\n typeof MutationObserver === "undefined"\n ) {\n return\n }\n\n sharedIsDarkTheme = readIsDarkTheme()\n darkThemeObserver = new MutationObserver(() => {\n const nextIsDark = readIsDarkTheme()\n if (nextIsDark === sharedIsDarkTheme) return\n\n sharedIsDarkTheme = nextIsDark\n darkThemeListeners.forEach((listener) => listener(nextIsDark))\n })\n darkThemeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ["class"],\n })\n}\n\nfunction useIsDarkTheme() {\n const [isDark, setIsDark] = React.useState(readIsDarkTheme)\n\n React.useEffect(() => {\n ensureDarkThemeObserver()\n setIsDark(sharedIsDarkTheme)\n darkThemeListeners.add(setIsDark)\n\n return () => {\n darkThemeListeners.delete(setIsDark)\n if (darkThemeListeners.size === 0 && darkThemeObserver) {\n darkThemeObserver.disconnect()\n darkThemeObserver = null\n }\n }\n }, [])\n\n return isDark\n}\n\nfunction useHumanReviewGridTheme() {\n const isDark = useIsDarkTheme()\n\n return React.useMemo<Partial<Theme>>(\n () => ({\n accentColor: isDark ? "rgb(96, 165, 250)" : "rgb(37, 99, 235)",\n accentLight: isDark ? "rgba(29, 78, 216, 0.15)" : "rgb(219, 234, 254)",\n accentFg: "rgb(255, 255, 255)",\n textDark: isDark ? "rgb(229, 229, 229)" : "rgb(23, 23, 23)",\n textMedium: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n textLight: isDark ? "rgb(115, 115, 115)" : "rgb(163, 163, 163)",\n textBubble: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n textHeader: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n textGroupHeader: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n bgCell: isDark ? "rgb(10, 10, 10)" : "rgb(255, 255, 255)",\n bgCellMedium: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n bgHeader: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n bgHeaderHasFocus: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n bgHeaderHovered: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n borderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n horizontalBorderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n cellHorizontalPadding: 8,\n cellVerticalPadding: 3,\n headerIconSize: 18,\n baseFontStyle: "13px",\n headerFontStyle: "600 13px",\n markerFontStyle: "11px",\n fontFamily: \'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif\',\n editorFontSize: "13px",\n }),\n [isDark]\n )\n}\n\nconst REVIEW_FIELDS: ReviewField[] = [\n {\n key: "vendor_name",\n schema: {\n type: "string",\n title: "Vendor name",\n description: "Supplier shown on the invoice header.",\n },\n actual: "Acme Supplies LLC",\n expected: "Acme Supply LLC",\n location: {\n page: 1,\n area: { left: 31, top: 30, width: 40, height: 5.8 },\n },\n },\n {\n key: "line_items",\n schema: {\n type: "array",\n title: "Line items",\n description: "Invoice rows with nested allocation details.",\n items: {\n type: "object",\n properties: {\n description: {\n type: "string",\n title: "Description",\n },\n quantity: {\n type: "number",\n title: "Qty",\n },\n unit_price: {\n type: "number",\n title: "Unit price",\n },\n tax_detail: {\n type: "object",\n title: "Tax detail",\n properties: {\n code: {\n type: "string",\n title: "Code",\n },\n jurisdiction: {\n type: "string",\n title: "Jurisdiction",\n },\n },\n },\n allocations: {\n type: "array",\n title: "Allocations",\n items: {\n type: "object",\n properties: {\n department: {\n type: "string",\n title: "Department",\n },\n percent: {\n type: "number",\n title: "Percent",\n },\n },\n },\n },\n },\n },\n },\n actual: [\n {\n description: "Transformer implementation support",\n quantity: 2,\n unit_price: 4200,\n tax_detail: { code: "TX-CA", jurisdiction: "CA" },\n allocations: [\n { department: "Research", percent: 70 },\n { department: "Platform", percent: 20 },\n ],\n },\n {\n description: "Attention model review",\n quantity: 1,\n unit_price: 4080,\n tax_detail: { code: "TX-NY", jurisdiction: "NY" },\n allocations: [{ department: "Research", percent: 100 }],\n },\n ],\n expected: [\n {\n description: "Transformer implementation support",\n quantity: 2,\n unit_price: 4200,\n tax_detail: { code: "TX-CA", jurisdiction: "CA" },\n allocations: [\n { department: "Research", percent: 70 },\n { department: "Platform", percent: 30 },\n ],\n },\n {\n description: "Attention model review",\n quantity: 1,\n unit_price: 4080.75,\n tax_detail: { code: "TX-NY", jurisdiction: "NY" },\n allocations: [{ department: "Research", percent: 100 }],\n },\n ],\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "total_amount",\n schema: {\n type: "number",\n title: "Total amount",\n description: "Final amount due including tax.",\n },\n actual: 12480,\n expected: 12480.75,\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "payment_terms",\n schema: {\n type: "string",\n title: "Payment terms",\n enum: ["Due on receipt", "Net 15", "Net 30"],\n },\n actual: "Net 15",\n expected: "Net 30",\n location: {\n page: 1,\n area: { left: 13.5, top: 55.5, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "requires_review",\n schema: {\n type: "boolean",\n title: "Requires review",\n description: "Whether a human should verify this document before export.",\n },\n actual: false,\n expected: true,\n location: {\n page: 2,\n area: { left: 9.5, top: 12, width: 81, height: 11.5 },\n },\n },\n {\n key: "remittance",\n schema: {\n type: "object",\n title: "Remittance details",\n description: "Payment destination used for invoice reconciliation.",\n properties: {\n account_holder: {\n type: "string",\n title: "Account holder",\n },\n routing_number: {\n type: "string",\n title: "Routing number",\n },\n verified: {\n type: "boolean",\n title: "Verified",\n },\n },\n },\n actual: {\n account_holder: "Acme Supplies LLC",\n routing_number: "021000021",\n verified: false,\n },\n expected: {\n account_holder: "Acme Supply LLC",\n routing_number: "021000021",\n verified: true,\n },\n },\n]\n\nfunction valuesFromFields(\n fields: ReviewField[],\n valueKey: "actual" | "expected"\n) {\n return fields.reduce<JsonObject>((values, field) => {\n values[field.key] = field[valueKey]\n return values\n }, {})\n}\n\nfunction formatJson(value: unknown) {\n return JSON.stringify(value, null, 2)\n}\n\nfunction isJsonObject(value: JsonValue): value is JsonObject {\n return typeof value === "object" && value !== null && !Array.isArray(value)\n}\n\nfunction isJsonArray(value: JsonValue): value is JsonArray {\n return Array.isArray(value)\n}\n\nfunction getObjectValue(value: JsonValue, key: string): JsonValue {\n if (!isJsonObject(value)) return null\n return value[key] ?? null\n}\n\nfunction setObjectValue(\n value: JsonValue,\n key: string,\n childValue: JsonValue\n): JsonObject {\n return {\n ...(isJsonObject(value) ? value : {}),\n [key]: childValue,\n }\n}\n\nfunction getArrayValue(value: JsonValue): JsonArray {\n return isJsonArray(value) ? value : []\n}\n\nfunction setArrayItemValue(\n value: JsonValue,\n index: number,\n childValue: JsonValue\n): JsonArray {\n const nextValue = getArrayValue(value).slice()\n nextValue[index] = childValue\n return nextValue\n}\n\nfunction getPrimitiveValue(value: JsonValue): JsonPrimitive {\n return isJsonObject(value) || isJsonArray(value) ? null : value\n}\n\nfunction jsonValuesEqual(left: JsonValue, right: JsonValue) {\n return formatJson(left) === formatJson(right)\n}\n\nfunction countReviewFields(fields: ReviewField[]): number {\n return fields.reduce((count, field) => {\n if (field.schema.type !== "object") return count + 1\n\n const properties = field.schema.properties ?? {}\n const childFields = Object.entries(properties).map(\n ([key, schema]): ReviewField => ({\n key: `${field.key}.${key}`,\n schema,\n actual: getObjectValue(field.actual, key),\n expected: getObjectValue(field.expected, key),\n })\n )\n\n return count + Math.max(countReviewFields(childFields), 1)\n }, 0)\n}\n\nfunction findReviewField(\n fields: ReviewField[],\n fieldKey: string | undefined\n): ReviewField | undefined {\n if (!fieldKey) return undefined\n\n for (const field of fields) {\n if (field.key === fieldKey) return field\n\n if (field.schema.type === "object") {\n const childFields = Object.entries(field.schema.properties ?? {}).map(\n ([key, schema]): ReviewField => ({\n key: `${field.key}.${key}`,\n schema,\n actual: getObjectValue(field.actual, key),\n expected: getObjectValue(field.expected, key),\n })\n )\n const childField = findReviewField(childFields, fieldKey)\n if (childField) return childField\n }\n }\n\n return undefined\n}\n\nfunction formatValue(value: JsonValue) {\n if (value === null) return "NULL"\n if (isJsonObject(value) || isJsonArray(value)) return formatJson(value)\n if (typeof value === "boolean") return value ? "true" : "false"\n return String(value)\n}\n\nfunction areGridRangesEqual(\n left: Readonly<Rectangle> | undefined,\n right: Readonly<Rectangle> | undefined\n) {\n return (\n left === right ||\n (left !== undefined &&\n right !== undefined &&\n left.x === right.x &&\n left.y === right.y &&\n left.width === right.width &&\n left.height === right.height)\n )\n}\n\nfunction areGridRangeStacksEqual(\n left: readonly Readonly<Rectangle>[] | undefined,\n right: readonly Readonly<Rectangle>[] | undefined\n) {\n if (left === right) return true\n if (!left || !right || left.length !== right.length) return false\n\n return left.every((range, index) => areGridRangesEqual(range, right[index]))\n}\n\nfunction areGridSelectionsEqual(left: GridSelection, right: GridSelection) {\n const leftCurrent = left.current\n const rightCurrent = right.current\n\n return (\n leftCurrent?.cell[0] === rightCurrent?.cell[0] &&\n leftCurrent?.cell[1] === rightCurrent?.cell[1] &&\n areGridRangesEqual(leftCurrent?.range, rightCurrent?.range) &&\n areGridRangeStacksEqual(\n leftCurrent?.rangeStack,\n rightCurrent?.rangeStack\n ) &&\n left.columns.equals(right.columns) &&\n left.rows.equals(right.rows)\n )\n}\n\nfunction getGridSelectionRanges(selection: GridSelection | undefined) {\n const current = selection?.current\n if (!current) return []\n\n return [...(current.rangeStack ?? []), current.range]\n}\n\nfunction areArrayNestedViewsEqual(\n left: ArrayNestedView[],\n right: ArrayNestedView[]\n) {\n if (left === right) return true\n if (left.length !== right.length) return false\n\n return left.every((view, index) => {\n const other = right[index]\n\n return (\n view.rowIndex === other?.rowIndex &&\n view.columnId === other.columnId &&\n view.title === other.title &&\n view.schema === other.schema &&\n Object.is(view.value, other.value)\n )\n })\n}\n\ntype HumanReviewOverlayCell = TextCell | NumberCell\n\ntype HumanReviewTextOverlayEditorProps = React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n> & {\n overlayOpenRef: React.RefObject<boolean>\n readOnly?: boolean\n}\n\nfunction HumanReviewTextOverlayEditor({\n isHighlighted,\n onFinishedEditing,\n overlayOpenRef,\n readOnly = false,\n validatedSelection,\n value,\n}: HumanReviewTextOverlayEditorProps) {\n const inputRef = React.useRef<HTMLTextAreaElement | null>(null)\n const initialValue =\n value.kind === GridCellKind.Number ? value.displayData : value.data\n const latestValueRef = React.useRef(initialValue)\n const finishedRef = React.useRef(false)\n\n const finishEditing = React.useCallback(\n (\n shouldSave: boolean,\n movement: readonly [-1 | 0 | 1, -1 | 0 | 1] = [0, 0]\n ) => {\n if (finishedRef.current) return\n\n finishedRef.current = true\n overlayOpenRef.current = false\n\n if (!shouldSave || readOnly) {\n onFinishedEditing(undefined, movement)\n return\n }\n\n if (value.kind === GridCellKind.Number) {\n const numericValue = Number(latestValueRef.current)\n\n onFinishedEditing(\n {\n ...value,\n data: Number.isFinite(numericValue) ? numericValue : value.data,\n displayData: latestValueRef.current,\n },\n movement\n )\n return\n }\n\n onFinishedEditing(\n {\n ...value,\n data: latestValueRef.current,\n displayData: latestValueRef.current,\n },\n movement\n )\n },\n [onFinishedEditing, overlayOpenRef, readOnly, value]\n )\n\n React.useEffect(() => {\n overlayOpenRef.current = true\n\n const input = inputRef.current\n if (!input) {\n return () => {\n overlayOpenRef.current = false\n }\n }\n\n const handleInput = (event: Event) => {\n event.stopPropagation()\n latestValueRef.current = input.value\n }\n const stopTextInputPropagation = (event: Event) => {\n event.stopPropagation()\n }\n const handleKeyDown = (event: KeyboardEvent) => {\n event.stopPropagation()\n\n if (event.key === "Escape") {\n event.preventDefault()\n finishEditing(false)\n return\n }\n\n if (event.key === "Tab") {\n event.preventDefault()\n finishEditing(true, [event.shiftKey ? -1 : 1, 0])\n return\n }\n\n if (event.key === "Enter" && !event.shiftKey) {\n event.preventDefault()\n finishEditing(true, [0, 1])\n }\n }\n\n input.addEventListener("input", handleInput)\n input.addEventListener("beforeinput", stopTextInputPropagation, true)\n input.addEventListener("keydown", handleKeyDown, true)\n\n input.focus()\n\n if (validatedSelection !== undefined) {\n const selectionRange =\n typeof validatedSelection === "number"\n ? [validatedSelection, validatedSelection]\n : validatedSelection\n input.setSelectionRange(selectionRange[0], selectionRange[1])\n } else if (isHighlighted) {\n input.setSelectionRange(0, input.value.length)\n } else {\n input.setSelectionRange(input.value.length, input.value.length)\n }\n\n return () => {\n input.removeEventListener("input", handleInput)\n input.removeEventListener("beforeinput", stopTextInputPropagation, true)\n input.removeEventListener("keydown", handleKeyDown, true)\n overlayOpenRef.current = false\n }\n }, [\n finishEditing,\n isHighlighted,\n overlayOpenRef,\n validatedSelection,\n readOnly,\n ])\n\n React.useEffect(() => {\n const handlePointerOutside = (event: PointerEvent | MouseEvent) => {\n const input = inputRef.current\n const overlayRoot = input?.closest(".gdg-clip-region")\n\n if (!overlayRoot || overlayRoot.contains(event.target as Node | null)) {\n return\n }\n\n finishEditing(true)\n }\n\n document.addEventListener("pointerdown", handlePointerOutside, true)\n document.addEventListener("contextmenu", handlePointerOutside, true)\n\n return () => {\n document.removeEventListener("pointerdown", handlePointerOutside, true)\n document.removeEventListener("contextmenu", handlePointerOutside, true)\n }\n }, [finishEditing])\n\n return (\n <textarea\n ref={inputRef}\n className="gdg-input"\n defaultValue={initialValue}\n readOnly={readOnly}\n aria-readonly={readOnly}\n dir="auto"\n style={{ height: "100%", minHeight: 32, resize: "none", width: "100%" }}\n />\n )\n}\n\nfunction getFieldIcon(type: SchemaPropertyType) {\n if (type === "number" || type === "integer") return InputNumericIcon\n if (type === "boolean") return TextCheckIcon\n if (type === "array") return SecondBracketIcon\n if (type === "object") return SourceCodeSquareIcon\n return InputTextIcon\n}\n\nfunction HumanReviewValueInput({\n readOnly = false,\n schema,\n value,\n onChange,\n}: {\n readOnly?: boolean\n schema: ReviewFieldSchema\n value: JsonPrimitive\n onChange: (value: JsonPrimitive) => void\n}) {\n if (schema.enum?.length) {\n return (\n <span className="relative inline-flex w-full rounded-lg border border-input bg-background text-sm text-foreground shadow-xs/5 dark:bg-input/32">\n <select\n disabled={readOnly}\n value={value === null ? "" : String(value)}\n onChange={(event) => onChange(event.target.value)}\n className="h-8.5 w-full appearance-none rounded-[inherit] bg-transparent px-3 text-sm outline-none sm:h-7.5"\n >\n {schema.enum.map((option) => (\n <option key={String(option)} value={String(option)}>\n {String(option)}\n </option>\n ))}\n </select>\n </span>\n )\n }\n\n if (schema.type === "number" || schema.type === "integer") {\n return (\n <Input\n nativeInput\n readOnly={readOnly}\n type="number"\n value={value === null ? "" : String(value)}\n onChange={(event) => {\n const nextValue = event.currentTarget.value\n onChange(nextValue === "" ? null : Number(nextValue))\n }}\n />\n )\n }\n\n if (schema.type === "boolean") {\n return (\n <div className="grid grid-cols-2 gap-1 rounded-lg bg-muted p-0.5">\n {[true, false].map((option) => (\n <Button\n key={String(option)}\n type="button"\n size="sm"\n variant={value === option ? "outline" : "ghost"}\n className={cn(\n "h-7 shadow-none",\n value === option && "bg-background dark:bg-input"\n )}\n disabled={readOnly}\n onClick={() => onChange(option)}\n >\n {option ? "True" : "False"}\n </Button>\n ))}\n </div>\n )\n }\n\n return (\n <Input\n nativeInput\n readOnly={readOnly}\n value={value === null ? "" : String(value)}\n onChange={(event) => onChange(event.currentTarget.value)}\n />\n )\n}\n\nfunction getArrayItemSchema(schema: ReviewFieldSchema): ReviewFieldSchema {\n return schema.items ?? { type: "string" }\n}\n\nfunction isComplexSchema(schema: ReviewFieldSchema) {\n return schema.type === "object" || schema.type === "array"\n}\n\nfunction summarizeComplexValue(value: JsonValue) {\n if (isJsonArray(value)) return `${value.length} items`\n if (isJsonObject(value)) return `${Object.keys(value).length} fields`\n return formatValue(value)\n}\n\nfunction getCellValueForArrayColumn(\n rowValue: JsonValue,\n itemSchema: ReviewFieldSchema,\n columnId: string\n) {\n if (itemSchema.type === "object") {\n return getObjectValue(rowValue, columnId)\n }\n\n return rowValue\n}\n\nfunction getCellSchemaForArrayColumn(\n itemSchema: ReviewFieldSchema,\n columnId: string\n) {\n if (itemSchema.type === "object") {\n return itemSchema.properties?.[columnId] ?? { type: "string" }\n }\n\n return itemSchema\n}\n\nfunction applyPrimitiveEdit(\n schema: ReviewFieldSchema,\n value: EditableGridCell\n): JsonValue | undefined {\n if (schema.type === "boolean" && value.kind === GridCellKind.Boolean) {\n return value.data\n }\n\n if (\n (schema.type === "number" || schema.type === "integer") &&\n value.kind === GridCellKind.Number\n ) {\n return value.data ?? null\n }\n\n if (value.kind === GridCellKind.Text) {\n if (schema.type === "number" || schema.type === "integer") {\n return value.data.trim() === "" ? null : Number(value.data)\n }\n\n return value.data\n }\n\n return undefined\n}\n\ntype ArrayNestedView = {\n rowIndex: number\n columnId: string\n title: string\n schema: ReviewFieldSchema\n value: JsonValue\n}\n\ntype ArrayReviewSide = "actual" | "expected"\n\ntype SyncedArrayNestedView = {\n activeSide: ArrayReviewSide | null\n stack: ArrayNestedView[]\n}\n\ntype SyncedArraySelection = {\n activeSide: ArrayReviewSide | null\n depth: number\n gridSelection: GridSelection\n}\n\nexport type HumanReviewTheme = "light" | "dark"\n\nconst EMPTY_SYNCED_ARRAY_NESTED_VIEW: SyncedArrayNestedView = {\n activeSide: null,\n stack: [],\n}\n\nconst EMPTY_SYNCED_ARRAY_SELECTION: SyncedArraySelection = {\n activeSide: null,\n depth: 0,\n gridSelection: emptyGridSelection,\n}\n\nfunction setNestedArrayValue({\n value,\n schema,\n nestedStack,\n nextNestedValue,\n}: {\n value: JsonValue\n schema: ReviewFieldSchema\n nestedStack: ArrayNestedView[]\n nextNestedValue: JsonValue\n}): JsonValue {\n const [currentView, ...remainingViews] = nestedStack\n\n if (!currentView) return nextNestedValue\n\n const itemSchema = getArrayItemSchema(schema)\n const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n const cellSchema = getCellSchemaForArrayColumn(\n itemSchema,\n currentView.columnId\n )\n const currentCellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n currentView.columnId\n )\n const nextCellValue: JsonValue = remainingViews.length\n ? setNestedArrayValue({\n value: currentCellValue,\n schema: cellSchema,\n nestedStack: remainingViews,\n nextNestedValue,\n })\n : nextNestedValue\n const nextRowValue: JsonValue =\n itemSchema.type === "object"\n ? setObjectValue(rowValue, currentView.columnId, nextCellValue)\n : nextCellValue\n\n return setArrayItemValue(value, currentView.rowIndex, nextRowValue)\n}\n\nfunction getNestedArrayValue({\n value,\n schema,\n nestedStack,\n}: {\n value: JsonValue\n schema: ReviewFieldSchema\n nestedStack: ArrayNestedView[]\n}): JsonValue {\n const [currentView, ...remainingViews] = nestedStack\n\n if (!currentView) return value\n\n const itemSchema = getArrayItemSchema(schema)\n const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n const cellSchema = getCellSchemaForArrayColumn(\n itemSchema,\n currentView.columnId\n )\n const cellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n currentView.columnId\n )\n\n if (!remainingViews.length) return cellValue\n\n return getNestedArrayValue({\n value: cellValue,\n schema: cellSchema,\n nestedStack: remainingViews,\n })\n}\n\nfunction HumanReviewArrayValueGrid({\n activeNestedSide = null,\n activeSelectionSide = null,\n label,\n nestedStackBaseDepth = 0,\n readOnly = false,\n schema,\n selectionDepth = 0,\n sharedGridSelection,\n sharedNestedStack,\n value,\n viewSide = "expected",\n onChange,\n onGridSelectionChange,\n onNestedStackChange,\n}: {\n activeNestedSide?: ArrayReviewSide | null\n activeSelectionSide?: ArrayReviewSide | null\n label: string\n nestedStackBaseDepth?: number\n readOnly?: boolean\n schema: ReviewFieldSchema\n selectionDepth?: number\n sharedGridSelection?: GridSelection\n sharedNestedStack?: ArrayNestedView[]\n value: JsonValue\n viewSide?: ArrayReviewSide\n onChange?: (value: JsonValue) => void\n onGridSelectionChange?: (\n selection: GridSelection,\n side: ArrayReviewSide,\n depth: number\n ) => void\n onNestedStackChange?: (\n stack: ArrayNestedView[],\n side: ArrayReviewSide\n ) => void\n}) {\n const rows = getArrayValue(value)\n const itemSchema = getArrayItemSchema(schema)\n const gridTheme = useHumanReviewGridTheme()\n const isDark = useIsDarkTheme()\n const [localNestedStack, setLocalNestedStack] = React.useState<\n ArrayNestedView[]\n >([])\n const [localGridSelection, setLocalGridSelection] =\n React.useState<GridSelection>(emptyGridSelection)\n const fastTextOverlayOpenRef = React.useRef(false)\n const nestedStack = sharedNestedStack ?? localNestedStack\n const visibleNestedStack = nestedStack.slice(nestedStackBaseDepth)\n const activeNestedView = visibleNestedStack[0] ?? null\n const activeNestedValue = activeNestedView\n ? getNestedArrayValue({\n value,\n schema,\n nestedStack: [activeNestedView],\n })\n : null\n const isActiveNestedSource =\n Boolean(activeNestedView) && activeNestedSide === viewSide\n const isMirroredNestedTarget =\n Boolean(activeNestedView) &&\n activeNestedSide !== null &&\n activeNestedSide !== viewSide\n const blueCellText = isDark ? "rgb(147, 197, 253)" : "rgb(37, 99, 235)"\n const selectedCellBackground = isDark\n ? "rgba(37, 99, 235, 0.2)"\n : "rgba(219, 234, 254, 0.85)"\n const mirroredCellBackground = isDark\n ? "rgba(167, 139, 250, 0.18)"\n : "rgba(237, 233, 254, 0.9)"\n const mirroredHighlightRegions = React.useMemo<\n React.ComponentProps<typeof DataEditor>["highlightRegions"]\n >(() => {\n if (\n !activeSelectionSide ||\n activeSelectionSide === viewSide ||\n selectionDepth !== nestedStackBaseDepth\n ) {\n return undefined\n }\n\n const ranges = getGridSelectionRanges(sharedGridSelection)\n if (!ranges.length) return undefined\n\n return ranges.map((range) => ({\n color: mirroredCellBackground,\n range,\n style: "dashed" as const,\n }))\n }, [\n activeSelectionSide,\n mirroredCellBackground,\n nestedStackBaseDepth,\n selectionDepth,\n sharedGridSelection,\n viewSide,\n ])\n\n const setNestedStack = React.useCallback(\n (\n updater:\n | ArrayNestedView[]\n | ((current: ArrayNestedView[]) => ArrayNestedView[])\n ) => {\n if (onNestedStackChange) {\n const nextStack =\n typeof updater === "function" ? updater(nestedStack) : updater\n\n onNestedStackChange(nextStack, viewSide)\n return\n }\n\n setLocalNestedStack(updater)\n },\n [nestedStack, onNestedStackChange, viewSide]\n )\n\n const handleGridSelectionChange = React.useCallback(\n (selection: GridSelection) => {\n flushSync(() => {\n setLocalGridSelection((current) =>\n areGridSelectionsEqual(current, selection) ? current : selection\n )\n })\n\n if (onGridSelectionChange) {\n if (\n activeSelectionSide === viewSide &&\n sharedGridSelection &&\n areGridSelectionsEqual(sharedGridSelection, selection)\n ) {\n return\n }\n\n React.startTransition(() => {\n onGridSelectionChange(selection, viewSide, nestedStackBaseDepth)\n })\n return\n }\n },\n [\n activeSelectionSide,\n nestedStackBaseDepth,\n onGridSelectionChange,\n sharedGridSelection,\n viewSide,\n ]\n )\n\n const columns = React.useMemo<GridColumn[]>(() => {\n if (itemSchema.type === "object") {\n const propertyEntries = Object.entries(itemSchema.properties ?? {})\n\n if (propertyEntries.length) {\n return propertyEntries.map(([key, propertySchema]) => ({\n id: key,\n title: propertySchema.title ?? key,\n width: isComplexSchema(propertySchema) ? 148 : 132,\n }))\n }\n }\n\n return [\n {\n id: "value",\n title: itemSchema.title ?? "Value",\n width: isComplexSchema(itemSchema) ? 148 : 180,\n },\n ]\n }, [itemSchema])\n\n const getCellContent = React.useCallback(\n ([col, row]: Item): GridCell => {\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n const cellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n columnId\n )\n const matchedNestedCell =\n activeNestedView?.rowIndex === row &&\n activeNestedView.columnId === columnId\n const nestedCellTheme: Partial<Theme> | undefined = matchedNestedCell\n ? {\n bgCell: isMirroredNestedTarget\n ? mirroredCellBackground\n : selectedCellBackground,\n textDark: blueCellText,\n }\n : undefined\n\n if (isComplexSchema(cellSchema)) {\n return {\n kind: GridCellKind.Text,\n data: summarizeComplexValue(cellValue),\n displayData: summarizeComplexValue(cellValue),\n allowOverlay: false,\n readonly: true,\n cursor: "pointer",\n activationBehaviorOverride: "second-click",\n themeOverride: {\n textDark: blueCellText,\n ...(nestedCellTheme ?? {}),\n },\n }\n }\n\n if (cellSchema.type === "boolean") {\n return {\n kind: GridCellKind.Boolean,\n data: typeof cellValue === "boolean" ? cellValue : false,\n allowOverlay: false,\n readonly: readOnly,\n }\n }\n\n if (cellSchema.type === "number" || cellSchema.type === "integer") {\n return {\n kind: GridCellKind.Number,\n data: typeof cellValue === "number" ? cellValue : undefined,\n displayData: typeof cellValue === "number" ? String(cellValue) : "",\n allowOverlay: true,\n readonly: false,\n activationBehaviorOverride: readOnly ? "single-click" : undefined,\n }\n }\n\n return {\n kind: GridCellKind.Text,\n data:\n cellValue === null ||\n isJsonObject(cellValue) ||\n isJsonArray(cellValue)\n ? ""\n : String(cellValue),\n displayData:\n cellValue === null ||\n isJsonObject(cellValue) ||\n isJsonArray(cellValue)\n ? ""\n : String(cellValue),\n allowOverlay: true,\n readonly: false,\n activationBehaviorOverride: readOnly ? "single-click" : undefined,\n }\n },\n [\n activeNestedView,\n blueCellText,\n columns,\n isMirroredNestedTarget,\n itemSchema,\n mirroredCellBackground,\n readOnly,\n rows,\n selectedCellBackground,\n ]\n )\n\n const updateCellValue = React.useCallback(\n ([col, row]: Item, nextCell: EditableGridCell) => {\n if (readOnly || !onChange) return\n\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n const nextValue = applyPrimitiveEdit(cellSchema, nextCell)\n\n if (nextValue === undefined) return\n\n const nextRowValue =\n itemSchema.type === "object"\n ? setObjectValue(rowValue, columnId, nextValue)\n : nextValue\n\n onChange(setArrayItemValue(value, row, nextRowValue))\n },\n [columns, itemSchema, onChange, readOnly, rows, value]\n )\n const provideEditor = React.useCallback<\n NonNullable<React.ComponentProps<typeof DataEditor>["provideEditor"]>\n >(\n (cell) => {\n if (\n cell.kind !== GridCellKind.Text &&\n cell.kind !== GridCellKind.Number\n ) {\n return undefined\n }\n\n return {\n editor: (props) => {\n if (\n props.value.kind !== GridCellKind.Text &&\n props.value.kind !== GridCellKind.Number\n ) {\n return null\n }\n\n return (\n <HumanReviewTextOverlayEditor\n {...(props as React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n >)}\n overlayOpenRef={fastTextOverlayOpenRef}\n readOnly={readOnly}\n />\n )\n },\n }\n },\n [readOnly]\n )\n const handleOutsideClick = React.useCallback(\n () => !fastTextOverlayOpenRef.current,\n []\n )\n\n const openNestedCell = React.useCallback(\n ([col, row]: Item) => {\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n\n if (!isComplexSchema(cellSchema)) return\n\n setNestedStack((current) => {\n const nextView = {\n rowIndex: row,\n columnId,\n title: `${column?.title ?? columnId} / row ${row + 1}`,\n schema: cellSchema,\n value: getCellValueForArrayColumn(rowValue, itemSchema, columnId),\n }\n const currentView = current[nestedStackBaseDepth]\n\n if (\n currentView?.rowIndex === nextView.rowIndex &&\n currentView.columnId === nextView.columnId\n ) {\n return current\n }\n\n return [...current.slice(0, nestedStackBaseDepth), nextView]\n })\n },\n [columns, itemSchema, nestedStackBaseDepth, rows, setNestedStack]\n )\n\n const updateNestedValue = React.useCallback(\n (nextNestedValue: JsonValue) => {\n if (!activeNestedView || readOnly || !onChange) return\n\n onChange(\n setNestedArrayValue({\n value,\n schema,\n nestedStack: visibleNestedStack.slice(0, 1),\n nextNestedValue,\n })\n )\n setNestedStack((current) =>\n current.map((view, index) =>\n index === nestedStackBaseDepth\n ? { ...view, value: nextNestedValue }\n : view\n )\n )\n },\n [\n activeNestedView,\n nestedStackBaseDepth,\n onChange,\n readOnly,\n schema,\n setNestedStack,\n value,\n visibleNestedStack,\n ]\n )\n\n return (\n <div\n className={cn(\n "relative overflow-hidden rounded-md border bg-background transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:shadow-[0_0_0_1px_rgb(59_130_246_/_8%)] hover:border-blue-500/50",\n isActiveNestedSource &&\n "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_10%)]"\n )}\n >\n <div>\n <div className="flex h-8 items-center justify-between gap-2 border-b px-2 text-[11px] font-medium text-muted-foreground">\n <span>{label}</span>\n <span>{rows.length} rows</span>\n </div>\n <div className="h-[220px]">\n <DataEditor\n columns={columns}\n rows={rows.length}\n getCellContent={getCellContent}\n cellActivationBehavior={readOnly ? "single-click" : "second-click"}\n gridSelection={localGridSelection}\n highlightRegions={mirroredHighlightRegions}\n onCellEdited={updateCellValue}\n onCellActivated={openNestedCell}\n onGridSelectionChange={handleGridSelectionChange}\n provideEditor={provideEditor}\n isOutsideClick={handleOutsideClick}\n rowMarkers="number"\n smoothScrollX\n smoothScrollY\n theme={gridTheme}\n width="100%"\n height="100%"\n rowHeight={32}\n headerHeight={34}\n />\n </div>\n </div>\n {activeNestedView ? (\n <div className="absolute inset-0 z-10 flex flex-col bg-background">\n <div className="flex h-8 items-center gap-2 border-b px-2">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="size-6 text-muted-foreground"\n onClick={() =>\n setNestedStack((current) =>\n current.slice(\n 0,\n Math.max(nestedStackBaseDepth, current.length - 1)\n )\n )\n }\n aria-label="Back to parent array"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />\n </Button>\n <div className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">\n {activeNestedView.title}\n </div>\n </div>\n <div className="min-h-0 flex-1 overflow-auto p-2">\n {activeNestedView.schema.type === "array" ? (\n <HumanReviewArrayValueGrid\n label={\n activeNestedView.schema.title ?? activeNestedView.columnId\n }\n nestedStackBaseDepth={nestedStackBaseDepth + 1}\n readOnly={readOnly}\n schema={activeNestedView.schema}\n sharedGridSelection={sharedGridSelection}\n sharedNestedStack={sharedNestedStack}\n value={activeNestedValue}\n viewSide={viewSide}\n activeNestedSide={activeNestedSide}\n activeSelectionSide={activeSelectionSide}\n selectionDepth={selectionDepth}\n onChange={updateNestedValue}\n onGridSelectionChange={onGridSelectionChange}\n onNestedStackChange={onNestedStackChange}\n />\n ) : (\n <HumanReviewObjectValueEditor\n schema={activeNestedView.schema}\n value={activeNestedValue}\n originalValue={activeNestedValue}\n readOnly={readOnly}\n onChange={updateNestedValue}\n />\n )}\n </div>\n </div>\n ) : null}\n </div>\n )\n}\n\nfunction HumanReviewObjectValueEditor({\n schema,\n value,\n originalValue,\n readOnly = false,\n onChange,\n}: {\n schema: ReviewFieldSchema\n value: JsonValue\n originalValue: JsonValue\n readOnly?: boolean\n onChange: (value: JsonValue) => void\n}) {\n const propertyEntries = Object.entries(schema.properties ?? {})\n\n if (!propertyEntries.length) {\n return (\n <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n No properties\n </div>\n )\n }\n\n return (\n <div className="space-y-2">\n {propertyEntries.map(([propertyKey, propertySchema]) => (\n <HumanReviewFieldCard\n key={propertyKey}\n field={{\n key: propertyKey,\n schema: propertySchema,\n actual: getObjectValue(originalValue, propertyKey),\n expected: getObjectValue(originalValue, propertyKey),\n }}\n value={getObjectValue(value, propertyKey)}\n originalValue={getObjectValue(originalValue, propertyKey)}\n readOnly={readOnly}\n onChange={(childValue) =>\n !readOnly &&\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onUndo={() =>\n !readOnly &&\n onChange(\n setObjectValue(\n value,\n propertyKey,\n getObjectValue(originalValue, propertyKey)\n )\n )\n }\n onSetNull={() =>\n !readOnly && onChange(setObjectValue(value, propertyKey, null))\n }\n />\n ))}\n </div>\n )\n}\n\ntype HumanReviewFieldCardProps = {\n field: ReviewField\n value: JsonValue\n originalValue: JsonValue\n active?: boolean\n activeFieldKey?: string\n readOnly?: boolean\n onChange: (value: JsonValue) => void\n onFieldFocus?: (field: ReviewField) => void\n onUndo: () => void\n onSetNull: () => void\n}\n\nfunction areHumanReviewFieldCardPropsEqual(\n previous: HumanReviewFieldCardProps,\n next: HumanReviewFieldCardProps\n) {\n return (\n previous.field === next.field &&\n Object.is(previous.value, next.value) &&\n Object.is(previous.originalValue, next.originalValue) &&\n previous.active === next.active &&\n previous.activeFieldKey === next.activeFieldKey &&\n previous.readOnly === next.readOnly &&\n previous.onFieldFocus === next.onFieldFocus\n )\n}\n\nconst HumanReviewFieldCard = React.memo(\n HumanReviewFieldCardBase,\n areHumanReviewFieldCardPropsEqual\n)\n\nfunction HumanReviewFieldCardBase({\n field,\n value,\n originalValue,\n active,\n activeFieldKey,\n readOnly = false,\n onChange,\n onFieldFocus,\n onUndo,\n onSetNull,\n}: HumanReviewFieldCardProps) {\n const modified = !jsonValuesEqual(value, originalValue)\n const Icon = getFieldIcon(field.schema.type)\n const propertyEntries = Object.entries(field.schema.properties ?? {})\n const [syncedArrayNestedView, setSyncedArrayNestedView] =\n React.useState<SyncedArrayNestedView>(EMPTY_SYNCED_ARRAY_NESTED_VIEW)\n const [syncedArraySelection, setSyncedArraySelection] =\n React.useState<SyncedArraySelection>(EMPTY_SYNCED_ARRAY_SELECTION)\n const updateSyncedArrayNestedView = React.useCallback(\n (stack: ArrayNestedView[], side: ArrayReviewSide) => {\n const activeSide = stack.length ? side : null\n\n setSyncedArrayNestedView((current) =>\n current.activeSide === activeSide &&\n areArrayNestedViewsEqual(current.stack, stack)\n ? current\n : {\n activeSide,\n stack,\n }\n )\n },\n []\n )\n const updateSyncedArraySelection = React.useCallback(\n (gridSelection: GridSelection, side: ArrayReviewSide, depth: number) => {\n const activeSide = gridSelection.current ? side : null\n\n setSyncedArraySelection((current) =>\n current.activeSide === activeSide &&\n current.depth === depth &&\n areGridSelectionsEqual(current.gridSelection, gridSelection)\n ? current\n : {\n activeSide,\n depth,\n gridSelection,\n }\n )\n },\n []\n )\n\n return (\n <div\n tabIndex={0}\n onFocusCapture={() => onFieldFocus?.(field)}\n onMouseEnter={() => onFieldFocus?.(field)}\n className={cn(\n "rounded-lg border bg-background p-3 transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:bg-blue-500/5 hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",\n active &&\n "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_8%)]"\n )}\n >\n <div className="mb-3 flex min-h-8 items-start justify-between gap-3">\n <div className="min-w-0">\n <div className="flex min-w-0 items-center gap-2">\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">\n {field.schema.title ?? field.key}\n </div>\n </div>\n <span\n className={cn(\n "size-2 shrink-0 rounded-full bg-amber-400 transition-opacity",\n !modified && "opacity-0"\n )}\n />\n </div>\n <div className="truncate text-xs text-muted-foreground">\n {field.key}\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-1">\n {!readOnly && modified ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="text-muted-foreground"\n onClick={onUndo}\n aria-label={`Undo ${field.key}`}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Revert changes</TooltipContent>\n </Tooltip>\n ) : null}\n {!readOnly ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="text-muted-foreground"\n onClick={onSetNull}\n aria-label={`Set ${field.key} to null`}\n >\n <HugeiconsIcon icon={CancelCircleIcon} className="size-4" />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Set to NULL</TooltipContent>\n </Tooltip>\n ) : null}\n <div className="flex h-6 items-center gap-1 rounded-md border bg-muted/50 px-1.5 text-xs text-muted-foreground">\n <HugeiconsIcon icon={Icon} className="size-3.5" />\n {field.schema.type}\n </div>\n </div>\n </div>\n {field.schema.type === "object" ? (\n <div className="rounded-md border bg-muted/25 p-2">\n <div className="mb-2 flex items-center justify-between gap-3 text-[11px] font-medium text-muted-foreground">\n <span>Properties</span>\n <span>{propertyEntries.length} fields</span>\n </div>\n <div className="space-y-2">\n {propertyEntries.length ? (\n propertyEntries.map(([propertyKey, schema]) => {\n const childField: ReviewField = {\n key: `${field.key}.${propertyKey}`,\n schema,\n actual: getObjectValue(field.actual, propertyKey),\n expected: getObjectValue(originalValue, propertyKey),\n }\n\n return (\n <HumanReviewFieldCard\n key={childField.key}\n field={childField}\n value={getObjectValue(value, propertyKey)}\n originalValue={childField.expected}\n active={childField.key === activeFieldKey}\n activeFieldKey={activeFieldKey}\n readOnly={readOnly}\n onChange={(childValue) =>\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onFieldFocus={onFieldFocus}\n onUndo={() =>\n onChange(\n setObjectValue(value, propertyKey, childField.expected)\n )\n }\n onSetNull={() =>\n onChange(setObjectValue(value, propertyKey, null))\n }\n />\n )\n })\n ) : (\n <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n No properties\n </div>\n )}\n </div>\n </div>\n ) : field.schema.type === "array" ? (\n <div className="grid gap-2">\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Actual"\n readOnly\n schema={field.schema}\n selectionDepth={syncedArraySelection.depth}\n sharedGridSelection={syncedArraySelection.gridSelection}\n sharedNestedStack={syncedArrayNestedView.stack}\n value={field.actual}\n viewSide="actual"\n onGridSelectionChange={updateSyncedArraySelection}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Expected"\n readOnly={readOnly}\n schema={field.schema}\n selectionDepth={syncedArraySelection.depth}\n sharedGridSelection={syncedArraySelection.gridSelection}\n sharedNestedStack={syncedArrayNestedView.stack}\n value={value}\n viewSide="expected"\n onChange={onChange}\n onGridSelectionChange={updateSyncedArraySelection}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n </div>\n ) : (\n <div className="grid gap-2 sm:grid-cols-2">\n <div className="rounded-md border bg-muted/30 p-2">\n {field.schema.description ? (\n <p className="mb-2 text-xs text-muted-foreground">\n {field.schema.description}\n </p>\n ) : null}\n <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n Actual\n </div>\n <div className="min-h-7 rounded-md bg-background px-2 py-1.5 text-sm">\n {formatValue(field.actual)}\n </div>\n </div>\n <div className="rounded-md border bg-muted/30 p-2">\n <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n Expected\n </div>\n <HumanReviewValueInput\n readOnly={readOnly}\n schema={field.schema}\n value={getPrimitiveValue(value)}\n onChange={onChange}\n />\n </div>\n </div>\n )}\n </div>\n )\n}\n\nfunction HumanReviewHighlight({ field }: { field: ReviewField }) {\n const area = field.location?.area\n\n if (!area) return null\n\n return (\n <div\n className={cn(\n "pointer-events-none absolute z-10 rounded-[3px] border",\n REVIEW_HIGHLIGHT_STYLE\n )}\n style={{\n left: `${area.left}%`,\n top: `${area.top}%`,\n width: `${area.width}%`,\n height: `${area.height}%`,\n }}\n />\n )\n}\n\nexport function JsonDiffView({\n actual,\n expected,\n theme = "light",\n}: {\n actual: JsonObject\n expected: JsonObject\n theme?: HumanReviewTheme\n}) {\n const oldFile = React.useMemo(\n () => ({\n name: "actual.json",\n contents: formatJson(actual),\n lang: "json",\n }),\n [actual]\n )\n const newFile = React.useMemo(\n () => ({\n name: "expected.json",\n contents: formatJson(expected),\n lang: "json",\n }),\n [expected]\n )\n\n return (\n <Virtualizer\n className="h-full overflow-auto rounded-b-xl bg-surface/60"\n contentClassName="min-w-full"\n >\n <div className="human-review-diff h-full text-xs">\n <MultiFileDiff\n className="block min-w-full"\n style={DIFF_VIEWER_THEME}\n oldFile={oldFile}\n newFile={newFile}\n options={{\n diffStyle: "split",\n diffIndicators: "bars",\n hunkSeparators: "line-info-basic",\n overflow: "wrap",\n themeType: theme,\n theme: {\n light: "pierre-light",\n dark: "pierre-dark",\n },\n }}\n />\n </div>\n </Virtualizer>\n )\n}\n\nexport function HumanReviewPanel({\n fields = REVIEW_FIELDS,\n activeFieldKey,\n className,\n onFieldFocus,\n theme = "light",\n}: {\n fields?: ReviewField[]\n activeFieldKey?: string\n className?: string\n onFieldFocus?: (field: ReviewField) => void\n theme?: HumanReviewTheme\n} = {}) {\n const [activeTab, setActiveTab] = React.useState("form")\n const actualValues = React.useMemo(\n () => valuesFromFields(fields, "actual"),\n [fields]\n )\n const initialExpectedValues = React.useMemo(\n () => valuesFromFields(fields, "expected"),\n [fields]\n )\n const [expected, setExpected] = React.useState<JsonObject>(\n initialExpectedValues\n )\n\n React.useEffect(() => {\n setExpected(initialExpectedValues)\n }, [initialExpectedValues])\n\n const updateValue = React.useCallback((key: string, value: JsonValue) => {\n setExpected((current) =>\n Object.is(current[key], value) ? current : { ...current, [key]: value }\n )\n }, [])\n const fieldCount = React.useMemo(() => countReviewFields(fields), [fields])\n\n return (\n <TooltipProvider delay={200}>\n <Tabs\n value={activeTab}\n onValueChange={setActiveTab}\n className={cn("flex h-[560px] flex-col gap-0 bg-background", className)}\n >\n <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">\n <TabsList className="h-8 sm:h-7">\n <TabsTrigger value="form" className="h-7 sm:h-6">\n <HugeiconsIcon icon={TextCheckIcon} className="size-4" />\n Form\n </TabsTrigger>\n <TabsTrigger value="json" className="h-7 sm:h-6">\n <HugeiconsIcon icon={SourceCodeSquareIcon} className="size-4" />\n JSON\n </TabsTrigger>\n </TabsList>\n <div className="flex h-8 items-center gap-1 rounded-md border bg-muted/40 px-2 text-xs text-muted-foreground sm:h-7">\n <HugeiconsIcon icon={FileDiffIcon} className="size-3.5" />\n {fieldCount} fields\n </div>\n </div>\n <TabsContent value="form" keepMounted className="min-h-0 flex-1">\n <ScrollArea className="h-full" scrollFade>\n <div className="space-y-3 p-3">\n {fields.map((field) => (\n <HumanReviewFieldCard\n key={field.key}\n field={field}\n value={expected[field.key] ?? null}\n originalValue={field.expected}\n active={\n field.key === activeFieldKey ||\n activeFieldKey?.startsWith(`${field.key}.`)\n }\n activeFieldKey={activeFieldKey}\n onChange={(value) => updateValue(field.key, value)}\n onFieldFocus={onFieldFocus}\n onUndo={() => updateValue(field.key, field.expected)}\n onSetNull={() => updateValue(field.key, null)}\n />\n ))}\n </div>\n </ScrollArea>\n </TabsContent>\n <TabsContent value="json" keepMounted className="min-h-0 flex-1">\n <JsonDiffView\n actual={actualValues}\n expected={expected}\n theme={theme}\n />\n </TabsContent>\n </Tabs>\n </TooltipProvider>\n )\n}\n\nexport function HumanReviewBlock({\n file,\n fields = REVIEW_FIELDS,\n className,\n theme,\n}: {\n file?: string\n fields?: ReviewField[]\n className?: string\n theme?: HumanReviewTheme\n}) {\n const [activeFieldKey, setActiveFieldKey] = React.useState(fields[0]?.key)\n const viewerRef = React.useRef<PDFViewerHandle>(null)\n const activeField = findReviewField(fields, activeFieldKey) ?? fields[0]\n\n React.useEffect(() => {\n if (activeFieldKey || !fields[0]) return\n setActiveFieldKey(fields[0].key)\n }, [activeFieldKey, fields])\n\n const focusField = React.useCallback(\n (field: ReviewField) => {\n if (field.key === activeFieldKey) return\n\n setActiveFieldKey(field.key)\n\n if (field.location) {\n viewerRef.current?.scrollToPageArea(\n field.location.page,\n field.location.area\n )\n }\n },\n [activeFieldKey]\n )\n\n return (\n <PdfBlockResizableShell\n autoSaveId="pdf-block-human-review"\n className={className}\n rightDefaultSize={42}\n rightMaxSize={60}\n rightMinSize={30}\n left={\n <PDFViewer\n ref={viewerRef}\n file={file}\n defaultZoom={DEFAULT_ZOOM}\n renderPageOverlay={({ pageNumber }) =>\n activeField?.location?.page === pageNumber ? (\n <HumanReviewHighlight field={activeField} />\n ) : null\n }\n />\n }\n right={\n <aside className="min-h-0 bg-background">\n <HumanReviewPanel\n fields={fields}\n activeFieldKey={activeField?.key}\n className="h-full min-h-0"\n theme={theme}\n onFieldFocus={focusField}\n />\n </aside>\n }\n />\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n DataEditor,\n emptyGridSelection,\n GridCellKind,\n TextCellEntry,\n type EditableGridCell,\n type GridCell,\n type GridColumn,\n type GridMouseEventArgs,\n type GridSelection,\n type Item,\n type NumberCell,\n type ProvideEditorComponent,\n type Rectangle,\n type TextCell,\n type Theme,\n} from "@glideapps/glide-data-grid"\nimport {\n ArrowLeft01Icon,\n CancelCircleIcon,\n FileDiffIcon,\n InputNumericIcon,\n InputTextIcon,\n SecondBracketIcon,\n SourceCodeSquareIcon,\n TextCheckIcon,\n Undo02Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport { MultiFileDiff, Virtualizer } from "@pierre/diffs/react"\nimport { flushSync } from "react-dom"\n\nimport { cn } from "@/lib/utils"\nimport { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"\nimport { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"\nimport { Button } from "@/registry/new-york-v4/ui/button"\nimport { Input } from "@/registry/new-york-v4/ui/input"\nimport { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"\nimport {\n Tabs,\n TabsContent,\n TabsList,\n TabsTrigger,\n} from "@/registry/new-york-v4/ui/tabs"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\nimport "@glideapps/glide-data-grid/dist/index.css"\n\nexport type JsonPrimitive = string | number | boolean | null\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray\nexport type JsonObject = { [key: string]: JsonValue }\nexport type JsonArray = JsonValue[]\nexport type SchemaPropertyType =\n | "string"\n | "number"\n | "integer"\n | "boolean"\n | "object"\n | "array"\n\nexport type ReviewFieldSchema = {\n type: SchemaPropertyType\n title?: string\n description?: string\n enum?: Array<string | number>\n properties?: Record<string, ReviewFieldSchema>\n items?: ReviewFieldSchema\n}\n\nexport type HighlightArea = {\n left: number\n top: number\n width: number\n height: number\n}\n\nexport type ReviewField = {\n key: string\n schema: ReviewFieldSchema\n actual: JsonValue\n expected: JsonValue\n location?: ReviewLocation\n metadataPath?: string\n}\n\nexport type ReviewLocation = {\n page: number\n area: HighlightArea\n}\n\nexport type ReviewCitation = {\n page: number\n polygon?: Array<{ x: number; y: number }>\n pageWidth: number\n pageHeight: number\n}\n\nexport type ReviewMetadataEntry = {\n citations?: ReviewCitation[]\n}\n\nconst DEFAULT_ZOOM = 0.75\nconst REVIEW_HIGHLIGHT_STYLE =\n "border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_10%)]"\nconst DIFF_VIEWER_THEME = {\n "--diffs-light-bg": "oklch(0.985 0.002 247)",\n "--diffs-dark-bg": "oklch(0.18 0.003 247)",\n "--diffs-light": "oklch(0.22 0.01 247)",\n "--diffs-dark": "oklch(0.92 0.006 247)",\n "--diffs-bg-context-override":\n "light-dark(oklch(0.967 0.003 247), oklch(0.235 0.004 247))",\n "--diffs-bg-context-gutter-override":\n "light-dark(oklch(0.948 0.004 247), oklch(0.205 0.004 247))",\n "--diffs-bg-separator-override":\n "light-dark(oklch(0.94 0.004 247), oklch(0.255 0.005 247))",\n "--diffs-bg-buffer-override":\n "light-dark(oklch(0.955 0.004 247), oklch(0.225 0.004 247))",\n "--diffs-light-addition-color": "oklch(0.54 0.13 158)",\n "--diffs-dark-addition-color": "oklch(0.72 0.13 158)",\n "--diffs-light-deletion-color": "oklch(0.55 0.16 28)",\n "--diffs-dark-deletion-color": "oklch(0.72 0.14 28)",\n "--diffs-bg-addition-override":\n "light-dark(oklch(0.957 0.032 158), oklch(0.255 0.052 158))",\n "--diffs-bg-addition-emphasis-override":\n "light-dark(oklch(0.88 0.06 158), oklch(0.36 0.08 158))",\n "--diffs-bg-deletion-override":\n "light-dark(oklch(0.958 0.03 28), oklch(0.255 0.047 28))",\n "--diffs-bg-deletion-emphasis-override":\n "light-dark(oklch(0.9 0.052 28), oklch(0.36 0.075 28))",\n "--diffs-fg-number-override":\n "light-dark(oklch(0.56 0.018 247), oklch(0.66 0.012 247))",\n "--diffs-font-size": "12px",\n "--diffs-line-height": "20px",\n} as React.CSSProperties\n\nfunction readIsDarkTheme() {\n return (\n typeof document !== "undefined" &&\n document.documentElement.classList.contains("dark")\n )\n}\n\n// A single shared MutationObserver backs every consumer. Each grid previously\n// created its own observer (two, via useHumanReviewGridTheme), so opening a\n// nested array view spun up and tore down several observers at once.\nconst darkThemeListeners = new Set<(isDark: boolean) => void>()\nlet darkThemeObserver: MutationObserver | null = null\nlet sharedIsDarkTheme = false\n\nfunction ensureDarkThemeObserver() {\n if (\n darkThemeObserver ||\n typeof document === "undefined" ||\n typeof MutationObserver === "undefined"\n ) {\n return\n }\n\n sharedIsDarkTheme = readIsDarkTheme()\n darkThemeObserver = new MutationObserver(() => {\n const nextIsDark = readIsDarkTheme()\n if (nextIsDark === sharedIsDarkTheme) return\n\n sharedIsDarkTheme = nextIsDark\n darkThemeListeners.forEach((listener) => listener(nextIsDark))\n })\n darkThemeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ["class"],\n })\n}\n\nfunction useIsDarkTheme() {\n const [isDark, setIsDark] = React.useState(readIsDarkTheme)\n\n React.useEffect(() => {\n ensureDarkThemeObserver()\n setIsDark(sharedIsDarkTheme)\n darkThemeListeners.add(setIsDark)\n\n return () => {\n darkThemeListeners.delete(setIsDark)\n if (darkThemeListeners.size === 0 && darkThemeObserver) {\n darkThemeObserver.disconnect()\n darkThemeObserver = null\n }\n }\n }, [])\n\n return isDark\n}\n\nfunction useHumanReviewGridTheme() {\n const isDark = useIsDarkTheme()\n\n return React.useMemo<Partial<Theme>>(\n () => ({\n accentColor: isDark ? "rgb(96, 165, 250)" : "rgb(37, 99, 235)",\n accentLight: isDark ? "rgba(29, 78, 216, 0.15)" : "rgb(219, 234, 254)",\n accentFg: "rgb(255, 255, 255)",\n textDark: isDark ? "rgb(229, 229, 229)" : "rgb(23, 23, 23)",\n textMedium: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n textLight: isDark ? "rgb(115, 115, 115)" : "rgb(163, 163, 163)",\n textBubble: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n textHeader: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n textGroupHeader: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n bgCell: isDark ? "rgb(10, 10, 10)" : "rgb(255, 255, 255)",\n bgCellMedium: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n bgHeader: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n bgHeaderHasFocus: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n bgHeaderHovered: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n borderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n horizontalBorderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n cellHorizontalPadding: 8,\n cellVerticalPadding: 3,\n headerIconSize: 18,\n baseFontStyle: "13px",\n headerFontStyle: "600 13px",\n markerFontStyle: "11px",\n fontFamily: \'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif\',\n editorFontSize: "13px",\n }),\n [isDark]\n )\n}\n\nconst REVIEW_FIELDS: ReviewField[] = [\n {\n key: "statement_period",\n schema: {\n type: "string",\n title: "Statement period",\n description: "Date range covered by the bank statement.",\n },\n actual: "Jan 1-31, 2026",\n expected: "January 1-31, 2026",\n location: {\n page: 1,\n area: { left: 31, top: 30, width: 40, height: 5.8 },\n },\n },\n {\n key: "transactions",\n schema: {\n type: "array",\n title: "Transactions",\n description: "Posted account activity during the statement period.",\n items: {\n type: "object",\n properties: {\n date: {\n type: "string",\n title: "Date",\n },\n description: {\n type: "string",\n title: "Description",\n },\n amount: {\n type: "number",\n title: "Amount",\n },\n category: {\n type: "string",\n title: "Category",\n },\n },\n },\n },\n actual: [\n {\n date: "2026-01-03",\n description: "ACH CREDIT PAYROLL",\n amount: 4250,\n category: "Deposit",\n },\n {\n date: "2026-01-12",\n description: "POS PURCHASE GROCERY MART",\n amount: -86.42,\n category: "Debit",\n },\n ],\n expected: [\n {\n date: "2026-01-03",\n description: "ACH CREDIT PAYROLL",\n amount: 4250,\n category: "Deposit",\n },\n {\n date: "2026-01-12",\n description: "POS PURCHASE GROCERY MART",\n amount: -68.42,\n category: "Debit",\n },\n ],\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "ending_balance",\n schema: {\n type: "number",\n title: "Ending balance",\n description: "Final account balance at the end of the statement period.",\n },\n actual: 12840.18,\n expected: 12858.18,\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "overdraft_protection_enabled",\n schema: {\n type: "boolean",\n title: "Overdraft protection enabled",\n description: "Whether overdraft protection is enabled for the account.",\n },\n actual: false,\n expected: true,\n location: {\n page: 2,\n area: { left: 9.5, top: 12, width: 81, height: 11.5 },\n },\n },\n {\n key: "account_details",\n schema: {\n type: "object",\n title: "Account details",\n description: "Account owner and identifying details from the statement.",\n properties: {\n holder_name: {\n type: "string",\n title: "Holder name",\n },\n account_last_four: {\n type: "string",\n title: "Account last four",\n },\n account_type: {\n type: "string",\n title: "Account type",\n },\n },\n },\n actual: {\n holder_name: "Jordan Lee",\n account_last_four: "4821",\n account_type: "Checking",\n },\n expected: {\n holder_name: "Jordan Lee",\n account_last_four: "4821",\n account_type: "Premier Checking",\n },\n },\n]\n\nfunction getCitationLocation(\n citation: ReviewCitation\n): ReviewLocation | undefined {\n const polygon = citation.polygon\n if (!polygon?.length || !citation.pageWidth || !citation.pageHeight) {\n return undefined\n }\n\n const xs = polygon.map((point) => point.x)\n const ys = polygon.map((point) => point.y)\n const left = Math.min(...xs)\n const top = Math.min(...ys)\n const right = Math.max(...xs)\n const bottom = Math.max(...ys)\n\n return {\n page: citation.page,\n area: {\n left: (left / citation.pageWidth) * 100,\n top: (top / citation.pageHeight) * 100,\n width: ((right - left) / citation.pageWidth) * 100,\n height: ((bottom - top) / citation.pageHeight) * 100,\n },\n }\n}\n\nfunction getMetadataLocation(\n metadata: Record<string, ReviewMetadataEntry> | undefined,\n metadataPath: string | undefined\n) {\n if (!metadata || !metadataPath) return undefined\n\n const citation = metadata[metadataPath]?.citations?.find(\n (candidate) => candidate.polygon?.length\n )\n\n return citation ? getCitationLocation(citation) : undefined\n}\n\nfunction getReviewFieldLocation(\n field: ReviewField | undefined,\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n) {\n if (!field) return undefined\n\n return (\n field.location ??\n resolveLocation?.(field.metadataPath ?? field.key) ??\n undefined\n )\n}\n\nfunction getReviewLocationKey(location: ReviewLocation | undefined) {\n if (!location) return null\n\n const { area } = location\n return [location.page, area.left, area.top, area.width, area.height].join(":")\n}\n\nfunction valuesFromFields(\n fields: ReviewField[],\n valueKey: "actual" | "expected"\n) {\n return fields.reduce<JsonObject>((values, field) => {\n values[field.key] = field[valueKey]\n return values\n }, {})\n}\n\nfunction formatJson(value: unknown) {\n return JSON.stringify(value, null, 2)\n}\n\nfunction isJsonObject(value: JsonValue): value is JsonObject {\n return typeof value === "object" && value !== null && !Array.isArray(value)\n}\n\nfunction isJsonArray(value: JsonValue): value is JsonArray {\n return Array.isArray(value)\n}\n\nfunction getObjectValue(value: JsonValue, key: string): JsonValue {\n if (!isJsonObject(value)) return null\n return value[key] ?? null\n}\n\nfunction setObjectValue(\n value: JsonValue,\n key: string,\n childValue: JsonValue\n): JsonObject {\n return {\n ...(isJsonObject(value) ? value : {}),\n [key]: childValue,\n }\n}\n\nfunction getArrayValue(value: JsonValue): JsonArray {\n return isJsonArray(value) ? value : []\n}\n\nfunction setArrayItemValue(\n value: JsonValue,\n index: number,\n childValue: JsonValue\n): JsonArray {\n const nextValue = getArrayValue(value).slice()\n nextValue[index] = childValue\n return nextValue\n}\n\nfunction getPrimitiveValue(value: JsonValue): JsonPrimitive {\n return isJsonObject(value) || isJsonArray(value) ? null : value\n}\n\nfunction jsonValuesEqual(left: JsonValue, right: JsonValue) {\n return formatJson(left) === formatJson(right)\n}\n\nfunction countReviewFields(fields: ReviewField[]): number {\n return fields.reduce((count, field) => {\n if (field.schema.type !== "object") return count + 1\n\n const properties = field.schema.properties ?? {}\n const childFields = Object.entries(properties).map(\n ([key, schema]): ReviewField => ({\n key: `${field.key}.${key}`,\n schema,\n actual: getObjectValue(field.actual, key),\n expected: getObjectValue(field.expected, key),\n metadataPath: `${field.metadataPath ?? field.key}.${key}`,\n })\n )\n\n return count + Math.max(countReviewFields(childFields), 1)\n }, 0)\n}\n\nfunction findReviewField(\n fields: ReviewField[],\n fieldKey: string | undefined\n): ReviewField | undefined {\n if (!fieldKey) return undefined\n\n for (const field of fields) {\n if (field.key === fieldKey) return field\n\n if (field.schema.type === "object") {\n const childFields = Object.entries(field.schema.properties ?? {}).map(\n ([key, schema]): ReviewField => ({\n key: `${field.key}.${key}`,\n schema,\n actual: getObjectValue(field.actual, key),\n expected: getObjectValue(field.expected, key),\n metadataPath: `${field.metadataPath ?? field.key}.${key}`,\n })\n )\n const childField = findReviewField(childFields, fieldKey)\n if (childField) return childField\n }\n }\n\n return undefined\n}\n\nfunction formatValue(value: JsonValue) {\n if (value === null) return "NULL"\n if (isJsonObject(value) || isJsonArray(value)) return formatJson(value)\n if (typeof value === "boolean") return value ? "true" : "false"\n return String(value)\n}\n\nfunction areGridRangesEqual(\n left: Readonly<Rectangle> | undefined,\n right: Readonly<Rectangle> | undefined\n) {\n return (\n left === right ||\n (left !== undefined &&\n right !== undefined &&\n left.x === right.x &&\n left.y === right.y &&\n left.width === right.width &&\n left.height === right.height)\n )\n}\n\nfunction areGridRangeStacksEqual(\n left: readonly Readonly<Rectangle>[] | undefined,\n right: readonly Readonly<Rectangle>[] | undefined\n) {\n if (left === right) return true\n if (!left || !right || left.length !== right.length) return false\n\n return left.every((range, index) => areGridRangesEqual(range, right[index]))\n}\n\nfunction areGridSelectionsEqual(left: GridSelection, right: GridSelection) {\n const leftCurrent = left.current\n const rightCurrent = right.current\n\n return (\n leftCurrent?.cell[0] === rightCurrent?.cell[0] &&\n leftCurrent?.cell[1] === rightCurrent?.cell[1] &&\n areGridRangesEqual(leftCurrent?.range, rightCurrent?.range) &&\n areGridRangeStacksEqual(\n leftCurrent?.rangeStack,\n rightCurrent?.rangeStack\n ) &&\n left.columns.equals(right.columns) &&\n left.rows.equals(right.rows)\n )\n}\n\nfunction getGridSelectionRanges(selection: GridSelection | undefined) {\n const current = selection?.current\n if (!current) return []\n\n return [...(current.rangeStack ?? []), current.range]\n}\n\nfunction areArrayNestedViewsEqual(\n left: ArrayNestedView[],\n right: ArrayNestedView[]\n) {\n if (left === right) return true\n if (left.length !== right.length) return false\n\n return left.every((view, index) => {\n const other = right[index]\n\n return (\n view.rowIndex === other?.rowIndex &&\n view.columnId === other.columnId &&\n view.title === other.title &&\n view.schema === other.schema &&\n Object.is(view.value, other.value)\n )\n })\n}\n\ntype HumanReviewOverlayCell = TextCell | NumberCell\n\ntype HumanReviewTextOverlayEditorProps = React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n> & {\n overlayOpenRef: React.RefObject<boolean>\n readOnly?: boolean\n}\n\nfunction HumanReviewTextOverlayEditor({\n isHighlighted,\n onFinishedEditing,\n overlayOpenRef,\n readOnly = false,\n validatedSelection,\n value,\n}: HumanReviewTextOverlayEditorProps) {\n const initialValue =\n value.kind === GridCellKind.Number ? value.displayData : value.data\n const [entryValue, setEntryValue] = React.useState(initialValue)\n const latestValueRef = React.useRef(initialValue)\n const finishedRef = React.useRef(false)\n\n const finishEditing = React.useCallback(\n (\n shouldSave: boolean,\n movement: readonly [-1 | 0 | 1, -1 | 0 | 1] = [0, 0]\n ) => {\n if (finishedRef.current) return\n\n finishedRef.current = true\n overlayOpenRef.current = false\n\n if (!shouldSave || readOnly) {\n onFinishedEditing(undefined, movement)\n return\n }\n\n if (value.kind === GridCellKind.Number) {\n const numericValue = Number(latestValueRef.current)\n\n onFinishedEditing(\n {\n ...value,\n data: Number.isFinite(numericValue) ? numericValue : value.data,\n displayData: latestValueRef.current,\n },\n movement\n )\n return\n }\n\n onFinishedEditing(\n {\n ...value,\n data: latestValueRef.current,\n displayData: latestValueRef.current,\n },\n movement\n )\n },\n [onFinishedEditing, overlayOpenRef, readOnly, value]\n )\n\n const handleEntryChange = React.useCallback(\n (event: React.ChangeEvent<HTMLTextAreaElement>) => {\n event.stopPropagation()\n latestValueRef.current = event.target.value\n setEntryValue(event.target.value)\n },\n []\n )\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n event.stopPropagation()\n\n if (event.key === "Escape") {\n event.preventDefault()\n finishEditing(false)\n return\n }\n\n if (event.key === "Tab") {\n event.preventDefault()\n finishEditing(true, [event.shiftKey ? -1 : 1, 0])\n return\n }\n\n if (event.key === "Enter" && !event.shiftKey) {\n event.preventDefault()\n finishEditing(true, [0, 1])\n }\n },\n [finishEditing]\n )\n\n React.useEffect(() => {\n overlayOpenRef.current = true\n\n return () => {\n overlayOpenRef.current = false\n }\n }, [overlayOpenRef])\n\n React.useEffect(() => {\n const handlePointerOutside = (event: PointerEvent | MouseEvent) => {\n const input = document.querySelector<HTMLTextAreaElement>(".gdg-input")\n const overlayRoot = input?.closest(".gdg-clip-region")\n\n if (!overlayRoot || overlayRoot.contains(event.target as Node | null)) {\n return\n }\n\n finishEditing(true)\n }\n\n document.addEventListener("pointerdown", handlePointerOutside, true)\n document.addEventListener("contextmenu", handlePointerOutside, true)\n\n return () => {\n document.removeEventListener("pointerdown", handlePointerOutside, true)\n document.removeEventListener("contextmenu", handlePointerOutside, true)\n }\n }, [finishEditing])\n\n return (\n <TextCellEntry\n autoFocus={!readOnly}\n disabled={readOnly}\n highlight={isHighlighted}\n value={entryValue}\n validatedSelection={validatedSelection}\n altNewline\n onChange={handleEntryChange}\n onKeyDown={handleKeyDown}\n />\n )\n}\n\nfunction getFieldIcon(type: SchemaPropertyType) {\n if (type === "number" || type === "integer") return InputNumericIcon\n if (type === "boolean") return TextCheckIcon\n if (type === "array") return SecondBracketIcon\n if (type === "object") return SourceCodeSquareIcon\n return InputTextIcon\n}\n\nfunction HumanReviewValueInput({\n readOnly = false,\n schema,\n value,\n onChange,\n}: {\n readOnly?: boolean\n schema: ReviewFieldSchema\n value: JsonPrimitive\n onChange: (value: JsonPrimitive) => void\n}) {\n if (schema.enum?.length) {\n return (\n <span className="relative inline-flex w-full rounded-lg border border-input bg-background text-sm text-foreground shadow-xs/5 dark:bg-input/32">\n <select\n disabled={readOnly}\n value={value === null ? "" : String(value)}\n onChange={(event) => onChange(event.target.value)}\n className="h-8.5 w-full appearance-none rounded-[inherit] bg-transparent px-3 text-sm outline-none sm:h-7.5"\n >\n {schema.enum.map((option) => (\n <option key={String(option)} value={String(option)}>\n {String(option)}\n </option>\n ))}\n </select>\n </span>\n )\n }\n\n if (schema.type === "number" || schema.type === "integer") {\n return (\n <Input\n nativeInput\n readOnly={readOnly}\n type="number"\n value={value === null ? "" : String(value)}\n onChange={(event) => {\n const nextValue = event.currentTarget.value\n onChange(nextValue === "" ? null : Number(nextValue))\n }}\n />\n )\n }\n\n if (schema.type === "boolean") {\n return (\n <div className="grid grid-cols-2 gap-1 rounded-lg bg-muted p-0.5">\n {[true, false].map((option) => (\n <Button\n key={String(option)}\n type="button"\n size="sm"\n variant={value === option ? "outline" : "ghost"}\n className={cn(\n "h-7 shadow-none",\n value === option && "bg-background dark:bg-input"\n )}\n disabled={readOnly}\n onClick={() => onChange(option)}\n >\n {option ? "True" : "False"}\n </Button>\n ))}\n </div>\n )\n }\n\n return (\n <Input\n nativeInput\n readOnly={readOnly}\n value={value === null ? "" : String(value)}\n onChange={(event) => onChange(event.currentTarget.value)}\n />\n )\n}\n\nfunction getArrayItemSchema(schema: ReviewFieldSchema): ReviewFieldSchema {\n return schema.items ?? { type: "string" }\n}\n\nfunction isComplexSchema(schema: ReviewFieldSchema) {\n return schema.type === "object" || schema.type === "array"\n}\n\nfunction summarizeComplexValue(value: JsonValue) {\n if (isJsonArray(value)) return `${value.length} items`\n if (isJsonObject(value)) return `${Object.keys(value).length} fields`\n return formatValue(value)\n}\n\nfunction getCellValueForArrayColumn(\n rowValue: JsonValue,\n itemSchema: ReviewFieldSchema,\n columnId: string\n) {\n if (itemSchema.type === "object") {\n return getObjectValue(rowValue, columnId)\n }\n\n return rowValue\n}\n\nfunction getCellSchemaForArrayColumn(\n itemSchema: ReviewFieldSchema,\n columnId: string\n) {\n if (itemSchema.type === "object") {\n return itemSchema.properties?.[columnId] ?? { type: "string" }\n }\n\n return itemSchema\n}\n\nfunction applyPrimitiveEdit(\n schema: ReviewFieldSchema,\n value: EditableGridCell\n): JsonValue | undefined {\n if (schema.type === "boolean" && value.kind === GridCellKind.Boolean) {\n return value.data\n }\n\n if (\n (schema.type === "number" || schema.type === "integer") &&\n value.kind === GridCellKind.Number\n ) {\n return value.data ?? null\n }\n\n if (value.kind === GridCellKind.Text) {\n if (schema.type === "number" || schema.type === "integer") {\n return value.data.trim() === "" ? null : Number(value.data)\n }\n\n return value.data\n }\n\n return undefined\n}\n\ntype ArrayNestedView = {\n rowIndex: number\n columnId: string\n title: string\n schema: ReviewFieldSchema\n value: JsonValue\n}\n\ntype ArrayReviewSide = "actual" | "expected"\n\ntype SyncedArrayNestedView = {\n activeSide: ArrayReviewSide | null\n stack: ArrayNestedView[]\n}\n\ntype SyncedArraySelection = {\n activeSide: ArrayReviewSide | null\n depth: number\n gridSelection: GridSelection\n}\n\nexport type HumanReviewTheme = "light" | "dark"\n\nconst EMPTY_SYNCED_ARRAY_NESTED_VIEW: SyncedArrayNestedView = {\n activeSide: null,\n stack: [],\n}\n\nconst EMPTY_SYNCED_ARRAY_SELECTION: SyncedArraySelection = {\n activeSide: null,\n depth: 0,\n gridSelection: emptyGridSelection,\n}\n\nfunction setNestedArrayValue({\n value,\n schema,\n nestedStack,\n nextNestedValue,\n}: {\n value: JsonValue\n schema: ReviewFieldSchema\n nestedStack: ArrayNestedView[]\n nextNestedValue: JsonValue\n}): JsonValue {\n const [currentView, ...remainingViews] = nestedStack\n\n if (!currentView) return nextNestedValue\n\n const itemSchema = getArrayItemSchema(schema)\n const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n const cellSchema = getCellSchemaForArrayColumn(\n itemSchema,\n currentView.columnId\n )\n const currentCellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n currentView.columnId\n )\n const nextCellValue: JsonValue = remainingViews.length\n ? setNestedArrayValue({\n value: currentCellValue,\n schema: cellSchema,\n nestedStack: remainingViews,\n nextNestedValue,\n })\n : nextNestedValue\n const nextRowValue: JsonValue =\n itemSchema.type === "object"\n ? setObjectValue(rowValue, currentView.columnId, nextCellValue)\n : nextCellValue\n\n return setArrayItemValue(value, currentView.rowIndex, nextRowValue)\n}\n\nfunction getNestedArrayValue({\n value,\n schema,\n nestedStack,\n}: {\n value: JsonValue\n schema: ReviewFieldSchema\n nestedStack: ArrayNestedView[]\n}): JsonValue {\n const [currentView, ...remainingViews] = nestedStack\n\n if (!currentView) return value\n\n const itemSchema = getArrayItemSchema(schema)\n const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n const cellSchema = getCellSchemaForArrayColumn(\n itemSchema,\n currentView.columnId\n )\n const cellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n currentView.columnId\n )\n\n if (!remainingViews.length) return cellValue\n\n return getNestedArrayValue({\n value: cellValue,\n schema: cellSchema,\n nestedStack: remainingViews,\n })\n}\n\nfunction HumanReviewArrayValueGrid({\n activeNestedSide = null,\n activeSelectionSide = null,\n label,\n nestedStackBaseDepth = 0,\n readOnly = false,\n schema,\n selectionDepth = 0,\n sharedGridSelection,\n sharedNestedStack,\n value,\n viewSide = "expected",\n metadataPath,\n onChange,\n onGridSelectionChange,\n onLocationHover,\n onNestedStackChange,\n resolveArrayItemMetadataPath,\n resolveLocation,\n}: {\n activeNestedSide?: ArrayReviewSide | null\n activeSelectionSide?: ArrayReviewSide | null\n label: string\n nestedStackBaseDepth?: number\n readOnly?: boolean\n schema: ReviewFieldSchema\n selectionDepth?: number\n sharedGridSelection?: GridSelection\n sharedNestedStack?: ArrayNestedView[]\n value: JsonValue\n viewSide?: ArrayReviewSide\n metadataPath?: string\n onChange?: (value: JsonValue) => void\n onGridSelectionChange?: (\n selection: GridSelection,\n side: ArrayReviewSide,\n depth: number\n ) => void\n onNestedStackChange?: (\n stack: ArrayNestedView[],\n side: ArrayReviewSide\n ) => void\n onLocationHover?: (location?: ReviewLocation) => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n}) {\n const rows = getArrayValue(value)\n const itemSchema = getArrayItemSchema(schema)\n const gridTheme = useHumanReviewGridTheme()\n const isDark = useIsDarkTheme()\n const [localNestedStack, setLocalNestedStack] = React.useState<\n ArrayNestedView[]\n >([])\n const [localGridSelection, setLocalGridSelection] =\n React.useState<GridSelection>(emptyGridSelection)\n const fastTextOverlayOpenRef = React.useRef(false)\n const nestedStack = sharedNestedStack ?? localNestedStack\n const visibleNestedStack = nestedStack.slice(nestedStackBaseDepth)\n const activeNestedView = visibleNestedStack[0] ?? null\n const activeNestedValue = activeNestedView\n ? getNestedArrayValue({\n value,\n schema,\n nestedStack: [activeNestedView],\n })\n : null\n const isActiveNestedSource =\n Boolean(activeNestedView) && activeNestedSide === viewSide\n const isMirroredNestedTarget =\n Boolean(activeNestedView) &&\n activeNestedSide !== null &&\n activeNestedSide !== viewSide\n const blueCellText = isDark ? "rgb(147, 197, 253)" : "rgb(37, 99, 235)"\n const selectedCellBackground = isDark\n ? "rgba(37, 99, 235, 0.2)"\n : "rgba(219, 234, 254, 0.85)"\n const mirroredCellBackground = isDark\n ? "rgba(167, 139, 250, 0.18)"\n : "rgba(237, 233, 254, 0.9)"\n const mirroredHighlightRegions = React.useMemo<\n React.ComponentProps<typeof DataEditor>["highlightRegions"]\n >(() => {\n if (\n !activeSelectionSide ||\n activeSelectionSide === viewSide ||\n selectionDepth !== nestedStackBaseDepth\n ) {\n return undefined\n }\n\n const ranges = getGridSelectionRanges(sharedGridSelection)\n if (!ranges.length) return undefined\n\n return ranges.map((range) => ({\n color: mirroredCellBackground,\n range,\n style: "dashed" as const,\n }))\n }, [\n activeSelectionSide,\n mirroredCellBackground,\n nestedStackBaseDepth,\n selectionDepth,\n sharedGridSelection,\n viewSide,\n ])\n\n const setNestedStack = React.useCallback(\n (\n updater:\n | ArrayNestedView[]\n | ((current: ArrayNestedView[]) => ArrayNestedView[])\n ) => {\n if (onNestedStackChange) {\n const nextStack =\n typeof updater === "function" ? updater(nestedStack) : updater\n\n onNestedStackChange(nextStack, viewSide)\n return\n }\n\n setLocalNestedStack(updater)\n },\n [nestedStack, onNestedStackChange, viewSide]\n )\n\n const handleGridSelectionChange = React.useCallback(\n (selection: GridSelection) => {\n flushSync(() => {\n setLocalGridSelection((current) =>\n areGridSelectionsEqual(current, selection) ? current : selection\n )\n })\n\n if (onGridSelectionChange) {\n if (\n activeSelectionSide === viewSide &&\n sharedGridSelection &&\n areGridSelectionsEqual(sharedGridSelection, selection)\n ) {\n return\n }\n\n React.startTransition(() => {\n onGridSelectionChange(selection, viewSide, nestedStackBaseDepth)\n })\n return\n }\n },\n [\n activeSelectionSide,\n nestedStackBaseDepth,\n onGridSelectionChange,\n sharedGridSelection,\n viewSide,\n ]\n )\n\n const columns = React.useMemo<GridColumn[]>(() => {\n if (itemSchema.type === "object") {\n const propertyEntries = Object.entries(itemSchema.properties ?? {})\n\n if (propertyEntries.length) {\n return propertyEntries.map(([key, propertySchema]) => ({\n id: key,\n title: propertySchema.title ?? key,\n width: isComplexSchema(propertySchema) ? 148 : 132,\n }))\n }\n }\n\n return [\n {\n id: "value",\n title: itemSchema.title ?? "Value",\n width: isComplexSchema(itemSchema) ? 148 : 180,\n },\n ]\n }, [itemSchema])\n\n const getCellContent = React.useCallback(\n ([col, row]: Item): GridCell => {\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n const cellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n columnId\n )\n const matchedNestedCell =\n activeNestedView?.rowIndex === row &&\n activeNestedView.columnId === columnId\n const nestedCellTheme: Partial<Theme> | undefined = matchedNestedCell\n ? {\n bgCell: isMirroredNestedTarget\n ? mirroredCellBackground\n : selectedCellBackground,\n textDark: blueCellText,\n }\n : undefined\n\n if (isComplexSchema(cellSchema)) {\n return {\n kind: GridCellKind.Text,\n data: summarizeComplexValue(cellValue),\n displayData: summarizeComplexValue(cellValue),\n allowOverlay: false,\n readonly: true,\n cursor: "pointer",\n activationBehaviorOverride: "double-click",\n themeOverride: {\n textDark: blueCellText,\n ...(nestedCellTheme ?? {}),\n },\n }\n }\n\n if (cellSchema.type === "boolean") {\n return {\n kind: GridCellKind.Boolean,\n data: typeof cellValue === "boolean" ? cellValue : false,\n allowOverlay: false,\n readonly: readOnly,\n }\n }\n\n if (cellSchema.type === "number" || cellSchema.type === "integer") {\n return {\n kind: GridCellKind.Number,\n data: typeof cellValue === "number" ? cellValue : undefined,\n displayData: typeof cellValue === "number" ? String(cellValue) : "",\n allowOverlay: true,\n readonly: false,\n }\n }\n\n return {\n kind: GridCellKind.Text,\n data:\n cellValue === null ||\n isJsonObject(cellValue) ||\n isJsonArray(cellValue)\n ? ""\n : String(cellValue),\n displayData:\n cellValue === null ||\n isJsonObject(cellValue) ||\n isJsonArray(cellValue)\n ? ""\n : String(cellValue),\n allowOverlay: true,\n readonly: false,\n }\n },\n [\n activeNestedView,\n blueCellText,\n columns,\n isMirroredNestedTarget,\n itemSchema,\n mirroredCellBackground,\n readOnly,\n rows,\n selectedCellBackground,\n ]\n )\n\n const updateCellValue = React.useCallback(\n ([col, row]: Item, nextCell: EditableGridCell) => {\n if (readOnly || !onChange) return\n\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n const nextValue = applyPrimitiveEdit(cellSchema, nextCell)\n\n if (nextValue === undefined) return\n\n const nextRowValue =\n itemSchema.type === "object"\n ? setObjectValue(rowValue, columnId, nextValue)\n : nextValue\n\n onChange(setArrayItemValue(value, row, nextRowValue))\n },\n [columns, itemSchema, onChange, readOnly, rows, value]\n )\n const provideEditor = React.useCallback<\n NonNullable<React.ComponentProps<typeof DataEditor>["provideEditor"]>\n >(\n (cell) => {\n if (\n cell.kind !== GridCellKind.Text &&\n cell.kind !== GridCellKind.Number\n ) {\n return undefined\n }\n\n return {\n editor: (props) => {\n if (\n props.value.kind !== GridCellKind.Text &&\n props.value.kind !== GridCellKind.Number\n ) {\n return null\n }\n\n return (\n <HumanReviewTextOverlayEditor\n {...(props as React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n >)}\n overlayOpenRef={fastTextOverlayOpenRef}\n readOnly={readOnly}\n />\n )\n },\n }\n },\n [readOnly]\n )\n const handleOutsideClick = React.useCallback(\n () => !fastTextOverlayOpenRef.current,\n []\n )\n const handleItemHovered = React.useCallback(\n (args: GridMouseEventArgs) => {\n if (!onLocationHover || !resolveLocation || !metadataPath) return\n\n if (args.kind !== "cell") {\n onLocationHover(undefined)\n return\n }\n\n const [col, row] = args.location\n const column = columns[col]\n const rowValue = rows[row]\n if (!column || rowValue === undefined) {\n onLocationHover(undefined)\n return\n }\n\n const columnId = String(column.id ?? "value")\n const rowMetadataPath = resolveArrayItemMetadataPath\n ? resolveArrayItemMetadataPath(metadataPath, row, rowValue)\n : `${metadataPath}[${row}]`\n if (!rowMetadataPath) {\n onLocationHover(undefined)\n return\n }\n\n const propertyMetadataPath =\n itemSchema.type === "object"\n ? `${rowMetadataPath}.${columnId}`\n : rowMetadataPath\n\n onLocationHover(\n resolveLocation(propertyMetadataPath) ??\n resolveLocation(rowMetadataPath)\n )\n },\n [\n columns,\n itemSchema.type,\n metadataPath,\n onLocationHover,\n resolveArrayItemMetadataPath,\n resolveLocation,\n rows,\n ]\n )\n\n const openNestedCell = React.useCallback(\n ([col, row]: Item) => {\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n\n if (!isComplexSchema(cellSchema)) return\n\n setNestedStack((current) => {\n const nextView = {\n rowIndex: row,\n columnId,\n title: `${column?.title ?? columnId} / row ${row + 1}`,\n schema: cellSchema,\n value: getCellValueForArrayColumn(rowValue, itemSchema, columnId),\n }\n const currentView = current[nestedStackBaseDepth]\n\n if (\n currentView?.rowIndex === nextView.rowIndex &&\n currentView.columnId === nextView.columnId\n ) {\n return current\n }\n\n return [...current.slice(0, nestedStackBaseDepth), nextView]\n })\n },\n [columns, itemSchema, nestedStackBaseDepth, rows, setNestedStack]\n )\n\n const updateNestedValue = React.useCallback(\n (nextNestedValue: JsonValue) => {\n if (!activeNestedView || readOnly || !onChange) return\n\n onChange(\n setNestedArrayValue({\n value,\n schema,\n nestedStack: visibleNestedStack.slice(0, 1),\n nextNestedValue,\n })\n )\n setNestedStack((current) =>\n current.map((view, index) =>\n index === nestedStackBaseDepth\n ? { ...view, value: nextNestedValue }\n : view\n )\n )\n },\n [\n activeNestedView,\n nestedStackBaseDepth,\n onChange,\n readOnly,\n schema,\n setNestedStack,\n value,\n visibleNestedStack,\n ]\n )\n\n return (\n <div\n onMouseLeave={() => onLocationHover?.(undefined)}\n className={cn(\n "relative overflow-hidden rounded-md border bg-background transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:shadow-[0_0_0_1px_rgb(59_130_246_/_8%)] hover:border-blue-500/50",\n isActiveNestedSource &&\n "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_10%)]"\n )}\n >\n <div>\n <div className="flex h-8 items-center justify-between gap-2 border-b px-2 text-[11px] font-medium text-muted-foreground">\n <span>{label}</span>\n <span>{rows.length} rows</span>\n </div>\n <div className="h-[220px]">\n <DataEditor\n columns={columns}\n rows={rows.length}\n getCellContent={getCellContent}\n cellActivationBehavior="double-click"\n gridSelection={localGridSelection}\n highlightRegions={mirroredHighlightRegions}\n onCellEdited={updateCellValue}\n onCellActivated={openNestedCell}\n onGridSelectionChange={handleGridSelectionChange}\n onItemHovered={handleItemHovered}\n provideEditor={provideEditor}\n isOutsideClick={handleOutsideClick}\n rowMarkers="number"\n smoothScrollX\n smoothScrollY\n theme={gridTheme}\n width="100%"\n height="100%"\n rowHeight={32}\n headerHeight={34}\n />\n </div>\n </div>\n {activeNestedView ? (\n <div className="absolute inset-0 z-10 flex flex-col bg-background">\n <div className="flex h-8 items-center gap-2 border-b px-2">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="size-6 text-muted-foreground"\n onClick={() =>\n setNestedStack((current) =>\n current.slice(\n 0,\n Math.max(nestedStackBaseDepth, current.length - 1)\n )\n )\n }\n aria-label="Back to parent array"\n >\n <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />\n </Button>\n <div className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">\n {activeNestedView.title}\n </div>\n </div>\n <div className="min-h-0 flex-1 overflow-auto p-2">\n {activeNestedView.schema.type === "array" ? (\n <HumanReviewArrayValueGrid\n label={\n activeNestedView.schema.title ?? activeNestedView.columnId\n }\n nestedStackBaseDepth={nestedStackBaseDepth + 1}\n readOnly={readOnly}\n schema={activeNestedView.schema}\n sharedGridSelection={sharedGridSelection}\n sharedNestedStack={sharedNestedStack}\n value={activeNestedValue}\n viewSide={viewSide}\n activeNestedSide={activeNestedSide}\n activeSelectionSide={activeSelectionSide}\n selectionDepth={selectionDepth}\n onChange={updateNestedValue}\n onGridSelectionChange={onGridSelectionChange}\n onNestedStackChange={onNestedStackChange}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n ) : (\n <HumanReviewObjectValueEditor\n schema={activeNestedView.schema}\n value={activeNestedValue}\n originalValue={activeNestedValue}\n readOnly={readOnly}\n onChange={updateNestedValue}\n />\n )}\n </div>\n </div>\n ) : null}\n </div>\n )\n}\n\nfunction HumanReviewObjectValueEditor({\n schema,\n value,\n originalValue,\n readOnly = false,\n onChange,\n}: {\n schema: ReviewFieldSchema\n value: JsonValue\n originalValue: JsonValue\n readOnly?: boolean\n onChange: (value: JsonValue) => void\n}) {\n const propertyEntries = Object.entries(schema.properties ?? {})\n\n if (!propertyEntries.length) {\n return (\n <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n No properties\n </div>\n )\n }\n\n return (\n <div className="space-y-2">\n {propertyEntries.map(([propertyKey, propertySchema]) => (\n <HumanReviewFieldCard\n key={propertyKey}\n field={{\n key: propertyKey,\n schema: propertySchema,\n actual: getObjectValue(originalValue, propertyKey),\n expected: getObjectValue(originalValue, propertyKey),\n }}\n value={getObjectValue(value, propertyKey)}\n originalValue={getObjectValue(originalValue, propertyKey)}\n readOnly={readOnly}\n onChange={(childValue) =>\n !readOnly &&\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onUndo={() =>\n !readOnly &&\n onChange(\n setObjectValue(\n value,\n propertyKey,\n getObjectValue(originalValue, propertyKey)\n )\n )\n }\n onSetNull={() =>\n !readOnly && onChange(setObjectValue(value, propertyKey, null))\n }\n />\n ))}\n </div>\n )\n}\n\ntype HumanReviewFieldCardProps = {\n field: ReviewField\n value: JsonValue\n originalValue: JsonValue\n active?: boolean\n activeFieldKey?: string\n readOnly?: boolean\n onChange: (value: JsonValue) => void\n onFieldFocus?: (field: ReviewField) => void\n onLocationHover?: (location?: ReviewLocation) => void\n onUndo: () => void\n onSetNull: () => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n}\n\nfunction areHumanReviewFieldCardPropsEqual(\n previous: HumanReviewFieldCardProps,\n next: HumanReviewFieldCardProps\n) {\n return (\n previous.field === next.field &&\n Object.is(previous.value, next.value) &&\n Object.is(previous.originalValue, next.originalValue) &&\n previous.active === next.active &&\n previous.activeFieldKey === next.activeFieldKey &&\n previous.readOnly === next.readOnly &&\n previous.onFieldFocus === next.onFieldFocus &&\n previous.onLocationHover === next.onLocationHover &&\n previous.resolveArrayItemMetadataPath ===\n next.resolveArrayItemMetadataPath &&\n previous.resolveLocation === next.resolveLocation\n )\n}\n\nconst HumanReviewFieldCard = React.memo(\n HumanReviewFieldCardBase,\n areHumanReviewFieldCardPropsEqual\n)\n\nfunction HumanReviewFieldCardBase({\n field,\n value,\n originalValue,\n active,\n activeFieldKey,\n readOnly = false,\n onChange,\n onFieldFocus,\n onLocationHover,\n onUndo,\n onSetNull,\n resolveArrayItemMetadataPath,\n resolveLocation,\n}: HumanReviewFieldCardProps) {\n const modified = !jsonValuesEqual(value, originalValue)\n const Icon = getFieldIcon(field.schema.type)\n const propertyEntries = Object.entries(field.schema.properties ?? {})\n const [syncedArrayNestedView, setSyncedArrayNestedView] =\n React.useState<SyncedArrayNestedView>(EMPTY_SYNCED_ARRAY_NESTED_VIEW)\n const [syncedArraySelection, setSyncedArraySelection] =\n React.useState<SyncedArraySelection>(EMPTY_SYNCED_ARRAY_SELECTION)\n const updateSyncedArrayNestedView = React.useCallback(\n (stack: ArrayNestedView[], side: ArrayReviewSide) => {\n const activeSide = stack.length ? side : null\n\n setSyncedArrayNestedView((current) =>\n current.activeSide === activeSide &&\n areArrayNestedViewsEqual(current.stack, stack)\n ? current\n : {\n activeSide,\n stack,\n }\n )\n },\n []\n )\n const updateSyncedArraySelection = React.useCallback(\n (gridSelection: GridSelection, side: ArrayReviewSide, depth: number) => {\n const activeSide = gridSelection.current ? side : null\n\n setSyncedArraySelection((current) =>\n current.activeSide === activeSide &&\n current.depth === depth &&\n areGridSelectionsEqual(current.gridSelection, gridSelection)\n ? current\n : {\n activeSide,\n depth,\n gridSelection,\n }\n )\n },\n []\n )\n const focusAndHoverField = React.useCallback(() => {\n onFieldFocus?.(field)\n onLocationHover?.(getReviewFieldLocation(field, resolveLocation))\n }, [field, onFieldFocus, onLocationHover, resolveLocation])\n\n return (\n <div\n tabIndex={0}\n onFocusCapture={focusAndHoverField}\n onMouseEnter={focusAndHoverField}\n onMouseLeave={() => onLocationHover?.(undefined)}\n className={cn(\n "rounded-lg border bg-background p-3 transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:bg-blue-500/5 hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",\n active &&\n "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_8%)]"\n )}\n >\n <div className="mb-3 flex min-h-8 items-start justify-between gap-3">\n <div className="min-w-0">\n <div className="flex min-w-0 items-center gap-2">\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">\n {field.schema.title ?? field.key}\n </div>\n </div>\n <span\n className={cn(\n "size-2 shrink-0 rounded-full bg-amber-400 transition-opacity",\n !modified && "opacity-0"\n )}\n />\n </div>\n <div className="truncate text-xs text-muted-foreground">\n {field.key}\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-1">\n {!readOnly && modified ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="text-muted-foreground"\n onClick={onUndo}\n aria-label={`Undo ${field.key}`}\n >\n <HugeiconsIcon icon={Undo02Icon} className="size-4" />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Revert changes</TooltipContent>\n </Tooltip>\n ) : null}\n {!readOnly ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="text-muted-foreground"\n onClick={onSetNull}\n aria-label={`Set ${field.key} to null`}\n >\n <HugeiconsIcon icon={CancelCircleIcon} className="size-4" />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Set to NULL</TooltipContent>\n </Tooltip>\n ) : null}\n <div className="flex h-6 items-center gap-1 rounded-md border bg-muted/50 px-1.5 text-xs text-muted-foreground">\n <HugeiconsIcon icon={Icon} className="size-3.5" />\n {field.schema.type}\n </div>\n </div>\n </div>\n {field.schema.type === "object" ? (\n <div className="rounded-md border bg-muted/25 p-2">\n <div className="mb-2 flex items-center justify-between gap-3 text-[11px] font-medium text-muted-foreground">\n <span>Properties</span>\n <span>{propertyEntries.length} fields</span>\n </div>\n <div className="space-y-2">\n {propertyEntries.length ? (\n propertyEntries.map(([propertyKey, schema]) => {\n const childField: ReviewField = {\n key: `${field.key}.${propertyKey}`,\n schema,\n actual: getObjectValue(field.actual, propertyKey),\n expected: getObjectValue(originalValue, propertyKey),\n metadataPath: `${field.metadataPath ?? field.key}.${propertyKey}`,\n }\n\n return (\n <HumanReviewFieldCard\n key={childField.key}\n field={childField}\n value={getObjectValue(value, propertyKey)}\n originalValue={childField.expected}\n active={childField.key === activeFieldKey}\n activeFieldKey={activeFieldKey}\n readOnly={readOnly}\n onChange={(childValue) =>\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onFieldFocus={onFieldFocus}\n onLocationHover={onLocationHover}\n onUndo={() =>\n onChange(\n setObjectValue(value, propertyKey, childField.expected)\n )\n }\n onSetNull={() =>\n onChange(setObjectValue(value, propertyKey, null))\n }\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n )\n })\n ) : (\n <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n No properties\n </div>\n )}\n </div>\n </div>\n ) : field.schema.type === "array" ? (\n <div className="grid gap-2">\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Actual"\n metadataPath={field.metadataPath ?? field.key}\n readOnly\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n schema={field.schema}\n selectionDepth={syncedArraySelection.depth}\n sharedGridSelection={syncedArraySelection.gridSelection}\n sharedNestedStack={syncedArrayNestedView.stack}\n value={field.actual}\n viewSide="actual"\n onGridSelectionChange={updateSyncedArraySelection}\n onLocationHover={onLocationHover}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Expected"\n metadataPath={field.metadataPath ?? field.key}\n readOnly={readOnly}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n schema={field.schema}\n selectionDepth={syncedArraySelection.depth}\n sharedGridSelection={syncedArraySelection.gridSelection}\n sharedNestedStack={syncedArrayNestedView.stack}\n value={value}\n viewSide="expected"\n onChange={onChange}\n onGridSelectionChange={updateSyncedArraySelection}\n onLocationHover={onLocationHover}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n </div>\n ) : (\n <div className="grid gap-2 sm:grid-cols-2">\n <div className="rounded-md border bg-muted/30 p-2">\n {field.schema.description ? (\n <p className="mb-2 text-xs text-muted-foreground">\n {field.schema.description}\n </p>\n ) : null}\n <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n Actual\n </div>\n <div className="min-h-7 rounded-md bg-background px-2 py-1.5 text-sm">\n {formatValue(field.actual)}\n </div>\n </div>\n <div className="rounded-md border bg-muted/30 p-2">\n <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n Expected\n </div>\n <HumanReviewValueInput\n readOnly={readOnly}\n schema={field.schema}\n value={getPrimitiveValue(value)}\n onChange={onChange}\n />\n </div>\n </div>\n )}\n </div>\n )\n}\n\nfunction HumanReviewHighlight({ location }: { location: ReviewLocation }) {\n const area = location.area\n\n return (\n <div\n className={cn(\n "pointer-events-none absolute z-10 border",\n REVIEW_HIGHLIGHT_STYLE\n )}\n style={{\n left: `${area.left}%`,\n top: `${area.top}%`,\n width: `${area.width}%`,\n height: `${area.height}%`,\n }}\n />\n )\n}\n\nexport function JsonDiffView({\n actual,\n expected,\n theme = "light",\n}: {\n actual: JsonObject\n expected: JsonObject\n theme?: HumanReviewTheme\n}) {\n const oldFile = React.useMemo(\n () => ({\n name: "actual.json",\n contents: formatJson(actual),\n lang: "json",\n }),\n [actual]\n )\n const newFile = React.useMemo(\n () => ({\n name: "expected.json",\n contents: formatJson(expected),\n lang: "json",\n }),\n [expected]\n )\n\n return (\n <Virtualizer\n className="h-full overflow-auto rounded-b-xl bg-surface/60"\n contentClassName="min-w-full"\n >\n <div className="human-review-diff h-full text-xs">\n <MultiFileDiff\n className="block min-w-full"\n style={DIFF_VIEWER_THEME}\n oldFile={oldFile}\n newFile={newFile}\n options={{\n diffStyle: "split",\n diffIndicators: "bars",\n hunkSeparators: "line-info-basic",\n overflow: "wrap",\n themeType: theme,\n theme: {\n light: "pierre-light",\n dark: "pierre-dark",\n },\n }}\n />\n </div>\n </Virtualizer>\n )\n}\n\nexport function HumanReviewPanel({\n fields = REVIEW_FIELDS,\n activeFieldKey,\n className,\n onFieldFocus,\n onLocationHover,\n resolveArrayItemMetadataPath,\n resolveLocation,\n theme = "light",\n}: {\n fields?: ReviewField[]\n activeFieldKey?: string\n className?: string\n onFieldFocus?: (field: ReviewField) => void\n onLocationHover?: (location?: ReviewLocation) => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n theme?: HumanReviewTheme\n} = {}) {\n const [activeTab, setActiveTab] = React.useState("form")\n const actualValues = React.useMemo(\n () => valuesFromFields(fields, "actual"),\n [fields]\n )\n const initialExpectedValues = React.useMemo(\n () => valuesFromFields(fields, "expected"),\n [fields]\n )\n const [expected, setExpected] = React.useState<JsonObject>(\n initialExpectedValues\n )\n\n React.useEffect(() => {\n setExpected(initialExpectedValues)\n }, [initialExpectedValues])\n\n const updateValue = React.useCallback((key: string, value: JsonValue) => {\n setExpected((current) =>\n Object.is(current[key], value) ? current : { ...current, [key]: value }\n )\n }, [])\n const fieldCount = React.useMemo(() => countReviewFields(fields), [fields])\n\n return (\n <TooltipProvider delay={200}>\n <Tabs\n value={activeTab}\n onValueChange={setActiveTab}\n className={cn("flex h-[560px] flex-col gap-0 bg-background", className)}\n >\n <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">\n <TabsList className="h-8 sm:h-7">\n <TabsTrigger value="form" className="h-7 sm:h-6">\n <HugeiconsIcon icon={TextCheckIcon} className="size-4" />\n Form\n </TabsTrigger>\n <TabsTrigger value="json" className="h-7 sm:h-6">\n <HugeiconsIcon icon={SourceCodeSquareIcon} className="size-4" />\n JSON\n </TabsTrigger>\n </TabsList>\n <div className="flex h-8 items-center gap-1 rounded-md border bg-muted/40 px-2 text-xs text-muted-foreground sm:h-7">\n <HugeiconsIcon icon={FileDiffIcon} className="size-3.5" />\n {fieldCount} fields\n </div>\n </div>\n <TabsContent value="form" keepMounted className="min-h-0 flex-1">\n <ScrollArea className="h-full" scrollFade>\n <div className="space-y-3 p-3">\n {fields.map((field) => (\n <HumanReviewFieldCard\n key={field.key}\n field={field}\n value={expected[field.key] ?? null}\n originalValue={field.expected}\n active={\n field.key === activeFieldKey ||\n activeFieldKey?.startsWith(`${field.key}.`)\n }\n activeFieldKey={activeFieldKey}\n onChange={(value) => updateValue(field.key, value)}\n onFieldFocus={onFieldFocus}\n onLocationHover={onLocationHover}\n onUndo={() => updateValue(field.key, field.expected)}\n onSetNull={() => updateValue(field.key, null)}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n ))}\n </div>\n </ScrollArea>\n </TabsContent>\n <TabsContent value="json" keepMounted className="min-h-0 flex-1">\n <JsonDiffView\n actual={actualValues}\n expected={expected}\n theme={theme}\n />\n </TabsContent>\n </Tabs>\n </TooltipProvider>\n )\n}\n\nexport function HumanReviewBlock({\n file,\n fields = REVIEW_FIELDS,\n className,\n metadata,\n resolveArrayItemMetadataPath,\n resolveLocation,\n theme,\n}: {\n file?: string\n fields?: ReviewField[]\n className?: string\n metadata?: Record<string, ReviewMetadataEntry>\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n theme?: HumanReviewTheme\n}) {\n const [activeFieldKey, setActiveFieldKey] = React.useState(fields[0]?.key)\n const [hoverLocation, setHoverLocation] =\n React.useState<ReviewLocation | null>(null)\n const viewerRef = React.useRef<PDFViewerHandle>(null)\n const hoverLocationKeyRef = React.useRef<string | null>(null)\n const resolveFieldLocation = React.useCallback(\n (metadataPath: string) =>\n resolveLocation?.(metadataPath) ??\n getMetadataLocation(metadata, metadataPath),\n [metadata, resolveLocation]\n )\n const activeField = findReviewField(fields, activeFieldKey) ?? fields[0]\n const activeLocation =\n hoverLocation ?? getReviewFieldLocation(activeField, resolveFieldLocation)\n\n React.useEffect(() => {\n if (activeFieldKey || !fields[0]) return\n setActiveFieldKey(fields[0].key)\n }, [activeFieldKey, fields])\n\n const focusField = React.useCallback(\n (field: ReviewField) => {\n if (field.key === activeFieldKey) return\n\n setActiveFieldKey(field.key)\n\n const location = getReviewFieldLocation(field, resolveFieldLocation)\n if (location) {\n viewerRef.current?.scrollToPageArea(location.page, location.area)\n }\n },\n [activeFieldKey, resolveFieldLocation]\n )\n const handleLocationHover = React.useCallback((location?: ReviewLocation) => {\n setHoverLocation(location ?? null)\n\n const locationKey = getReviewLocationKey(location)\n if (!location) {\n hoverLocationKeyRef.current = null\n return\n }\n if (locationKey === hoverLocationKeyRef.current) return\n\n hoverLocationKeyRef.current = locationKey\n viewerRef.current?.scrollToPageArea(location.page, location.area, {\n behavior: "auto",\n })\n }, [])\n\n return (\n <PdfBlockResizableShell\n autoSaveId="pdf-block-human-review"\n className={className}\n rightDefaultSize={42}\n rightMaxSize={60}\n rightMinSize={30}\n left={\n <PDFViewer\n ref={viewerRef}\n file={file}\n defaultZoom={DEFAULT_ZOOM}\n renderPageOverlay={({ pageNumber }) =>\n activeLocation?.page === pageNumber ? (\n <HumanReviewHighlight location={activeLocation} />\n ) : null\n }\n />\n }\n right={\n <aside className="min-h-0 bg-background">\n <HumanReviewPanel\n fields={fields}\n activeFieldKey={activeField?.key}\n className="h-full min-h-0"\n theme={theme}\n onFieldFocus={focusField}\n onLocationHover={handleLocationHover}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveFieldLocation}\n />\n </aside>\n }\n />\n )\n}\n'+export function HumanReviewSource() {return <HighlightedCodeBlock code={humanReviewSourceCode} />}diff --git a/apps/v4/components/ocr-blocks-docs.tsx b/apps/v4/components/ocr-blocks-docs.tsxindex 9f9f2c3..4547464 100644--- a/apps/v4/components/ocr-blocks-docs.tsx+++ b/apps/v4/components/ocr-blocks-docs.tsx@@ -2,14 +2,21 @@import * as React from "react"import {+ AlignBoxBottomCenterIcon,Heading01Icon,- Image01Icon,+ ImageCompositionIcon,LeftToRightListBulletIcon,ParagraphIcon,Table01Icon,+ TextCenterlineCenterTopIcon,+ TextNumberSignIcon,} from "@hugeicons/core-free-icons"import { HugeiconsIcon } from "@hugeicons/react"+import { useVirtualizer } from "@tanstack/react-virtual"import ReactMarkdown from "react-markdown"+import rehypeRaw from "rehype-raw"+import rehypeSanitize, { defaultSchema } from "rehype-sanitize"+import remarkGfm from "remark-gfm"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"@@ -23,15 +30,57 @@ type Point = {y: number}-type OcrBlockType = "heading" | "paragraph" | "list" | "table" | "image"+type BoundingBox = {+ left: number+ top: number+ right: number+ bottom: number+}++type OcrBlockType =+ | "heading"+ | "paragraph"+ | "list"+ | "table"+ | "figure"+ | "header"+ | "footer"+ | "page_number"++type ParsedOcrBlock = {+ id: string+ type: string+ content: string+ metadata: {+ page: {+ number: number+ width: number+ height: number+ }+ layoutClass?: string+ minOcrConfidence?: number+ avgOcrConfidence?: number+ }+ polygon?: Point[]+ boundingBox?: BoundingBox+}++type ParsedOcrOutput = {+ chunks: {+ blocks: ParsedOcrBlock[]+ }[]+}type OcrBlock = {id: stringtype: OcrBlockTypetext: stringpage: number+ pageWidth: number+ pageHeight: numberconfidence: number- polygon: Point[]+ polygon?: Point[]+ boundingBox?: BoundingBox}type HighlightArea = {@@ -41,10 +90,30 @@ type HighlightArea = {height: number}-const PDF_URL = "/samples/attention.pdf"-const ANNOTATION_PAGE_WIDTH = 792-const ANNOTATION_PAGE_HEIGHT = 612+const PDF_URL = "/samples/attention-rotated.pdf"const DEFAULT_ZOOM = 0.75+const OCR_BLOCK_ROW_ESTIMATE = 132+const OCR_BLOCK_LIST_PADDING = 12+const OCR_MARKDOWN_SCHEMA = {+ ...defaultSchema,+ attributes: {+ ...defaultSchema.attributes,+ figure: [...(defaultSchema.attributes?.figure ?? []), "type"],+ },+ tagNames: [+ ...(defaultSchema.tagNames ?? []),+ "caption",+ "figcaption",+ "figure",+ ],+}+const OCR_MARKDOWN_REHYPE_PLUGINS: NonNullable<+ React.ComponentProps<typeof ReactMarkdown>["rehypePlugins"]+> = [rehypeRaw, [rehypeSanitize, OCR_MARKDOWN_SCHEMA]]+const OCR_MARKDOWN_REMARK_PLUGINS: NonNullable<+ React.ComponentProps<typeof ReactMarkdown>["remarkPlugins"]+> = [remarkGfm]+const OCR_MARKDOWN_FIGURE_CAPTION_PATTERN = /<\/?caption>/giconst BLOCK_STYLES: Record<OcrBlockType,{@@ -97,9 +166,9 @@ const BLOCK_STYLES: Record<soft: "bg-amber-500/10 text-amber-700 dark:text-amber-300",text: "text-amber-700 dark:text-amber-300",},- image: {- label: "Image",- icon: Image01Icon,+ figure: {+ label: "Figure",+ icon: ImageCompositionIcon,overlay:"border-rose-500/70 bg-rose-500/10 shadow-[0_4px_16px_rgb(244_63_94_/_12%)]",mutedOverlay: "border-rose-500/35 bg-rose-500/5",@@ -107,116 +176,7911 @@ const BLOCK_STYLES: Record<soft: "bg-rose-500/10 text-rose-600 dark:text-rose-300",text: "text-rose-600 dark:text-rose-300",},-}--const OCR_BLOCKS: OcrBlock[] = [- {- id: "title",- type: "heading",- text: "# Attention Is All You Need",- page: 1,- confidence: 0.99,- polygon: [- { x: 246, y: 188 },- { x: 566, y: 188 },- { x: 566, y: 222 },- { x: 246, y: 222 },- ],- },- {- id: "author-grid",- type: "paragraph",- text: "Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, and Illia Polosukhin.",- page: 1,- confidence: 0.96,- polygon: [- { x: 92, y: 206 },- { x: 698, y: 206 },- { x: 698, y: 270 },- { x: 92, y: 270 },- ],- },- {- id: "abstract-heading",- type: "heading",- text: "## Abstract",- page: 1,- confidence: 0.98,- polygon: [- { x: 360, y: 330 },- { x: 434, y: 330 },- { x: 434, y: 350 },- { x: 360, y: 350 },- ],- },- {- id: "abstract-body",- type: "paragraph",- text: "The Transformer is based **solely on attention mechanisms**, dispensing with recurrence and convolutions entirely.",- page: 1,- confidence: 0.94,- polygon: [- { x: 108, y: 346 },- { x: 692, y: 346 },- { x: 692, y: 458 },- { x: 108, y: 458 },- ],- },- {- id: "background-body",- type: "paragraph",- text: "Recurrent neural networks, **LSTM**, and gated recurrent neural networks have been established as sequence modeling approaches.",- page: 2,- confidence: 0.92,- polygon: [- { x: 76, y: 74 },- { x: 718, y: 74 },- { x: 718, y: 184 },- { x: 76, y: 184 },- ],- },- {- id: "attention-diagram",- type: "image",- text: "_Transformer_ architecture diagram",- page: 2,- confidence: 0.89,- polygon: [- { x: 462, y: 250 },- { x: 720, y: 250 },- { x: 720, y: 602 },- { x: 462, y: 602 },- ],+ header: {+ label: "Header",+ icon: TextCenterlineCenterTopIcon,+ overlay:+ "border-cyan-500/70 bg-cyan-500/10 shadow-[0_4px_16px_rgb(6_182_212_/_12%)]",+ mutedOverlay: "border-cyan-500/35 bg-cyan-500/5",+ ring: "border-cyan-500/60 bg-cyan-500/5",+ soft: "bg-cyan-500/10 text-cyan-700 dark:text-cyan-300",+ text: "text-cyan-700 dark:text-cyan-300",},- {- id: "comparison-table",- type: "table",- text: "- **Layer type**\n- Complexity per layer\n- Sequential operations\n- Maximum path length",- page: 6,- confidence: 0.91,- polygon: [- { x: 52, y: 58 },- { x: 740, y: 58 },- { x: 740, y: 190 },- { x: 52, y: 190 },- ],+ footer: {+ label: "Footer",+ icon: AlignBoxBottomCenterIcon,+ overlay:+ "border-slate-500/70 bg-slate-500/10 shadow-[0_4px_16px_rgb(100_116_139_/_12%)]",+ mutedOverlay: "border-slate-500/35 bg-slate-500/5",+ ring: "border-slate-500/60 bg-slate-500/5",+ soft: "bg-slate-500/10 text-slate-700 dark:text-slate-300",+ text: "text-slate-700 dark:text-slate-300",},- {- id: "layer-list",- type: "list",- text: "- Total computational complexity\n- Parallelizable computation\n- Maximum path length",- page: 6,- confidence: 0.88,- polygon: [- { x: 56, y: 440 },- { x: 735, y: 440 },- { x: 735, y: 548 },- { x: 56, y: 548 },- ],+ page_number: {+ label: "Page number",+ icon: TextNumberSignIcon,+ overlay:+ "border-zinc-500/70 bg-zinc-500/10 shadow-[0_4px_16px_rgb(113_113_122_/_12%)]",+ mutedOverlay: "border-zinc-500/35 bg-zinc-500/5",+ ring: "border-zinc-500/60 bg-zinc-500/5",+ soft: "bg-zinc-500/10 text-zinc-700 dark:text-zinc-300",+ text: "text-zinc-700 dark:text-zinc-300",},-]+}++const ATTENTION_OCR_OUTPUT = {+ chunks: [+ {+ blocks: [+ {+ id: "block_1_IKDP4i",+ type: "header",+ content: "arXiv:1706.03762v7 [cs.CL] 2 Aug 2023",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Header",+ minOcrConfidence: 0.959,+ avgOcrConfidence: 0.98,+ },+ polygon: [+ {+ x: 36.16179897837395,+ y: 447.38040863840206,+ },+ {+ x: 75.85163708150822,+ y: 447.38040863840206,+ },+ {+ x: 75.85163708150822,+ y: 1155.1796566956025,+ },+ {+ x: 36.16179897837395,+ y: 1155.1796566956025,+ },+ ],+ boundingBox: {+ left: 36.16179897837395,+ top: 447.38040863840206,+ right: 75.85163708150822,+ bottom: 1155.1796566956025,+ },+ },+ {+ id: "block_1_rtNdsr",+ type: "header",+ content:+ "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.",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Header",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 258.50183528705236,+ y: 151.7837261257315,+ },+ {+ x: 1016.8830982960054,+ y: 151.7837261257315,+ },+ {+ x: 1016.8830982960054,+ y: 233.84929126366637,+ },+ {+ x: 258.50183528705236,+ y: 233.84929126366637,+ },+ ],+ boundingBox: {+ left: 258.50183528705236,+ top: 151.7837261257315,+ right: 1016.8830982960054,+ bottom: 233.84929126366637,+ },+ },+ {+ id: "block_1_eo9AoV",+ type: "heading",+ content: "# Attention Is All You Need",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Heading",+ minOcrConfidence: 0.99,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 440.0215455215343,+ y: 312.01490975860366,+ },+ {+ x: 831.4373211268961,+ y: 312.01490975860366,+ },+ {+ x: 831.4373211268961,+ y: 339.0022611402928,+ },+ {+ x: 440.0215455215343,+ y: 339.0022611402928,+ },+ ],+ boundingBox: {+ left: 440.0215455215343,+ top: 312.01490975860366,+ right: 831.4373211268961,+ bottom: 339.0022611402928,+ },+ },+ {+ id: "block_1_Kdt5Cu",+ type: "text",+ content: "Ashish Vaswani* Google Brain [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.977,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 242.9606625633518,+ y: 490.4495616712068,+ },+ {+ x: 449.64758323056856,+ y: 490.4495616712068,+ },+ {+ x: 449.64758323056856,+ y: 555.9028907431696,+ },+ {+ x: 242.9606625633518,+ y: 555.9028907431696,+ },+ ],+ boundingBox: {+ left: 242.9606625633518,+ top: 490.4495616712068,+ right: 449.64758323056856,+ bottom: 555.9028907431696,+ },+ },+ {+ id: "block_1_6Xv6uR",+ type: "text",+ content: "Llion Jones* Google Research [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.927,+ avgOcrConfidence: 0.982,+ },+ polygon: [+ {+ x: 264.3723327748097,+ y: 594.5307239733245,+ },+ {+ x: 438.3605845653227,+ y: 594.5307239733245,+ },+ {+ x: 438.3605845653227,+ y: 660.7685646688132,+ },+ {+ x: 264.3723327748097,+ y: 660.7685646688132,+ },+ ],+ boundingBox: {+ left: 264.3723327748097,+ top: 594.5307239733245,+ right: 438.3605845653227,+ bottom: 660.7685646688132,+ },+ },+ {+ id: "block_1_Lx35WU",+ type: "text",+ content: "Noam Shazeer* Google Brain [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.983,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 479.08373644752226,+ y: 490.1169480632122,+ },+ {+ x: 643.7573955006842,+ y: 490.1169480632122,+ },+ {+ x: 643.7573955006842,+ y: 556.2343205043247,+ },+ {+ x: 479.08373644752226,+ y: 556.2343205043247,+ },+ ],+ boundingBox: {+ left: 479.08373644752226,+ top: 490.1169480632122,+ right: 643.7573955006842,+ bottom: 556.2343205043247,+ },+ },+ {+ id: "block_1_VxOJIL",+ type: "text",+ content:+ "Aidan N. Gomez* * University of Toronto [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.095,+ avgOcrConfidence: 0.875,+ },+ polygon: [+ {+ x: 489.9820146769503,+ y: 593.5908916444707,+ },+ {+ x: 708.1676900821881,+ y: 593.5908916444707,+ },+ {+ x: 708.1676900821881,+ y: 657.7173651788468,+ },+ {+ x: 489.9820146769503,+ y: 657.7173651788468,+ },+ ],+ boundingBox: {+ left: 489.9820146769503,+ top: 593.5908916444707,+ right: 708.1676900821881,+ bottom: 657.7173651788468,+ },+ },+ {+ id: "block_1_m1Gb17",+ type: "text",+ content: "Niki Parmar* Google Research [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.99,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 673.3537325893875,+ y: 490.2837284059453,+ },+ {+ x: 848.6601168221802,+ y: 490.2837284059453,+ },+ {+ x: 848.6601168221802,+ y: 556.287735673718,+ },+ {+ x: 673.3537325893875,+ y: 556.287735673718,+ },+ ],+ boundingBox: {+ left: 673.3537325893875,+ top: 490.2837284059453,+ right: 848.6601168221802,+ bottom: 556.287735673718,+ },+ },+ {+ id: "block_1_otnY8T",+ type: "text",+ content: "\u0141ukasz Kaiser* Google Brain [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.984,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 759.3324257509552,+ y: 594.2661578816579,+ },+ {+ x: 1011.1333304078039,+ y: 594.2661578816579,+ },+ {+ x: 1011.1333304078039,+ y: 660.9298993160851,+ },+ {+ x: 759.3324257509552,+ y: 660.9298993160851,+ },+ ],+ boundingBox: {+ left: 759.3324257509552,+ top: 594.2661578816579,+ right: 1011.1333304078039,+ bottom: 660.9298993160851,+ },+ },+ {+ id: "block_1_ICaos6",+ type: "text",+ content: "Illia Polosukhin* * [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.107,+ avgOcrConfidence: 0.766,+ },+ polygon: [+ {+ x: 495.9563429338219,+ y: 697.325802423004,+ },+ {+ x: 778.5449758933407,+ y: 697.325802423004,+ },+ {+ x: 778.5449758933407,+ y: 742.1158899292909,+ },+ {+ x: 495.9563429338219,+ y: 742.1158899292909,+ },+ ],+ boundingBox: {+ left: 495.9563429338219,+ top: 697.325802423004,+ right: 778.5449758933407,+ bottom: 742.1158899292909,+ },+ },+ {+ id: "block_1_zNN0g5",+ type: "section_heading",+ content: "### Abstract",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 590.8429918498018,+ y: 804.3203170891095,+ },+ {+ x: 683.8031267597728,+ y: 804.3203170891095,+ },+ {+ x: 683.8031267597728,+ y: 823.7656170264223,+ },+ {+ x: 590.8429918498018,+ y: 823.7656170264223,+ },+ ],+ boundingBox: {+ left: 590.8429918498018,+ top: 804.3203170891095,+ right: 683.8031267597728,+ bottom: 823.7656170264223,+ },+ },+ {+ id: "block_1_Pzc7ia",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.987,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 298.2268201173657,+ y: 861.5167879950731,+ },+ {+ x: 978.0244980415288,+ y: 861.5167879950731,+ },+ {+ x: 978.0244980415288,+ y: 1201.6481075430274,+ },+ {+ x: 298.2268201173657,+ y: 1201.6481075430274,+ },+ ],+ boundingBox: {+ left: 298.2268201173657,+ top: 861.5167879950731,+ right: 978.0244980415288,+ bottom: 1201.6481075430274,+ },+ },+ {+ id: "block_1_bHnLKj",+ type: "text",+ content:+ "*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.",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.951,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 222.8755505415645,+ y: 1247.2573697082978,+ },+ {+ x: 1049.6971241749116,+ y: 1247.2573697082978,+ },+ {+ x: 1049.6971241749116,+ y: 1429.7100451476592,+ },+ {+ x: 222.8755505415645,+ y: 1429.7100451476592,+ },+ ],+ boundingBox: {+ left: 222.8755505415645,+ top: 1247.2573697082978,+ right: 1049.6971241749116,+ bottom: 1429.7100451476592,+ },+ },+ {+ id: "block_1_J3Olku",+ type: "text",+ content: "+ Work performed while at Google Brain.",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.11,+ avgOcrConfidence: 0.869,+ },+ polygon: [+ {+ x: 250.1677060649343,+ y: 1434.3817888991277,+ },+ {+ x: 555.1793119333087,+ y: 1434.3817888991277,+ },+ {+ x: 555.1793119333087,+ y: 1456.532320926064,+ },+ {+ x: 250.1677060649343,+ y: 1456.532320926064,+ },+ ],+ boundingBox: {+ left: 250.1677060649343,+ top: 1434.3817888991277,+ right: 555.1793119333087,+ bottom: 1456.532320926064,+ },+ },+ {+ id: "block_1_aQsakB",+ type: "text",+ content: "#Work performed while at Google Research.",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.652,+ avgOcrConfidence: 0.94,+ },+ polygon: [+ {+ x: 249.36288151427775,+ y: 1458.4100914288283,+ },+ {+ x: 582.4047478446125,+ y: 1458.4100914288283,+ },+ {+ x: 582.4047478446125,+ y: 1479.773507369192,+ },+ {+ x: 249.36288151427775,+ y: 1479.773507369192,+ },+ ],+ boundingBox: {+ left: 249.36288151427775,+ top: 1458.4100914288283,+ right: 582.4047478446125,+ bottom: 1479.773507369192,+ },+ },+ {+ id: "block_1_iKp4Ae",+ type: "footer",+ content:+ "31st Conference on Neural Information Processing Systems (NIPS 2017), Long Beach, CA, USA.",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Footer",+ minOcrConfidence: 0.99,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 224.27405893367575,+ y: 1527.1945287374626,+ },+ {+ x: 958.2568426201814,+ y: 1527.1945287374626,+ },+ {+ x: 958.2568426201814,+ y: 1546.3855383736748,+ },+ {+ x: 224.27405893367575,+ y: 1546.3855383736748,+ },+ ],+ boundingBox: {+ left: 224.27405893367575,+ top: 1527.1945287374626,+ right: 958.2568426201814,+ bottom: 1546.3855383736748,+ },+ },+ {+ id: "block_1_zPHQaR",+ type: "text",+ content: "Jakob Uszkoreit* Google Research [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 879.2488933479699,+ y: 489.58686880240765,+ },+ {+ x: 1035.003756780694,+ y: 489.58686880240765,+ },+ {+ x: 1035.003756780694,+ y: 555.848623204052,+ },+ {+ x: 879.2488933479699,+ y: 555.848623204052,+ },+ ],+ boundingBox: {+ left: 879.2488933479699,+ top: 489.58686880240765,+ right: 1035.003756780694,+ bottom: 555.848623204052,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_2_UD1C1k",+ type: "heading",+ content: "# 1 Introduction",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Heading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 225.86025321570625,+ y: 152.1792611932396,+ },+ {+ x: 396.86960095036636,+ y: 152.1792611932396,+ },+ {+ x: 396.86960095036636,+ y: 171.96800693712737,+ },+ {+ x: 225.86025321570625,+ y: 171.96800693712737,+ },+ ],+ boundingBox: {+ left: 225.86025321570625,+ top: 152.1792611932396,+ right: 396.86960095036636,+ bottom: 171.96800693712737,+ },+ },+ {+ id: "block_2_C25o9D",+ type: "text",+ content:+ "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].",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.908,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 223.64054213475134,+ y: 206.4059457563816,+ },+ {+ x: 1050.9159227357293,+ y: 206.4059457563816,+ },+ {+ x: 1050.9159227357293,+ y: 316.89823061720773,+ },+ {+ x: 223.64054213475134,+ y: 316.89823061720773,+ },+ ],+ boundingBox: {+ left: 223.64054213475134,+ top: 206.4059457563816,+ right: 1050.9159227357293,+ bottom: 316.89823061720773,+ },+ },+ {+ id: "block_2_Cw1VyU",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.9,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 223.69928568819142,+ y: 331.227654822787,+ },+ {+ x: 1049.6158961832089,+ y: 331.227654822787,+ },+ {+ x: 1049.6158961832089,+ y: 511.80734250061494,+ },+ {+ x: 223.69928568819142,+ y: 511.80734250061494,+ },+ ],+ boundingBox: {+ left: 223.69928568819142,+ top: 331.227654822787,+ right: 1049.6158961832089,+ bottom: 511.80734250061494,+ },+ },+ {+ id: "block_2_FR7zlH",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.959,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 223.38852708357095,+ y: 525.5238181666324,+ },+ {+ x: 1052.1732525233804,+ y: 525.5238181666324,+ },+ {+ x: 1052.1732525233804,+ y: 613.7107948647406,+ },+ {+ x: 223.38852708357095,+ y: 613.7107948647406,+ },+ ],+ boundingBox: {+ left: 223.38852708357095,+ top: 525.5238181666324,+ right: 1052.1732525233804,+ bottom: 613.7107948647406,+ },+ },+ {+ id: "block_2_ZyhlFh",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.991,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 223.20226126343667,+ y: 627.2328828797304,+ },+ {+ x: 1052.7354108156078,+ y: 627.2328828797304,+ },+ {+ x: 1052.7354108156078,+ y: 716.0174654623619,+ },+ {+ x: 223.20226126343667,+ y: 716.0174654623619,+ },+ ],+ boundingBox: {+ left: 223.20226126343667,+ top: 627.2328828797304,+ right: 1052.7354108156078,+ bottom: 716.0174654623619,+ },+ },+ {+ id: "block_2_MZBXjP",+ type: "section_heading",+ content: "### 2 Background",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.994,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 224.22355178498873,+ y: 757.4257287333783,+ },+ {+ x: 392.45446198178036,+ y: 757.4257287333783,+ },+ {+ x: 392.45446198178036,+ y: 781.2853567654029,+ },+ {+ x: 224.22355178498873,+ y: 781.2853567654029,+ },+ ],+ boundingBox: {+ left: 224.22355178498873,+ top: 757.4257287333783,+ right: 392.45446198178036,+ bottom: 781.2853567654029,+ },+ },+ {+ id: "block_2_JeOnOk",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.893,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 223.30221050847186,+ y: 810.9956032315591,+ },+ {+ x: 1051.187440078624,+ y: 810.9956032315591,+ },+ {+ x: 1051.187440078624,+ y: 1010.7095232511822,+ },+ {+ x: 223.30221050847186,+ y: 1010.7095232511822,+ },+ ],+ boundingBox: {+ left: 223.30221050847186,+ top: 810.9956032315591,+ right: 1051.187440078624,+ bottom: 1010.7095232511822,+ },+ },+ {+ id: "block_2_tEzlrD",+ type: "text",+ content:+ "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].",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.984,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 224.00045882176306,+ y: 1028.0413251030714,+ },+ {+ x: 1051.4467448213675,+ y: 1028.0413251030714,+ },+ {+ x: 1051.4467448213675,+ y: 1116.9915041815966,+ },+ {+ x: 224.00045882176306,+ y: 1116.9915041815966,+ },+ ],+ boundingBox: {+ left: 224.00045882176306,+ top: 1028.0413251030714,+ right: 1051.4467448213675,+ bottom: 1116.9915041815966,+ },+ },+ {+ id: "block_2_AFJ4ch",+ type: "text",+ content:+ "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].",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.963,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 224.05524984763485,+ y: 1129.9793457949072,+ },+ {+ x: 1052.8165441359918,+ y: 1129.9793457949072,+ },+ {+ x: 1052.8165441359918,+ y: 1196.1117767678168,+ },+ {+ x: 224.05524984763485,+ y: 1196.1117767678168,+ },+ ],+ boundingBox: {+ left: 224.05524984763485,+ top: 1129.9793457949072,+ right: 1052.8165441359918,+ bottom: 1196.1117767678168,+ },+ },+ {+ id: "block_2_CBbJP3",+ type: "text",+ content:+ "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].",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.898,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 222.86987026242443,+ y: 1210.5673043387276,+ },+ {+ x: 1052.2374396776631,+ y: 1210.5673043387276,+ },+ {+ x: 1052.2374396776631,+ y: 1298.352294004053,+ },+ {+ x: 222.86987026242443,+ y: 1298.352294004053,+ },+ ],+ boundingBox: {+ left: 222.86987026242443,+ top: 1210.5673043387276,+ right: 1052.2374396776631,+ bottom: 1298.352294004053,+ },+ },+ {+ id: "block_2_RlRHBW",+ type: "section_heading",+ content: "### 3 Model Architecture",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.993,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 224.20267675914906,+ y: 1339.2827093368187,+ },+ {+ x: 470.2105250671832,+ y: 1339.2827093368187,+ },+ {+ x: 470.2105250671832,+ y: 1359.0320211424864,+ },+ {+ x: 224.20267675914906,+ y: 1359.0320211424864,+ },+ ],+ boundingBox: {+ left: 224.20267675914906,+ top: 1339.2827093368187,+ right: 470.2105250671832,+ bottom: 1359.0320211424864,+ },+ },+ {+ id: "block_2_OhVaOm",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.619,+ avgOcrConfidence: 0.969,+ },+ polygon: [+ {+ x: 223.9033023806384,+ y: 1394.2295871247027,+ },+ {+ x: 1051.703398767179,+ y: 1394.2295871247027,+ },+ {+ x: 1051.703398767179,+ y: 1505.850527885265,+ },+ {+ x: 223.9033023806384,+ y: 1505.850527885265,+ },+ ],+ boundingBox: {+ left: 223.9033023806384,+ top: 1394.2295871247027,+ right: 1051.703398767179,+ bottom: 1505.850527885265,+ },+ },+ {+ id: "block_2_MzhUlf",+ type: "page_number",+ content: "2",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 631.4816022441336,+ y: 1547.6769732138268,+ },+ {+ x: 642.0810031194757,+ y: 1547.6769732138268,+ },+ {+ x: 642.0810031194757,+ y: 1563.2578182363868,+ },+ {+ x: 631.4816022441336,+ y: 1563.2578182363868,+ },+ ],+ boundingBox: {+ left: 631.4816022441336,+ top: 1547.6769732138268,+ right: 642.0810031194757,+ bottom: 1563.2578182363868,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_3_afwbz8",+ type: "figure",+ content:+ '<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>',+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Picture/Figure/Image/Chart",+ minOcrConfidence: 0.868,+ avgOcrConfidence: 0.987,+ },+ polygon: [+ {+ x: 409.83791490540887,+ y: 150.86351013900642,+ },+ {+ x: 863.1759754932709,+ y: 150.86351013900642,+ },+ {+ x: 863.1759754932709,+ y: 821.7723977798806,+ },+ {+ x: 409.83791490540887,+ y: 821.7723977798806,+ },+ ],+ boundingBox: {+ left: 409.83791490540887,+ top: 150.86351013900642,+ right: 863.1759754932709,+ bottom: 821.7723977798806,+ },+ },+ {+ id: "block_3_1WIk1S",+ type: "text",+ content: "Figure 1: The Transformer - model architecture.",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.989,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 436.4703770101505,+ y: 843.2910397178248,+ },+ {+ x: 836.1937028648209,+ y: 843.2910397178248,+ },+ {+ x: 836.1937028648209,+ y: 863.7018851373429,+ },+ {+ x: 436.4703770101505,+ y: 863.7018851373429,+ },+ ],+ boundingBox: {+ left: 436.4703770101505,+ top: 843.2910397178248,+ right: 836.1937028648209,+ bottom: 863.7018851373429,+ },+ },+ {+ id: "block_3_jyPEOL",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.973,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 222.86804783953366,+ y: 910.1303693154701,+ },+ {+ x: 1051.9256870241932,+ y: 910.1303693154701,+ },+ {+ x: 1051.9256870241932,+ y: 977.3362178945899,+ },+ {+ x: 222.86804783953366,+ y: 977.3362178945899,+ },+ ],+ boundingBox: {+ left: 222.86804783953366,+ top: 910.1303693154701,+ right: 1051.9256870241932,+ bottom: 977.3362178945899,+ },+ },+ {+ id: "block_3_nEQfm1",+ type: "section_heading",+ content: "### 3.1 Encoder and Decoder Stacks",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 223.72352154585568,+ y: 1007.3903008367782,+ },+ {+ x: 527.4041196725664,+ y: 1007.3903008367782,+ },+ {+ x: 527.4041196725664,+ y: 1023.9329030316575,+ },+ {+ x: 223.72352154585568,+ y: 1023.9329030316575,+ },+ ],+ boundingBox: {+ left: 223.72352154585568,+ top: 1007.3903008367782,+ right: 527.4041196725664,+ bottom: 1023.9329030316575,+ },+ },+ {+ id: "block_3_W2U9b2",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.657,+ avgOcrConfidence: 0.984,+ },+ polygon: [+ {+ x: 223.8025010937322,+ y: 1048.091523421438,+ },+ {+ x: 1053.5889674277203,+ y: 1048.091523421438,+ },+ {+ x: 1053.5889674277203,+ y: 1206.3018568225373,+ },+ {+ x: 223.8025010937322,+ y: 1206.3018568225373,+ },+ ],+ boundingBox: {+ left: 223.8025010937322,+ top: 1048.091523421438,+ right: 1053.5889674277203,+ bottom: 1206.3018568225373,+ },+ },+ {+ id: "block_3_8wxg0F",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.633,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 224.16407452882643,+ y: 1233.3413921729066,+ },+ {+ x: 1049.721170689938,+ y: 1233.3413921729066,+ },+ {+ x: 1049.721170689938,+ y: 1391.0596241198086,+ },+ {+ x: 224.16407452882643,+ y: 1391.0596241198086,+ },+ ],+ boundingBox: {+ left: 224.16407452882643,+ top: 1233.3413921729066,+ right: 1049.721170689938,+ bottom: 1391.0596241198086,+ },+ },+ {+ id: "block_3_i0stGS",+ type: "section_heading",+ content: "### 3.2 Attention",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 224.0832962258889,+ y: 1421.7722100279386,+ },+ {+ x: 354.57085797386446,+ y: 1421.7722100279386,+ },+ {+ x: 354.57085797386446,+ y: 1437.668053017523,+ },+ {+ x: 224.0832962258889,+ y: 1437.668053017523,+ },+ ],+ boundingBox: {+ left: 224.0832962258889,+ top: 1421.7722100279386,+ right: 354.57085797386446,+ bottom: 1437.668053017523,+ },+ },+ {+ id: "block_3_LwJLS3",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.986,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.38670466068018,+ y: 1462.3713376611695,+ },+ {+ x: 1052.432178580848,+ y: 1462.3713376611695,+ },+ {+ x: 1052.432178580848,+ y: 1506.3117546138906,+ },+ {+ x: 223.38670466068018,+ y: 1506.3117546138906,+ },+ ],+ boundingBox: {+ left: 223.38670466068018,+ top: 1462.3713376611695,+ right: 1052.432178580848,+ bottom: 1506.3117546138906,+ },+ },+ {+ id: "block_3_gqT8MC",+ type: "page_number",+ content: "3",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.997,+ avgOcrConfidence: 0.997,+ },+ polygon: [+ {+ x: 632.2706403523466,+ y: 1547.236487481827,+ },+ {+ x: 642.0801037419451,+ y: 1547.236487481827,+ },+ {+ x: 642.0801037419451,+ y: 1562.977578012567,+ },+ {+ x: 632.2706403523466,+ y: 1562.977578012567,+ },+ ],+ boundingBox: {+ left: 632.2706403523466,+ top: 1547.236487481827,+ right: 642.0801037419451,+ bottom: 1562.977578012567,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_4_PplY2k",+ type: "header",+ content: "Scaled Dot-Product Attention",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Header",+ minOcrConfidence: 0.993,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 307.9120037329458,+ y: 148.57123934236685,+ },+ {+ x: 554.1308270753735,+ y: 148.57123934236685,+ },+ {+ x: 554.1308270753735,+ y: 164.4924521697195,+ },+ {+ x: 307.9120037329458,+ y: 164.4924521697195,+ },+ ],+ boundingBox: {+ left: 307.9120037329458,+ top: 148.57123934236685,+ right: 554.1308270753735,+ bottom: 164.4924521697195,+ },+ },+ {+ id: "block_4_TZACGH",+ type: "text",+ content: "Multi-Head Attention",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.993,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 756.6973442578839,+ y: 148.30866211339045,+ },+ {+ x: 937.5759876557511,+ y: 148.30866211339045,+ },+ {+ x: 937.5759876557511,+ y: 164.44492071911804,+ },+ {+ x: 756.6973442578839,+ y: 164.44492071911804,+ },+ ],+ boundingBox: {+ left: 756.6973442578839,+ top: 148.30866211339045,+ right: 937.5759876557511,+ bottom: 164.44492071911804,+ },+ },+ {+ id: "block_4_yRQL9Y",+ type: "figure",+ content:+ '<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>',+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Picture/Figure/Image/Chart",+ minOcrConfidence: 0.226,+ avgOcrConfidence: 0.815,+ },+ polygon: [+ {+ x: 364.7714322500855,+ y: 195.77549835434533,+ },+ {+ x: 497.28713766501767,+ y: 195.77549835434533,+ },+ {+ x: 497.28713766501767,+ y: 457.62115733784844,+ },+ {+ x: 364.7714322500855,+ y: 457.62115733784844,+ },+ ],+ boundingBox: {+ left: 364.7714322500855,+ top: 195.77549835434533,+ right: 497.28713766501767,+ bottom: 457.62115733784844,+ },+ },+ {+ id: "block_4_goCdts",+ type: "figure",+ content:+ '<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>',+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Picture/Figure/Image/Chart",+ minOcrConfidence: 0.981,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 723.0441991430129,+ y: 171.2063080421964,+ },+ {+ x: 971.0292342805515,+ y: 171.2063080421964,+ },+ {+ x: 971.0292342805515,+ y: 495.8982404264292,+ },+ {+ x: 723.0441991430129,+ y: 495.8982404264292,+ },+ ],+ boundingBox: {+ left: 723.0441991430129,+ top: 171.2063080421964,+ right: 971.0292342805515,+ bottom: 495.8982404264292,+ },+ },+ {+ id: "block_4_ZQ6XHX",+ type: "text",+ content:+ "Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel.",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.991,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 224.32437673972473,+ y: 572.2067347074809,+ },+ {+ x: 1050.060662039875,+ y: 572.2067347074809,+ },+ {+ x: 1050.060662039875,+ y: 615.706381804961,+ },+ {+ x: 224.32437673972473,+ y: 615.706381804961,+ },+ ],+ boundingBox: {+ left: 224.32437673972473,+ top: 572.2067347074809,+ right: 1050.060662039875,+ bottom: 615.706381804961,+ },+ },+ {+ id: "block_4_seZO33",+ type: "text",+ content:+ "of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.989,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 224.44408862260138,+ y: 661.3754045586836,+ },+ {+ x: 1049.3653012018135,+ y: 661.3754045586836,+ },+ {+ x: 1049.3653012018135,+ y: 705.0281940833071,+ },+ {+ x: 224.44408862260138,+ y: 705.0281940833071,+ },+ ],+ boundingBox: {+ left: 224.44408862260138,+ top: 661.3754045586836,+ right: 1049.3653012018135,+ bottom: 705.0281940833071,+ },+ },+ {+ id: "block_4_CMgLHk",+ type: "section_heading",+ content: "### 3.2.1 Scaled Dot-Product Attention",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.53467593227862,+ y: 732.4767248397483,+ },+ {+ x: 549.2687448097842,+ y: 732.4767248397483,+ },+ {+ x: 549.2687448097842,+ y: 748.6887496431967,+ },+ {+ x: 223.53467593227862,+ y: 748.6887496431967,+ },+ ],+ boundingBox: {+ left: 223.53467593227862,+ top: 732.4767248397483,+ right: 549.2687448097842,+ bottom: 748.6887496431967,+ },+ },+ {+ id: "block_4_fmfLoy",+ type: "text",+ content:+ '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.',+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.594,+ avgOcrConfidence: 0.98,+ },+ polygon: [+ {+ x: 223.39593511428276,+ y: 771.1101458269851,+ },+ {+ x: 1051.4275265436104,+ y: 771.1101458269851,+ },+ {+ x: 1051.4275265436104,+ y: 856.1295272138783,+ },+ {+ x: 223.39593511428276,+ y: 856.1295272138783,+ },+ ],+ boundingBox: {+ left: 223.39593511428276,+ top: 771.1101458269851,+ right: 1051.4275265436104,+ bottom: 856.1295272138783,+ },+ },+ {+ id: "block_4_cDuW6h",+ type: "text",+ content:+ "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:",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.976,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 224.08788778486044,+ y: 873.4355685585424,+ },+ {+ x: 1050.3812191260122,+ y: 873.4355685585424,+ },+ {+ x: 1050.3812191260122,+ y: 938.6725377821385,+ },+ {+ x: 224.08788778486044,+ y: 938.6725377821385,+ },+ ],+ boundingBox: {+ left: 224.08788778486044,+ top: 873.4355685585424,+ right: 1050.3812191260122,+ bottom: 938.6725377821385,+ },+ },+ {+ id: "block_4_VaSWNE",+ type: "text",+ content: "QKT Attention(Q, K, V) = softmax( V Vdk",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Formula",+ minOcrConfidence: 0.908,+ avgOcrConfidence: 0.961,+ },+ polygon: [+ {+ x: 458.52888900868214,+ y: 968.9788274549901,+ },+ {+ x: 816.6205023327013,+ y: 968.9788274549901,+ },+ {+ x: 816.6205023327013,+ y: 1021.9395890773686,+ },+ {+ x: 458.52888900868214,+ y: 1021.9395890773686,+ },+ ],+ boundingBox: {+ left: 458.52888900868214,+ top: 968.9788274549901,+ right: 816.6205023327013,+ bottom: 1021.9395890773686,+ },+ },+ {+ id: "block_4_Wtl7xI",+ type: "text",+ content: "(1)",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 1026.9459968065694,+ y: 986.4570474839747,+ },+ {+ x: 1051.0514920645387,+ y: 986.4570474839747,+ },+ {+ x: 1051.0514920645387,+ y: 1005.8566982871607,+ },+ {+ x: 1026.9459968065694,+ y: 1005.8566982871607,+ },+ ],+ boundingBox: {+ left: 1026.9459968065694,+ top: 986.4570474839747,+ right: 1051.0514920645387,+ bottom: 1005.8566982871607,+ },+ },+ {+ id: "block_4_HVInAp",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.098,+ avgOcrConfidence: 0.981,+ },+ polygon: [+ {+ x: 223.11696240501684,+ y: 1041.6009173859331,+ },+ {+ x: 1052.8067929901345,+ y: 1041.6009173859331,+ },+ {+ x: 1052.8067929901345,+ y: 1180.0422397699572,+ },+ {+ x: 223.11696240501684,+ y: 1180.0422397699572,+ },+ ],+ boundingBox: {+ left: 223.11696240501684,+ top: 1041.6009173859331,+ right: 1052.8067929901345,+ bottom: 1180.0422397699572,+ },+ },+ {+ id: "block_4_6NHlzf",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.58,+ avgOcrConfidence: 0.98,+ },+ polygon: [+ {+ x: 223.18699551324775,+ y: 1194.0708248167111,+ },+ {+ x: 1050.8364934990875,+ y: 1194.0708248167111,+ },+ {+ x: 1050.8364934990875,+ y: 1289.5664457163416,+ },+ {+ x: 223.18699551324775,+ y: 1289.5664457163416,+ },+ ],+ boundingBox: {+ left: 223.18699551324775,+ top: 1194.0708248167111,+ right: 1050.8364934990875,+ bottom: 1289.5664457163416,+ },+ },+ {+ id: "block_4_4VWmvI",+ type: "section_heading",+ content: "### 3.2.2 Multi-Head Attention",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.994,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.5976323594142,+ y: 1315.4335938647278,+ },+ {+ x: 479.8474026422431,+ y: 1315.4335938647278,+ },+ {+ x: 479.8474026422431,+ y: 1331.4542616650574,+ },+ {+ x: 223.5976323594142,+ y: 1331.4542616650574,+ },+ ],+ boundingBox: {+ left: 223.5976323594142,+ top: 1315.4335938647278,+ right: 479.8474026422431,+ bottom: 1331.4542616650574,+ },+ },+ {+ id: "block_4_n7aPpb",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.619,+ avgOcrConfidence: 0.979,+ },+ polygon: [+ {+ x: 223.83094982509195,+ y: 1354.33461159154,+ },+ {+ x: 1052.0098498267848,+ y: 1354.33461159154,+ },+ {+ x: 1052.0098498267848,+ y: 1442.8801044664883,+ },+ {+ x: 223.83094982509195,+ y: 1442.8801044664883,+ },+ ],+ boundingBox: {+ left: 223.83094982509195,+ top: 1354.33461159154,+ right: 1052.0098498267848,+ bottom: 1442.8801044664883,+ },+ },+ {+ id: "block_4_rfqNPC",+ type: "text",+ content:+ "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-",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.105,+ avgOcrConfidence: 0.921,+ },+ polygon: [+ {+ x: 224.42529636577967,+ y: 1459.9841341864794,+ },+ {+ x: 1049.4534401998033,+ y: 1459.9841341864794,+ },+ {+ x: 1049.4534401998033,+ y: 1506.815978659723,+ },+ {+ x: 224.42529636577967,+ y: 1506.815978659723,+ },+ ],+ boundingBox: {+ left: 224.42529636577967,+ top: 1459.9841341864794,+ right: 1049.4534401998033,+ bottom: 1506.815978659723,+ },+ },+ {+ id: "block_4_35BhDQ",+ type: "page_number",+ content: "4",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.996,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 631.2688757903385,+ y: 1548.1330857241064,+ },+ {+ x: 642.0564832478544,+ y: 1548.1330857241064,+ },+ {+ x: 642.0564832478544,+ y: 1562.0727401962854,+ },+ {+ x: 631.2688757903385,+ y: 1562.0727401962854,+ },+ ],+ boundingBox: {+ left: 631.2688757903385,+ top: 1548.1330857241064,+ right: 642.0564832478544,+ bottom: 1562.0727401962854,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_5_Zc8VSW",+ type: "text",+ content:+ "output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure 2.",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.988,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 224.67903916853186,+ y: 155.68632458564932,+ },+ {+ x: 1049.4719957783275,+ y: 155.68632458564932,+ },+ {+ x: 1049.4719957783275,+ y: 199.30535079841326,+ },+ {+ x: 224.67903916853186,+ y: 199.30535079841326,+ },+ ],+ boundingBox: {+ left: 224.67903916853186,+ top: 155.68632458564932,+ right: 1049.4719957783275,+ bottom: 199.30535079841326,+ },+ },+ {+ id: "block_5_P72mUL",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 224.58133836732293,+ y: 212.29537068990837,+ },+ {+ x: 1049.5524663994781,+ y: 212.29537068990837,+ },+ {+ x: 1049.5524663994781,+ y: 255.9039790504857,+ },+ {+ x: 224.58133836732293,+ y: 255.9039790504857,+ },+ ],+ boundingBox: {+ left: 224.58133836732293,+ top: 212.29537068990837,+ right: 1049.5524663994781,+ bottom: 255.9039790504857,+ },+ },+ {+ id: "block_5_zTpvNY",+ type: "text",+ content:+ "MultiHead(Q,K,V)=Concat(head1, ... , headh)W\u00ba where head; = Attention(Qw?, KWK,VW)",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Formula",+ minOcrConfidence: 0.581,+ avgOcrConfidence: 0.796,+ },+ polygon: [+ {+ x: 388.73733464818804,+ y: 302.5467395065422,+ },+ {+ x: 883.3280911410811,+ y: 302.5467395065422,+ },+ {+ x: 883.3280911410811,+ y: 364.6030674267532,+ },+ {+ x: 388.73733464818804,+ y: 364.6030674267532,+ },+ ],+ boundingBox: {+ left: 388.73733464818804,+ top: 302.5467395065422,+ right: 883.3280911410811,+ bottom: 364.6030674267532,+ },+ },+ {+ id: "block_5_cOSQOc",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.252,+ avgOcrConfidence: 0.682,+ },+ polygon: [+ {+ x: 223.51567066498916,+ y: 424.5787134959285,+ },+ {+ x: 1047.1388211215499,+ y: 424.5787134959285,+ },+ {+ x: 1047.1388211215499,+ y: 472.1556711698833,+ },+ {+ x: 223.51567066498916,+ y: 472.1556711698833,+ },+ ],+ boundingBox: {+ left: 223.51567066498916,+ top: 424.5787134959285,+ right: 1047.1388211215499,+ bottom: 472.1556711698833,+ },+ },+ {+ id: "block_5_4oR3J2",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.557,+ avgOcrConfidence: 0.98,+ },+ polygon: [+ {+ x: 223.83189653828197,+ y: 488.323372747665,+ },+ {+ x: 1049.9097559573877,+ y: 488.323372747665,+ },+ {+ x: 1049.9097559573877,+ y: 555.0531728357302,+ },+ {+ x: 223.83189653828197,+ y: 555.0531728357302,+ },+ ],+ boundingBox: {+ left: 223.83189653828197,+ top: 488.323372747665,+ right: 1049.9097559573877,+ bottom: 555.0531728357302,+ },+ },+ {+ id: "block_5_oGR7Tp",+ type: "section_heading",+ content: "### 3.2.3 Applications of Attention in our Model",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.994,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 223.9031130380004,+ y: 584.1135347409356,+ },+ {+ x: 629.6546824657133,+ y: 584.1135347409356,+ },+ {+ x: 629.6546824657133,+ y: 605.02614180486,+ },+ {+ x: 223.9031130380004,+ y: 605.02614180486,+ },+ ],+ boundingBox: {+ left: 223.9031130380004,+ top: 584.1135347409356,+ right: 629.6546824657133,+ bottom: 605.02614180486,+ },+ },+ {+ id: "block_5_b34egv",+ type: "text",+ content:+ "The Transformer uses multi-head attention in three different ways:",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.3985859112148,+ y: 623.9660812033746,+ },+ {+ x: 775.7513199409428,+ y: 623.9660812033746,+ },+ {+ x: 775.7513199409428,+ y: 644.7702005429376,+ },+ {+ x: 223.3985859112148,+ y: 644.7702005429376,+ },+ ],+ boundingBox: {+ left: 223.3985859112148,+ top: 623.9660812033746,+ right: 775.7513199409428,+ bottom: 644.7702005429376,+ },+ },+ {+ id: "block_5_NSYaLO",+ type: "text",+ content:+ '\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].',+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.586,+ avgOcrConfidence: 0.984,+ },+ polygon: [+ {+ x: 281.7719981618171,+ y: 667.4162908568419,+ },+ {+ x: 1052.1352893244612,+ y: 667.4162908568419,+ },+ {+ x: 1052.1352893244612,+ y: 778.3123385207098,+ },+ {+ x: 281.7719981618171,+ y: 778.3123385207098,+ },+ ],+ boundingBox: {+ left: 281.7719981618171,+ top: 667.4162908568419,+ right: 1052.1352893244612,+ bottom: 778.3123385207098,+ },+ },+ {+ id: "block_5_ZbEUX6",+ type: "text",+ content:+ "\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.",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.407,+ avgOcrConfidence: 0.983,+ },+ polygon: [+ {+ x: 282.1731915439132,+ y: 791.5420637202442,+ },+ {+ x: 1049.6795153095775,+ y: 791.5420637202442,+ },+ {+ x: 1049.6795153095775,+ y: 876.9418387735697,+ },+ {+ x: 282.1731915439132,+ y: 876.9418387735697,+ },+ ],+ boundingBox: {+ left: 282.1731915439132,+ top: 791.5420637202442,+ right: 1049.6795153095775,+ bottom: 876.9418387735697,+ },+ },+ {+ id: "block_5_wkxEH8",+ type: "text",+ content:+ "\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.",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.543,+ avgOcrConfidence: 0.985,+ },+ polygon: [+ {+ x: 281.12820952478114,+ y: 893.687589086088,+ },+ {+ x: 1049.8325041610829,+ y: 893.687589086088,+ },+ {+ x: 1049.8325041610829,+ y: 1005.0602061336201,+ },+ {+ x: 281.12820952478114,+ y: 1005.0602061336201,+ },+ ],+ boundingBox: {+ left: 281.12820952478114,+ top: 893.687589086088,+ right: 1049.8325041610829,+ bottom: 1005.0602061336201,+ },+ },+ {+ id: "block_5_vVMF0e",+ type: "section_heading",+ content: "### 3.3 Position-wise Feed-Forward Networks",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.59919443617773,+ y: 1037.180243872162,+ },+ {+ x: 609.3837069768975,+ y: 1037.180243872162,+ },+ {+ x: 609.3837069768975,+ y: 1053.935843790384,+ },+ {+ x: 223.59919443617773,+ y: 1053.935843790384,+ },+ ],+ boundingBox: {+ left: 223.59919443617773,+ top: 1037.180243872162,+ right: 609.3837069768975,+ bottom: 1053.935843790384,+ },+ },+ {+ id: "block_5_WtW3Xc",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.986,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.937928415563,+ y: 1079.1571798109471,+ },+ {+ x: 1049.736412772297,+ y: 1079.1571798109471,+ },+ {+ x: 1049.736412772297,+ y: 1142.9025967246607,+ },+ {+ x: 223.937928415563,+ y: 1142.9025967246607,+ },+ ],+ boundingBox: {+ left: 223.937928415563,+ top: 1079.1571798109471,+ right: 1049.736412772297,+ bottom: 1142.9025967246607,+ },+ },+ {+ id: "block_5_TCB4QK",+ type: "text",+ content: "FFN(x)=max(0,xW1+b1)W2+b2",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Formula",+ minOcrConfidence: 0.668,+ avgOcrConfidence: 0.668,+ },+ polygon: [+ {+ x: 471.6477776965956,+ y: 1184.1576702146604,+ },+ {+ x: 801.1487473536581,+ y: 1184.1576702146604,+ },+ {+ x: 801.1487473536581,+ y: 1206.444581397494,+ },+ {+ x: 471.6477776965956,+ y: 1206.444581397494,+ },+ ],+ boundingBox: {+ left: 471.6477776965956,+ top: 1184.1576702146604,+ right: 801.1487473536581,+ bottom: 1206.444581397494,+ },+ },+ {+ id: "block_5_olGJjx",+ type: "text",+ content: "(2)",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.997,+ avgOcrConfidence: 0.997,+ },+ polygon: [+ {+ x: 1026.9936164800267,+ y: 1185.5856736262042,+ },+ {+ x: 1051.1806237436558,+ y: 1185.5856736262042,+ },+ {+ x: 1051.1806237436558,+ y: 1204.3962422421102,+ },+ {+ x: 1026.9936164800267,+ y: 1204.3962422421102,+ },+ ],+ boundingBox: {+ left: 1026.9936164800267,+ top: 1185.5856736262042,+ right: 1051.1806237436558,+ bottom: 1204.3962422421102,+ },+ },+ {+ id: "block_5_KTjDsL",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.881,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 222.78797957148865,+ y: 1230.1093008858818,+ },+ {+ x: 1052.541145269018,+ y: 1230.1093008858818,+ },+ {+ x: 1052.541145269018,+ y: 1320.3967533541802,+ },+ {+ x: 222.78797957148865,+ y: 1320.3967533541802,+ },+ ],+ boundingBox: {+ left: 222.78797957148865,+ top: 1230.1093008858818,+ right: 1052.541145269018,+ bottom: 1320.3967533541802,+ },+ },+ {+ id: "block_5_Pwzvu2",+ type: "section_heading",+ content: "### 3.4 Embeddings and Softmax",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.997,+ },+ polygon: [+ {+ x: 223.80512822283447,+ y: 1351.0096120045598,+ },+ {+ x: 499.655388045485,+ y: 1351.0096120045598,+ },+ {+ x: 499.655388045485,+ y: 1371.2419333206979,+ },+ {+ x: 223.80512822283447,+ y: 1371.2419333206979,+ },+ ],+ boundingBox: {+ left: 223.80512822283447,+ top: 1351.0096120045598,+ right: 499.655388045485,+ bottom: 1371.2419333206979,+ },+ },+ {+ id: "block_5_6y9ZGB",+ type: "text",+ content:+ "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 -",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.275,+ avgOcrConfidence: 0.983,+ },+ polygon: [+ {+ x: 224.49331770848184,+ y: 1394.318801822519,+ },+ {+ x: 1052.2855327077154,+ y: 1394.318801822519,+ },+ {+ x: 1052.2855327077154,+ y: 1505.8341434450076,+ },+ {+ x: 224.49331770848184,+ y: 1505.8341434450076,+ },+ ],+ boundingBox: {+ left: 224.49331770848184,+ top: 1394.318801822519,+ right: 1052.2855327077154,+ bottom: 1505.8341434450076,+ },+ },+ {+ id: "block_5_o8MKrc",+ type: "page_number",+ content: "5",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 631.5606054598397,+ y: 1547.4356578740858,+ },+ {+ x: 641.9868998283888,+ y: 1547.4356578740858,+ },+ {+ x: 641.9868998283888,+ y: 1563.1716341864794,+ },+ {+ x: 631.5606054598397,+ y: 1563.1716341864794,+ },+ ],+ boundingBox: {+ left: 631.5606054598397,+ top: 1547.4356578740858,+ right: 641.9868998283888,+ bottom: 1563.1716341864794,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_6_YmUPFZ",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.977,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 222.7798615058843,+ y: 148.2273318355245,+ },+ {+ x: 1048.906618661254,+ y: 148.2273318355245,+ },+ {+ x: 1048.906618661254,+ y: 214.40370720311216,+ },+ {+ x: 222.7798615058843,+ y: 214.40370720311216,+ },+ ],+ boundingBox: {+ left: 222.7798615058843,+ top: 148.2273318355245,+ right: 1048.906618661254,+ bottom: 214.40370720311216,+ },+ },+ {+ id: "block_6_kibLxu",+ type: "table",+ content:+ "| 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) [ ] |",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Table",+ minOcrConfidence: 0.256,+ avgOcrConfidence: 0.856,+ },+ polygon: [+ {+ x: 246.08119491243013,+ y: 233.8958637983279,+ },+ {+ x: 1028.2713006012632,+ y: 233.8958637983279,+ },+ {+ x: 1028.2713006012632,+ y: 389.94297754674926,+ },+ {+ x: 246.08119491243013,+ y: 389.94297754674926,+ },+ ],+ boundingBox: {+ left: 246.08119491243013,+ top: 233.8958637983279,+ right: 1028.2713006012632,+ bottom: 389.94297754674926,+ },+ },+ {+ id: "block_6_tUIpoY",+ type: "section_heading",+ content: "### 3.5 Positional Encoding",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 224.00651778617916,+ y: 445.9595083078944,+ },+ {+ x: 448.20427163674015,+ y: 445.9595083078944,+ },+ {+ x: 448.20427163674015,+ y: 466.69903696390026,+ },+ {+ x: 224.00651778617916,+ y: 466.69903696390026,+ },+ ],+ boundingBox: {+ left: 224.00651778617916,+ top: 445.9595083078944,+ right: 448.20427163674015,+ bottom: 466.69903696390026,+ },+ },+ {+ id: "block_6_mmxGrc",+ type: "text",+ content:+ '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].',+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.912,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.83698512167825,+ y: 487.3354288832586,+ },+ {+ x: 1050.4121766473256,+ y: 487.3354288832586,+ },+ {+ x: 1050.4121766473256,+ y: 620.7750930786133,+ },+ {+ x: 223.83698512167825,+ y: 620.7750930786133,+ },+ ],+ boundingBox: {+ left: 223.83698512167825,+ top: 487.3354288832586,+ right: 1050.4121766473256,+ bottom: 620.7750930786133,+ },+ },+ {+ id: "block_6_NG2aN8",+ type: "text",+ content:+ "In this work, we use sine and cosine functions of different frequencies:",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 224.39521455416715,+ y: 635.0555533789154,+ },+ {+ x: 810.5588871197108,+ y: 635.0555533789154,+ },+ {+ x: 810.5588871197108,+ y: 655.9754529393705,+ },+ {+ x: 224.39521455416715,+ y: 655.9754529393705,+ },+ ],+ boundingBox: {+ left: 224.39521455416715,+ top: 635.0555533789154,+ right: 810.5588871197108,+ bottom: 655.9754529393705,+ },+ },+ {+ id: "block_6_ktOzAP",+ type: "text",+ content:+ "PE(pos,2i) = sin(pos/100002i/dmodel ) PE(pos,2i+1) = cos(pos/100002i/dmodel) )",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Formula",+ minOcrConfidence: 0.646,+ avgOcrConfidence: 0.856,+ },+ polygon: [+ {+ x: 470.62755222738224,+ y: 700.6432727440855,+ },+ {+ x: 804.2361684089159,+ y: 700.6432727440855,+ },+ {+ x: 804.2361684089159,+ y: 763.5065343469606,+ },+ {+ x: 470.62755222738224,+ y: 763.5065343469606,+ },+ ],+ boundingBox: {+ left: 470.62755222738224,+ top: 700.6432727440855,+ right: 804.2361684089159,+ bottom: 763.5065343469606,+ },+ },+ {+ id: "block_6_L0vHNu",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.291,+ avgOcrConfidence: 0.967,+ },+ polygon: [+ {+ x: 223.63699196028884,+ y: 787.3148307800293,+ },+ {+ x: 1050.8335586881985,+ y: 787.3148307800293,+ },+ {+ x: 1050.8335586881985,+ y: 900.202535012611,+ },+ {+ x: 223.63699196028884,+ y: 900.202535012611,+ },+ ],+ boundingBox: {+ left: 223.63699196028884,+ top: 787.3148307800293,+ right: 1050.8335586881985,+ bottom: 900.202535012611,+ },+ },+ {+ id: "block_6_Sai49H",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.868,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 223.15007369883736,+ y: 912.2991767252298,+ },+ {+ x: 1049.522644933993,+ y: 912.2991767252298,+ },+ {+ x: 1049.522644933993,+ y: 1000.5864015736975,+ },+ {+ x: 223.15007369883736,+ y: 1000.5864015736975,+ },+ ],+ boundingBox: {+ left: 223.15007369883736,+ top: 912.2991767252298,+ right: 1049.522644933993,+ bottom: 1000.5864015736975,+ },+ },+ {+ id: "block_6_545oKE",+ type: "section_heading",+ content: "### 4 Why Self-Attention",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.44270274586924,+ y: 1036.185907234823,+ },+ {+ x: 468.14631162768734,+ y: 1036.185907234823,+ },+ {+ x: 468.14631162768734,+ y: 1059.806398205291,+ },+ {+ x: 223.44270274586924,+ y: 1059.806398205291,+ },+ ],+ boundingBox: {+ left: 223.44270274586924,+ top: 1036.185907234823,+ right: 468.14631162768734,+ bottom: 1059.806398205291,+ },+ },+ {+ id: "block_6_rdkytl",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.298,+ avgOcrConfidence: 0.936,+ },+ polygon: [+ {+ x: 222.55295802206888,+ y: 1087.3066867455505,+ },+ {+ x: 1052.7677884067061,+ y: 1087.3066867455505,+ },+ {+ x: 1052.7677884067061,+ y: 1195.3768446499244,+ },+ {+ x: 222.55295802206888,+ y: 1195.3768446499244,+ },+ ],+ boundingBox: {+ left: 222.55295802206888,+ top: 1087.3066867455505,+ right: 1052.7677884067061,+ bottom: 1195.3768446499244,+ },+ },+ {+ id: "block_6_y2UJTk",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.43593374656064,+ y: 1212.4905345601246,+ },+ {+ x: 1048.7435946499345,+ y: 1212.4905345601246,+ },+ {+ x: 1048.7435946499345,+ y: 1255.7911059730932,+ },+ {+ x: 223.43593374656064,+ y: 1255.7911059730932,+ },+ ],+ boundingBox: {+ left: 223.43593374656064,+ top: 1212.4905345601246,+ right: 1048.7435946499345,+ bottom: 1255.7911059730932,+ },+ },+ {+ id: "block_6_OGHshO",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.983,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 222.87737296445525,+ y: 1268.8657945905413,+ },+ {+ x: 1049.749950770914,+ y: 1268.8657945905413,+ },+ {+ x: 1049.749950770914,+ y: 1426.1352065236945,+ },+ {+ x: 222.87737296445525,+ y: 1426.1352065236945,+ },+ ],+ boundingBox: {+ left: 222.87737296445525,+ top: 1268.8657945905413,+ right: 1049.749950770914,+ bottom: 1426.1352065236945,+ },+ },+ {+ id: "block_6_zgN3wO",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.963,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 223.4352473794979,+ y: 1439.235182109632,+ },+ {+ x: 1051.6017217705719,+ y: 1439.235182109632,+ },+ {+ x: 1051.6017217705719,+ y: 1506.1062388025728,+ },+ {+ x: 223.4352473794979,+ y: 1506.1062388025728,+ },+ ],+ boundingBox: {+ left: 223.4352473794979,+ top: 1439.235182109632,+ right: 1051.6017217705719,+ bottom: 1506.1062388025728,+ },+ },+ {+ id: "block_6_aNgpKT",+ type: "page_number",+ content: "6",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.993,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 631.7702550957673,+ y: 1548.2886905526757,+ },+ {+ x: 642.7105200551722,+ y: 1548.2886905526757,+ },+ {+ x: 642.7105200551722,+ y: 1563.5418467700931,+ },+ {+ x: 631.7702550957673,+ y: 1563.5418467700931,+ },+ ],+ boundingBox: {+ left: 631.7702550957673,+ top: 1548.2886905526757,+ right: 642.7105200551722,+ bottom: 1563.5418467700931,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_7_u723hy",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.909,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 223.89144479793353,+ y: 155.39061148363845,+ },+ {+ x: 1050.0338700565978,+ y: 155.39061148363845,+ },+ {+ x: 1050.0338700565978,+ y: 290.11272512163436,+ },+ {+ x: 223.89144479793353,+ y: 290.11272512163436,+ },+ ],+ boundingBox: {+ left: 223.89144479793353,+ top: 155.39061148363845,+ right: 1050.0338700565978,+ bottom: 290.11272512163436,+ },+ },+ {+ id: "block_7_SLgoxa",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.525,+ avgOcrConfidence: 0.977,+ },+ polygon: [+ {+ x: 223.84822734080961,+ y: 303.4973448416344,+ },+ {+ x: 1051.7048188369638,+ y: 303.4973448416344,+ },+ {+ x: 1051.7048188369638,+ y: 482.7421505003047,+ },+ {+ x: 223.84822734080961,+ y: 482.7421505003047,+ },+ ],+ boundingBox: {+ left: 223.84822734080961,+ top: 303.4973448416344,+ right: 1051.7048188369638,+ bottom: 482.7421505003047,+ },+ },+ {+ id: "block_7_lGN5L0",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.94,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.7218884656029,+ y: 496.4417208334557,+ },+ {+ x: 1049.5183847246378,+ y: 496.4417208334557,+ },+ {+ x: 1049.5183847246378,+ y: 581.3287481437052,+ },+ {+ x: 223.7218884656029,+ y: 581.3287481437052,+ },+ ],+ boundingBox: {+ left: 223.7218884656029,+ top: 496.4417208334557,+ right: 1049.5183847246378,+ bottom: 581.3287481437052,+ },+ },+ {+ id: "block_7_FOtl5B",+ type: "heading",+ content: "# 5 Training",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Heading",+ minOcrConfidence: 0.989,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 224.4122553915873,+ y: 625.3390120599503,+ },+ {+ x: 354.91415984439146,+ y: 625.3390120599503,+ },+ {+ x: 354.91415984439146,+ y: 649.7166914688913,+ },+ {+ x: 224.4122553915873,+ y: 649.7166914688913,+ },+ ],+ boundingBox: {+ left: 224.4122553915873,+ top: 625.3390120599503,+ right: 354.91415984439146,+ bottom: 649.7166914688913,+ },+ },+ {+ id: "block_7_3jYBCf",+ type: "text",+ content: "This section describes the training regime for our models.",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 222.4527957665659,+ y: 679.1303132709704,+ },+ {+ x: 701.988161741382,+ y: 679.1303132709704,+ },+ {+ x: 701.988161741382,+ y: 699.7081758025894,+ },+ {+ x: 222.4527957665659,+ y: 699.7081758025894,+ },+ ],+ boundingBox: {+ left: 222.4527957665659,+ top: 679.1303132709704,+ right: 701.988161741382,+ bottom: 699.7081758025894,+ },+ },+ {+ id: "block_7_PIafds",+ type: "section_heading",+ content: "### 5.1 Training Data and Batching",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.68002007477475,+ y: 735.0401794318866,+ },+ {+ x: 519.6398407873446,+ y: 735.0401794318866,+ },+ {+ x: 519.6398407873446,+ y: 755.8565634247055,+ },+ {+ x: 223.68002007477475,+ y: 755.8565634247055,+ },+ ],+ boundingBox: {+ left: 223.68002007477475,+ top: 735.0401794318866,+ right: 519.6398407873446,+ bottom: 755.8565634247055,+ },+ },+ {+ id: "block_7_8RhsHH",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.911,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.70165247116648,+ y: 778.8621643467953,+ },+ {+ x: 1052.1871692072737,+ y: 778.8621643467953,+ },+ {+ x: 1052.1871692072737,+ y: 935.23512009929,+ },+ {+ x: 223.70165247116648,+ y: 935.23512009929,+ },+ ],+ boundingBox: {+ left: 223.70165247116648,+ top: 778.8621643467953,+ right: 1052.1871692072737,+ bottom: 935.23512009929,+ },+ },+ {+ id: "block_7_2fOgoW",+ type: "section_heading",+ content: "### 5.2 Hardware and Schedule",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.994,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 223.9209349138023,+ y: 971.4598863071069,+ },+ {+ x: 484.7486314982394,+ y: 971.4598863071069,+ },+ {+ x: 484.7486314982394,+ y: 987.6652342143811,+ },+ {+ x: 223.9209349138023,+ y: 987.6652342143811,+ },+ ],+ boundingBox: {+ left: 223.9209349138023,+ top: 971.4598863071069,+ right: 484.7486314982394,+ bottom: 987.6652342143811,+ },+ },+ {+ id: "block_7_7vykWe",+ type: "text",+ content:+ "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).",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.961,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 223.2459757449853,+ y: 1014.9955223485043,+ },+ {+ x: 1049.3973947789548,+ y: 1014.9955223485043,+ },+ {+ x: 1049.3973947789548,+ y: 1126.7015106660083,+ },+ {+ x: 223.2459757449853,+ y: 1126.7015106660083,+ },+ ],+ boundingBox: {+ left: 223.2459757449853,+ top: 1014.9955223485043,+ right: 1049.3973947789548,+ bottom: 1126.7015106660083,+ },+ },+ {+ id: "block_7_Xjy6qb",+ type: "section_heading",+ content: "### 5.3 Optimizer",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.994,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.84361211400832,+ y: 1161.1210525053784,+ },+ {+ x: 361.9454223744191,+ y: 1161.1210525053784,+ },+ {+ x: 361.9454223744191,+ y: 1181.9203891037102,+ },+ {+ x: 223.84361211400832,+ y: 1181.9203891037102,+ },+ ],+ boundingBox: {+ left: 223.84361211400832,+ top: 1161.1210525053784,+ right: 361.9454223744191,+ bottom: 1181.9203891037102,+ },+ },+ {+ id: "block_7_uZS3FC",+ type: "text",+ content:+ "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:",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.472,+ avgOcrConfidence: 0.947,+ },+ polygon: [+ {+ x: 223.18536243299496,+ y: 1203.7906809068263,+ },+ {+ x: 1049.5936484232436,+ y: 1203.7906809068263,+ },+ {+ x: 1049.5936484232436,+ y: 1249.0720648514596,+ },+ {+ x: 223.18536243299496,+ y: 1249.0720648514596,+ },+ ],+ boundingBox: {+ left: 223.18536243299496,+ top: 1203.7906809068263,+ right: 1049.5936484232436,+ bottom: 1249.0720648514596,+ },+ },+ {+ id: "block_7_qvJczg",+ type: "text",+ content:+ "lrate = dmodel . min(step_num-0.5, step_num . warmup_steps-1.5)",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Formula",+ minOcrConfidence: 0.563,+ avgOcrConfidence: 0.786,+ },+ polygon: [+ {+ x: 338.51696905428474,+ y: 1286.921258338412,+ },+ {+ x: 933.735361586522,+ y: 1286.921258338412,+ },+ {+ x: 933.735361586522,+ y: 1314.0637410099346,+ },+ {+ x: 338.51696905428474,+ y: 1314.0637410099346,+ },+ ],+ boundingBox: {+ left: 338.51696905428474,+ top: 1286.921258338412,+ right: 933.735361586522,+ bottom: 1314.0637410099346,+ },+ },+ {+ id: "block_7_ZRnl1T",+ type: "text",+ content: "(3)",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 1026.6387883764114,+ y: 1291.0368781986094,+ },+ {+ x: 1051.2767151324417,+ y: 1291.0368781986094,+ },+ {+ x: 1051.2767151324417,+ y: 1311.080825805664,+ },+ {+ x: 1026.6387883764114,+ y: 1311.080825805664,+ },+ ],+ boundingBox: {+ left: 1026.6387883764114,+ top: 1291.0368781986094,+ right: 1051.2767151324417,+ bottom: 1311.080825805664,+ },+ },+ {+ id: "block_7_M71nL9",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.916,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 222.72840764400732,+ y: 1340.2761936044335,+ },+ {+ x: 1052.0266066502481,+ y: 1340.2761936044335,+ },+ {+ x: 1052.0266066502481,+ y: 1406.6737115616188,+ },+ {+ x: 222.72840764400732,+ y: 1406.6737115616188,+ },+ ],+ boundingBox: {+ left: 222.72840764400732,+ top: 1340.2761936044335,+ right: 1052.0266066502481,+ bottom: 1406.6737115616188,+ },+ },+ {+ id: "block_7_ACakMa",+ type: "section_heading",+ content: "### 5.4 Regularization",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.993,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 223.81116351942077,+ y: 1441.41800626597,+ },+ {+ x: 402.1996435457773,+ y: 1441.41800626597,+ },+ {+ x: 402.1996435457773,+ y: 1461.9926013803124,+ },+ {+ x: 223.81116351942077,+ y: 1461.9926013803124,+ },+ ],+ boundingBox: {+ left: 223.81116351942077,+ top: 1441.41800626597,+ right: 402.1996435457773,+ bottom: 1461.9926013803124,+ },+ },+ {+ id: "block_7_rR8JeL",+ type: "text",+ content: "We employ three types of regularization during training:",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 222.88627206844134,+ y: 1484.7892296583134,+ },+ {+ x: 690.987449144795,+ y: 1484.7892296583134,+ },+ {+ x: 690.987449144795,+ y: 1505.950728681751,+ },+ {+ x: 222.88627206844134,+ y: 1505.950728681751,+ },+ ],+ boundingBox: {+ left: 222.88627206844134,+ top: 1484.7892296583134,+ right: 690.987449144795,+ bottom: 1505.950728681751,+ },+ },+ {+ id: "block_7_I7j7Uy",+ type: "page_number",+ content: "7",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.996,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 631.8865114755004,+ y: 1547.4189893105872,+ },+ {+ x: 642.4512153124288,+ y: 1547.4189893105872,+ },+ {+ x: 642.4512153124288,+ y: 1562.541448836936,+ },+ {+ x: 631.8865114755004,+ y: 1562.541448836936,+ },+ ],+ boundingBox: {+ left: 631.8865114755004,+ top: 1547.4189893105872,+ right: 642.4512153124288,+ bottom: 1562.541448836936,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_8_8rtbBp",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.963,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 222.40285664579295,+ y: 148.11078211418666,+ },+ {+ x: 1048.695596291201,+ y: 148.11078211418666,+ },+ {+ x: 1048.695596291201,+ y: 191.8824890538266,+ },+ {+ x: 222.40285664579295,+ y: 191.8824890538266,+ },+ ],+ boundingBox: {+ left: 222.40285664579295,+ top: 148.11078211418666,+ right: 1048.695596291201,+ bottom: 191.8824890538266,+ },+ },+ {+ id: "block_8_M3V7h9",+ type: "table",+ content:+ "| 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 | |",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Table",+ minOcrConfidence: 0.141,+ avgOcrConfidence: 0.893,+ },+ polygon: [+ {+ x: 271.150136516042,+ y: 195.3426247575229,+ },+ {+ x: 1004.1704442379248,+ y: 195.3426247575229,+ },+ {+ x: 1004.1704442379248,+ y: 508.6132290201976,+ },+ {+ x: 271.150136516042,+ y: 508.6132290201976,+ },+ ],+ boundingBox: {+ left: 271.150136516042,+ top: 195.3426247575229,+ right: 1004.1704442379248,+ bottom: 508.6132290201976,+ },+ },+ {+ id: "block_8_Wl0xmI",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.893,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 223.9333605244212,+ y: 569.1121117154458,+ },+ {+ x: 1051.605887308608,+ y: 569.1121117154458,+ },+ {+ x: 1051.605887308608,+ y: 660.0886577520155,+ },+ {+ x: 223.9333605244212,+ y: 660.0886577520155,+ },+ ],+ boundingBox: {+ left: 223.9333605244212,+ top: 569.1121117154458,+ right: 1051.605887308608,+ bottom: 660.0886577520155,+ },+ },+ {+ id: "block_8_CtqTnb",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.518,+ avgOcrConfidence: 0.977,+ },+ polygon: [+ {+ x: 223.52019122047145,+ y: 690.790115499855,+ },+ {+ x: 1049.6801780088103,+ y: 690.790115499855,+ },+ {+ x: 1049.6801780088103,+ y: 734.1354363233523,+ },+ {+ x: 223.52019122047145,+ y: 734.1354363233523,+ },+ ],+ boundingBox: {+ left: 223.52019122047145,+ top: 690.790115499855,+ right: 1049.6801780088103,+ bottom: 734.1354363233523,+ },+ },+ {+ id: "block_8_KA1kZT",+ type: "heading",+ content: "# 6 Results",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Heading",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 224.16400352533717,+ y: 774.585115131579,+ },+ {+ x: 339.42863018843383,+ y: 774.585115131579,+ },+ {+ x: 339.42863018843383,+ y: 793.809935433524,+ },+ {+ x: 224.16400352533717,+ y: 793.809935433524,+ },+ ],+ boundingBox: {+ left: 224.16400352533717,+ top: 774.585115131579,+ right: 339.42863018843383,+ bottom: 793.809935433524,+ },+ },+ {+ id: "block_8_LYkEL8",+ type: "section_heading",+ content: "### 6.1 Machine Translation",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.994,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 224.2968510537252,+ y: 828.3471990026029,+ },+ {+ x: 455.2866330111984,+ y: 828.3471990026029,+ },+ {+ x: 455.2866330111984,+ y: 844.3720339438072,+ },+ {+ x: 224.2968510537252,+ y: 844.3720339438072,+ },+ ],+ boundingBox: {+ left: 224.2968510537252,+ top: 828.3471990026029,+ right: 455.2866330111984,+ bottom: 844.3720339438072,+ },+ },+ {+ id: "block_8_UnI1Ea",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.973,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.56291165317063,+ y: 872.0711140453367,+ },+ {+ x: 1050.5385628581919,+ y: 872.0711140453367,+ },+ {+ x: 1050.5385628581919,+ y: 1006.0390107004266,+ },+ {+ x: 223.56291165317063,+ y: 1006.0390107004266,+ },+ ],+ boundingBox: {+ left: 223.56291165317063,+ top: 872.0711140453367,+ right: 1050.5385628581919,+ bottom: 1006.0390107004266,+ },+ },+ {+ id: "block_8_pkBARc",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.945,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 224.05139199138557,+ y: 1019.1086798072756,+ },+ {+ x: 1052.2523977460653,+ y: 1019.1086798072756,+ },+ {+ x: 1052.2523977460653,+ y: 1109.5784446888401,+ },+ {+ x: 224.05139199138557,+ y: 1109.5784446888401,+ },+ ],+ boundingBox: {+ left: 224.05139199138557,+ top: 1019.1086798072756,+ right: 1052.2523977460653,+ bottom: 1109.5784446888401,+ },+ },+ {+ id: "block_8_vKs7Yg",+ type: "text",+ content:+ "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].",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.099,+ avgOcrConfidence: 0.983,+ },+ polygon: [+ {+ x: 223.50279536560504,+ y: 1122.2645474197273,+ },+ {+ x: 1050.043905216412,+ y: 1122.2645474197273,+ },+ {+ x: 1050.043905216412,+ y: 1233.5787297872673,+ },+ {+ x: 223.50279536560504,+ y: 1233.5787297872673,+ },+ ],+ boundingBox: {+ left: 223.50279536560504,+ top: 1122.2645474197273,+ right: 1050.043905216412,+ bottom: 1233.5787297872673,+ },+ },+ {+ id: "block_8_42PSVl",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.975,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 222.3879459130503,+ y: 1247.2785842436597,+ },+ {+ x: 1049.63284234931,+ y: 1247.2785842436597,+ },+ {+ x: 1049.63284234931,+ y: 1336.1913537620603,+ },+ {+ x: 222.3879459130503,+ y: 1336.1913537620603,+ },+ ],+ boundingBox: {+ left: 222.3879459130503,+ top: 1247.2785842436597,+ right: 1049.63284234931,+ bottom: 1336.1913537620603,+ },+ },+ {+ id: "block_8_pDx0nB",+ type: "section_heading",+ content: "### 6.2 Model Variations",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 224.05955739264942,+ y: 1370.9984397027727,+ },+ {+ x: 424.93188398597886,+ y: 1370.9984397027727,+ },+ {+ x: 424.93188398597886,+ y: 1387.4261614003576,+ },+ {+ x: 224.05955739264942,+ y: 1387.4261614003576,+ },+ ],+ boundingBox: {+ left: 224.05955739264942,+ top: 1370.9984397027727,+ right: 424.93188398597886,+ bottom: 1387.4261614003576,+ },+ },+ {+ id: "block_8_XCLvsN",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 222.6526705888066,+ y: 1413.835037862448,+ },+ {+ x: 1049.9819901737853,+ y: 1413.835037862448,+ },+ {+ x: 1049.9819901737853,+ y: 1458.0598621798638,+ },+ {+ x: 222.6526705888066,+ y: 1458.0598621798638,+ },+ ],+ boundingBox: {+ left: 222.6526705888066,+ top: 1413.835037862448,+ right: 1049.9819901737853,+ bottom: 1458.0598621798638,+ },+ },+ {+ id: "block_8_6e9VRc",+ type: "text",+ content:+ "5We used values of 2.8, 3.7, 6.0 and 9.5 TFLOPS for K80, K40, M40 and P100, respectively.",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.976,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 249.0640041601919,+ y: 1482.8447849015545,+ },+ {+ x: 944.2274051861172,+ y: 1482.8447849015545,+ },+ {+ x: 944.2274051861172,+ y: 1505.4603319670025,+ },+ {+ x: 249.0640041601919,+ y: 1505.4603319670025,+ },+ ],+ boundingBox: {+ left: 249.0640041601919,+ top: 1482.8447849015545,+ right: 944.2274051861172,+ bottom: 1505.4603319670025,+ },+ },+ {+ id: "block_8_HHxEh9",+ type: "page_number",+ content: "8",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.996,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 631.7743259624843,+ y: 1547.954182789738,+ },+ {+ x: 642.6607229413778,+ y: 1547.954182789738,+ },+ {+ x: 642.6607229413778,+ y: 1563.2957013352473,+ },+ {+ x: 631.7743259624843,+ y: 1563.2957013352473,+ },+ ],+ boundingBox: {+ left: 631.7743259624843,+ top: 1547.954182789738,+ right: 642.6607229413778,+ bottom: 1563.2957013352473,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_9_2CG18E",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.99,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 222.6654748847015,+ y: 147.86792777355453,+ },+ {+ x: 1049.6700481776775,+ y: 147.86792777355453,+ },+ {+ x: 1049.6700481776775,+ y: 237.19010704442076,+ },+ {+ x: 222.6654748847015,+ y: 237.19010704442076,+ },+ ],+ boundingBox: {+ left: 222.6654748847015,+ top: 147.86792777355453,+ right: 1049.6700481776775,+ bottom: 237.19010704442076,+ },+ },+ {+ id: "block_9_0WToWH",+ type: "table",+ content:+ "| | 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 |",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Table",+ minOcrConfidence: 0.612,+ avgOcrConfidence: 0.986,+ },+ polygon: [+ {+ x: 224.84461930546448,+ y: 268.65403318763674,+ },+ {+ x: 1060.6742636130673,+ y: 268.65403318763674,+ },+ {+ x: 1060.6742636130673,+ y: 801.2216690178204,+ },+ {+ x: 224.84461930546448,+ y: 801.2216690178204,+ },+ ],+ boundingBox: {+ left: 224.84461930546448,+ top: 268.65403318763674,+ right: 1060.6742636130673,+ bottom: 801.2216690178204,+ },+ },+ {+ id: "block_9_p8WB9c",+ type: "text",+ content:+ "development set, newstest2013. We used beam search as described in the previous section, but no checkpoint averaging. We present these results in Table 3.",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.989,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 224.42882287241247,+ y: 862.6040329323675,+ },+ {+ x: 1049.5265264580719,+ y: 862.6040329323675,+ },+ {+ x: 1049.5265264580719,+ y: 905.6541023541213,+ },+ {+ x: 224.42882287241247,+ y: 905.6541023541213,+ },+ ],+ boundingBox: {+ left: 224.42882287241247,+ top: 862.6040329323675,+ right: 1049.5265264580719,+ bottom: 905.6541023541213,+ },+ },+ {+ id: "block_9_XvsIA2",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.967,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 224.23600106343736,+ y: 918.8913094656807,+ },+ {+ x: 1052.034559041044,+ y: 918.8913094656807,+ },+ {+ x: 1052.034559041044,+ y: 986.1080494357232,+ },+ {+ x: 224.23600106343736,+ y: 986.1080494357232,+ },+ ],+ boundingBox: {+ left: 224.23600106343736,+ top: 918.8913094656807,+ right: 1052.034559041044,+ bottom: 986.1080494357232,+ },+ },+ {+ id: "block_9_lFHLbG",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.881,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 224.0262804240206,+ y: 998.9746651326803,+ },+ {+ x: 1052.338643317675,+ y: 998.9746651326803,+ },+ {+ x: 1052.338643317675,+ y: 1130.1984048140678,+ },+ {+ x: 224.0262804240206,+ y: 1130.1984048140678,+ },+ ],+ boundingBox: {+ left: 224.0262804240206,+ top: 998.9746651326803,+ right: 1052.338643317675,+ bottom: 1130.1984048140678,+ },+ },+ {+ id: "block_9_nnE2Kn",+ type: "section_heading",+ content: "### 6.3 English Constituency Parsing",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.994,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 224.00199723069687,+ y: 1168.0604785546325,+ },+ {+ x: 533.1579584274849,+ y: 1168.0604785546325,+ },+ {+ x: 533.1579584274849,+ y: 1188.5333575485345,+ },+ {+ x: 224.00199723069687,+ y: 1188.5333575485345,+ },+ ],+ boundingBox: {+ left: 224.00199723069687,+ top: 1168.0604785546325,+ right: 533.1579584274849,+ bottom: 1188.5333575485345,+ },+ },+ {+ id: "block_9_UvLm1J",+ type: "text",+ content:+ "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].",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.963,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.0787388599702,+ y: 1212.099580979885,+ },+ {+ x: 1049.9080518736457,+ y: 1212.099580979885,+ },+ {+ x: 1049.9080518736457,+ y: 1300.6617424183323,+ },+ {+ x: 223.0787388599702,+ y: 1300.6617424183323,+ },+ ],+ boundingBox: {+ left: 223.0787388599702,+ top: 1212.099580979885,+ right: 1049.9080518736457,+ bottom: 1300.6617424183323,+ },+ },+ {+ id: "block_9_nmNLPf",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.913,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 223.08401678600453,+ y: 1314.1105266370273,+ },+ {+ x: 1051.1732393807738,+ y: 1314.1105266370273,+ },+ {+ x: 1051.1732393807738,+ y: 1425.9921031177494,+ },+ {+ x: 223.08401678600453,+ y: 1425.9921031177494,+ },+ ],+ boundingBox: {+ left: 223.08401678600453,+ top: 1314.1105266370273,+ right: 1051.1732393807738,+ bottom: 1425.9921031177494,+ },+ },+ {+ id: "block_9_kQhH3x",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.1762739863709,+ y: 1439.0945411051127,+ },+ {+ x: 1050.7557388639798,+ y: 1439.0945411051127,+ },+ {+ x: 1050.7557388639798,+ y: 1505.8386894168711,+ },+ {+ x: 223.1762739863709,+ y: 1505.8386894168711,+ },+ ],+ boundingBox: {+ left: 223.1762739863709,+ top: 1439.0945411051127,+ right: 1050.7557388639798,+ bottom: 1505.8386894168711,+ },+ },+ {+ id: "block_9_C4QuNg",+ type: "page_number",+ content: "9",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.993,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 631.6446262554531,+ y: 1547.2787271370566,+ },+ {+ x: 642.3550765879834,+ y: 1547.2787271370566,+ },+ {+ x: 642.3550765879834,+ y: 1562.906831325445,+ },+ {+ x: 631.6446262554531,+ y: 1562.906831325445,+ },+ ],+ boundingBox: {+ left: 631.6446262554531,+ top: 1547.2787271370566,+ right: 642.3550765879834,+ bottom: 1562.906831325445,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_10_Whfo1k",+ type: "text",+ content:+ "Table 4: The Transformer generalizes well to English constituency parsing (Results are on Section 23 of WSJ)",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.988,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 222.60232911492787,+ y: 147.913837353986,+ },+ {+ x: 1049.0453121435903,+ y: 147.913837353986,+ },+ {+ x: 1049.0453121435903,+ y: 190.50408882485297,+ },+ {+ x: 222.60232911492787,+ y: 190.50408882485297,+ },+ ],+ boundingBox: {+ left: 222.60232911492787,+ top: 147.913837353986,+ right: 1049.0453121435903,+ bottom: 190.50408882485297,+ },+ },+ {+ id: "block_10_Oq0boE",+ type: "table",+ content:+ "| 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 |",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Table",+ minOcrConfidence: 0.926,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 300.48226962124346,+ y: 193.81453893417702,+ },+ {+ x: 974.1206315312072,+ y: 193.81453893417702,+ },+ {+ x: 974.1206315312072,+ y: 493.68785631567016,+ },+ {+ x: 300.48226962124346,+ y: 493.68785631567016,+ },+ ],+ boundingBox: {+ left: 300.48226962124346,+ top: 193.81453893417702,+ right: 974.1206315312072,+ bottom: 493.68785631567016,+ },+ },+ {+ id: "block_10_wSUPzw",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.117,+ avgOcrConfidence: 0.964,+ },+ polygon: [+ {+ x: 223.84354111051908,+ y: 546.3992524398001,+ },+ {+ x: 1049.2353174808252,+ y: 546.3992524398001,+ },+ {+ x: 1049.2353174808252,+ y: 589.787902057619,+ },+ {+ x: 223.84354111051908,+ y: 589.787902057619,+ },+ ],+ boundingBox: {+ left: 223.84354111051908,+ top: 546.3992524398001,+ right: 1049.2353174808252,+ bottom: 589.787902057619,+ },+ },+ {+ id: "block_10_KdYXbX",+ type: "text",+ content:+ "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].",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.917,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 224.34470740548016,+ y: 603.5821801379211,+ },+ {+ x: 1052.1757139776746,+ y: 603.5821801379211,+ },+ {+ x: 1052.1757139776746,+ y: 667.7562916691143,+ },+ {+ x: 224.34470740548016,+ y: 667.7562916691143,+ },+ ],+ boundingBox: {+ left: 224.34470740548016,+ top: 603.5821801379211,+ right: 1052.1757139776746,+ bottom: 667.7562916691143,+ },+ },+ {+ id: "block_10_spL6f1",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.907,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 223.93137242672216,+ y: 683.4819921909419,+ },+ {+ x: 1052.021589070341,+ y: 683.4819921909419,+ },+ {+ x: 1052.021589070341,+ y: 725.8283830513632,+ },+ {+ x: 223.93137242672216,+ y: 725.8283830513632,+ },+ ],+ boundingBox: {+ left: 223.93137242672216,+ top: 683.4819921909419,+ right: 1052.021589070341,+ bottom: 725.8283830513632,+ },+ },+ {+ id: "block_10_FpxS4M",+ type: "section_heading",+ content: "### 7 Conclusion",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.993,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.87968188654767,+ y: 760.911873552136,+ },+ {+ x: 380.37754949862074,+ y: 760.911873552136,+ },+ {+ x: 380.37754949862074,+ y: 780.8896204439321,+ },+ {+ x: 223.87968188654767,+ y: 780.8896204439321,+ },+ ],+ boundingBox: {+ left: 223.87968188654767,+ top: 760.911873552136,+ right: 380.37754949862074,+ bottom: 780.8896204439321,+ },+ },+ {+ id: "block_10_06Cxhy",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.989,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.7800876589587,+ y: 811.1846398948727,+ },+ {+ x: 1049.4503160462762,+ y: 811.1846398948727,+ },+ {+ x: 1049.4503160462762,+ y: 872.951422555106,+ },+ {+ x: 223.7800876589587,+ y: 872.951422555106,+ },+ ],+ boundingBox: {+ left: 223.7800876589587,+ top: 811.1846398948727,+ right: 1049.4503160462762,+ bottom: 872.951422555106,+ },+ },+ {+ id: "block_10_4PqBx5",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.989,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.91187013500797,+ y: 890.9364237390963,+ },+ {+ x: 1049.8108244290318,+ y: 890.9364237390963,+ },+ {+ x: 1049.8108244290318,+ y: 980.2941302536126,+ },+ {+ x: 223.91187013500797,+ y: 980.2941302536126,+ },+ ],+ boundingBox: {+ left: 223.91187013500797,+ top: 890.9364237390963,+ right: 1049.8108244290318,+ bottom: 980.2941302536126,+ },+ },+ {+ id: "block_10_9Aa2OZ",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.985,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.4691397117002,+ y: 993.4156992059005,+ },+ {+ x: 1051.09778633953,+ y: 993.4156992059005,+ },+ {+ x: 1051.09778633953,+ y: 1081.8706514745727,+ },+ {+ x: 223.4691397117002,+ y: 1081.8706514745727,+ },+ ],+ boundingBox: {+ left: 223.4691397117002,+ top: 993.4156992059005,+ right: 1051.09778633953,+ bottom: 1081.8706514745727,+ },+ },+ {+ id: "block_10_eXUU9v",+ type: "text",+ content:+ "The code we used to train and evaluate our models is available at https://github.com/ tensorflow/tensor2tensor.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.94,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 222.4288912585182,+ y: 1095.2490678371344,+ },+ {+ x: 1050.6089983195284,+ y: 1095.2490678371344,+ },+ {+ x: 1050.6089983195284,+ y: 1136.225321719521,+ },+ {+ x: 222.4288912585182,+ y: 1136.225321719521,+ },+ ],+ boundingBox: {+ left: 222.4288912585182,+ top: 1095.2490678371344,+ right: 1050.6089983195284,+ bottom: 1136.225321719521,+ },+ },+ {+ id: "block_10_HbnFiy",+ type: "text",+ content:+ "Acknowledgements We are grateful to Nal Kalchbrenner and Stephan Gouws for their fruitful comments, corrections and inspiration.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 223.74068072242457,+ y: 1165.530171673997,+ },+ {+ x: 1049.9162882783987,+ y: 1165.530171673997,+ },+ {+ x: 1049.9162882783987,+ y: 1209.6124608319503,+ },+ {+ x: 223.74068072242457,+ y: 1209.6124608319503,+ },+ ],+ boundingBox: {+ left: 223.74068072242457,+ top: 1165.530171673997,+ right: 1049.9162882783987,+ bottom: 1209.6124608319503,+ },+ },+ {+ id: "block_10_FqHFgA",+ type: "section_heading",+ content: "### References",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 224.3401158465086,+ y: 1243.4205694557131,+ },+ {+ x: 340.41243086766156,+ y: 1243.4205694557131,+ },+ {+ x: 340.41243086766156,+ y: 1263.1433630921786,+ },+ {+ x: 224.3401158465086,+ y: 1263.1433630921786,+ },+ ],+ boundingBox: {+ left: 224.3401158465086,+ top: 1243.4205694557131,+ right: 340.41243086766156,+ bottom: 1263.1433630921786,+ },+ },+ {+ id: "block_10_PnBCYC",+ type: "text",+ content:+ "[1] Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint arXiv: 1607.06450, 2016.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.913,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 234.62492392881074,+ y: 1281.5349446346884,+ },+ {+ x: 1049.520940850251,+ y: 1281.5349446346884,+ },+ {+ x: 1049.520940850251,+ y: 1323.6168167573169,+ },+ {+ x: 234.62492392881074,+ y: 1323.6168167573169,+ },+ ],+ boundingBox: {+ left: 234.62492392881074,+ top: 1281.5349446346884,+ right: 1049.520940850251,+ bottom: 1323.6168167573169,+ },+ },+ {+ id: "block_10_sUAYRJ",+ type: "text",+ content:+ "[2] Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly learning to align and translate. CoRR, abs/1409.0473, 2014.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.913,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 233.7351792050104,+ y: 1342.1247941210754,+ },+ {+ x: 1048.5688313950586,+ y: 1342.1247941210754,+ },+ {+ x: 1048.5688313950586,+ y: 1385.6842018070079,+ },+ {+ x: 233.7351792050104,+ y: 1385.6842018070079,+ },+ ],+ boundingBox: {+ left: 233.7351792050104,+ top: 1342.1247941210754,+ right: 1048.5688313950586,+ bottom: 1385.6842018070079,+ },+ },+ {+ id: "block_10_cYNyCb",+ type: "text",+ content:+ "[3] Denny Britz, Anna Goldie, Minh-Thang Luong, and Quoc V. Le. Massive exploration of neural machine translation architectures. CoRR, abs/1703.03906, 2017.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.914,+ avgOcrConfidence: 0.989,+ },+ polygon: [+ {+ x: 234.47555625525703,+ y: 1401.96474766552,+ },+ {+ x: 1050.0915248898693,+ y: 1401.96474766552,+ },+ {+ x: 1050.0915248898693,+ y: 1443.4021335687853,+ },+ {+ x: 234.47555625525703,+ y: 1443.4021335687853,+ },+ ],+ boundingBox: {+ left: 234.47555625525703,+ top: 1401.96474766552,+ right: 1050.0915248898693,+ bottom: 1443.4021335687853,+ },+ },+ {+ id: "block_10_akeHB3",+ type: "text",+ content:+ "[4] Jianpeng Cheng, Li Dong, and Mirella Lapata. Long short-term memory-networks for machine reading. arXiv preprint arXiv: 1601.06733, 2016.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.91,+ avgOcrConfidence: 0.989,+ },+ polygon: [+ {+ x: 235.1935672063897,+ y: 1461.8473196961825,+ },+ {+ x: 1049.3358584216041,+ y: 1461.8473196961825,+ },+ {+ x: 1049.3358584216041,+ y: 1505.7106445427228,+ },+ {+ x: 235.1935672063897,+ y: 1505.7106445427228,+ },+ ],+ boundingBox: {+ left: 235.1935672063897,+ top: 1461.8473196961825,+ right: 1049.3358584216041,+ bottom: 1505.7106445427228,+ },+ },+ {+ id: "block_10_sJYSgt",+ type: "page_number",+ content: "10",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.999,+ avgOcrConfidence: 0.999,+ },+ polygon: [+ {+ x: 628.4902252420022,+ y: 1547.7831405983832,+ },+ {+ x: 647.7796484954166,+ y: 1547.7831405983832,+ },+ {+ x: 647.7796484954166,+ y: 1563.3856736950409,+ },+ {+ x: 628.4902252420022,+ y: 1563.3856736950409,+ },+ ],+ boundingBox: {+ left: 628.4902252420022,+ top: 1547.7831405983832,+ right: 647.7796484954166,+ bottom: 1563.3856736950409,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_11_VBbBwR",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.932,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 234.95565818174043,+ y: 155.04768656967278,+ },+ {+ x: 1051.617910566121,+ y: 155.04768656967278,+ },+ {+ x: 1051.617910566121,+ y: 219.22101676195186,+ },+ {+ x: 234.95565818174043,+ y: 219.22101676195186,+ },+ ],+ boundingBox: {+ left: 234.95565818174043,+ top: 155.04768656967278,+ right: 1051.617910566121,+ bottom: 219.22101676195186,+ },+ },+ {+ id: "block_11_fZULb0",+ type: "text",+ content:+ "[6] Francois Chollet. Xception: Deep learning with depthwise separable convolutions. arXiv preprint arXiv: 1610.02357, 2016.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.916,+ avgOcrConfidence: 0.987,+ },+ polygon: [+ {+ x: 234.37082610861228,+ y: 242.1581676597882,+ },+ {+ x: 1050.1136779785156,+ y: 242.1581676597882,+ },+ {+ x: 1050.1136779785156,+ y: 284.96119192309845,+ },+ {+ x: 234.37082610861228,+ y: 284.96119192309845,+ },+ ],+ boundingBox: {+ left: 234.37082610861228,+ top: 242.1581676597882,+ right: 1050.1136779785156,+ bottom: 284.96119192309845,+ },+ },+ {+ id: "block_11_KQxaZG",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.937,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 234.59709056102446,+ y: 305.8525607747243,+ },+ {+ x: 1050.252182118214,+ y: 305.8525607747243,+ },+ {+ x: 1050.252182118214,+ y: 348.70033444856347,+ },+ {+ x: 234.59709056102446,+ y: 348.70033444856347,+ },+ ],+ boundingBox: {+ left: 234.59709056102446,+ top: 305.8525607747243,+ right: 1050.252182118214,+ bottom: 348.70033444856347,+ },+ },+ {+ id: "block_11_lSxX1m",+ type: "text",+ content:+ "[8] Chris Dyer, Adhiguna Kuncoro, Miguel Ballesteros, and Noah A. Smith. Recurrent neural network grammars. In Proc. of NAACL, 2016.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.92,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 234.54393261540545,+ y: 369.88837531814,+ },+ {+ x: 1049.7648141679972,+ y: 369.88837531814,+ },+ {+ x: 1049.7648141679972,+ y: 412.63161531606113,+ },+ {+ x: 234.54393261540545,+ y: 412.63161531606113,+ },+ ],+ boundingBox: {+ left: 234.54393261540545,+ top: 369.88837531814,+ right: 1049.7648141679972,+ bottom: 412.63161531606113,+ },+ },+ {+ id: "block_11_3YLXoz",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.927,+ avgOcrConfidence: 0.989,+ },+ polygon: [+ {+ x: 233.81299902922916,+ y: 434.3302966813395,+ },+ {+ x: 1052.8067929901345,+ y: 434.3302966813395,+ },+ {+ x: 1052.8067929901345,+ y: 476.945989020785,+ },+ {+ x: 233.81299902922916,+ y: 476.945989020785,+ },+ ],+ boundingBox: {+ left: 233.81299902922916,+ top: 434.3302966813395,+ right: 1052.8067929901345,+ bottom: 476.945989020785,+ },+ },+ {+ id: "block_11_OkxRaO",+ type: "text",+ content:+ "[10] Alex Graves. Generating sequences with recurrent neural networks. arXiv preprint arXiv: 1308.0850, 2013.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.904,+ avgOcrConfidence: 0.986,+ },+ polygon: [+ {+ x: 224.38643378932983,+ y: 498.1091927836712,+ },+ {+ x: 1050.5877919440723,+ y: 498.1091927836712,+ },+ {+ x: 1050.5877919440723,+ y: 539.0395607625632,+ },+ {+ x: 224.38643378932983,+ y: 539.0395607625632,+ },+ ],+ boundingBox: {+ left: 224.38643378932983,+ top: 498.1091927836712,+ right: 1050.5877919440723,+ bottom: 539.0395607625632,+ },+ },+ {+ id: "block_11_RVnHcs",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.919,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.3475475450502,+ y: 561.9494121522832,+ },+ {+ x: 1053.1976908662893,+ y: 561.9494121522832,+ },+ {+ x: 1053.1976908662893,+ y: 627.2271530610278,+ },+ {+ x: 224.3475475450502,+ y: 627.2271530610278,+ },+ ],+ boundingBox: {+ left: 224.3475475450502,+ top: 561.9494121522832,+ right: 1053.1976908662893,+ bottom: 627.2271530610278,+ },+ },+ {+ id: "block_11_s96TQd",+ type: "text",+ content:+ "[12] Sepp Hochreiter, Yoshua Bengio, Paolo Frasconi, and J\u00fcrgen Schmidhuber. Gradient flow in recurrent nets: the difficulty of learning long-term dependencies, 2001.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.892,+ avgOcrConfidence: 0.989,+ },+ polygon: [+ {+ x: 224.27874516396628,+ y: 647.9830188034173,+ },+ {+ x: 1048.8635432111087,+ y: 647.9830188034173,+ },+ {+ x: 1048.8635432111087,+ y: 692.1669293740639,+ },+ {+ x: 224.27874516396628,+ y: 692.1669293740639,+ },+ ],+ boundingBox: {+ left: 224.27874516396628,+ top: 647.9830188034173,+ right: 1048.8635432111087,+ bottom: 692.1669293740639,+ },+ },+ {+ id: "block_11_bKrlBK",+ type: "text",+ content:+ "[13] Sepp Hochreiter and J\u00fcrgen Schmidhuber. Long short-term memory. Neural computation, 9(8):1735-1780, 1997.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.903,+ avgOcrConfidence: 0.984,+ },+ polygon: [+ {+ x: 224.36335765532334,+ y: 712.3709330738038,+ },+ {+ x: 1051.7104044447851,+ y: 712.3709330738038,+ },+ {+ x: 1051.7104044447851,+ y: 754.2910917181719,+ },+ {+ x: 224.36335765532334,+ y: 754.2910917181719,+ },+ ],+ boundingBox: {+ left: 224.36335765532334,+ top: 712.3709330738038,+ right: 1051.7104044447851,+ bottom: 754.2910917181719,+ },+ },+ {+ id: "block_11_c3sQ7S",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.908,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.70277800177138,+ y: 777.0990849258308,+ },+ {+ x: 1050.1772024335653,+ y: 777.0990849258308,+ },+ {+ x: 1050.1772024335653,+ y: 842.7015786995565,+ },+ {+ x: 224.70277800177138,+ y: 842.7015786995565,+ },+ ],+ boundingBox: {+ left: 224.70277800177138,+ top: 777.0990849258308,+ right: 1050.1772024335653,+ bottom: 842.7015786995565,+ },+ },+ {+ id: "block_11_HmSxMA",+ type: "text",+ content:+ "[15] Rafal Jozefowicz, Oriol Vinyals, Mike Schuster, Noam Shazeer, and Yonghui Wu. Exploring the limits of language modeling. arXiv preprint arXiv: 1602.02410, 2016.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.906,+ avgOcrConfidence: 0.989,+ },+ polygon: [+ {+ x: 223.96287430811972,+ y: 863.015632801486,+ },+ {+ x: 1049.822942357864,+ y: 863.015632801486,+ },+ {+ x: 1049.822942357864,+ y: 907.0369301702743,+ },+ {+ x: 223.96287430811972,+ y: 907.0369301702743,+ },+ ],+ boundingBox: {+ left: 223.96287430811972,+ top: 863.015632801486,+ right: 1049.822942357864,+ bottom: 907.0369301702743,+ },+ },+ {+ id: "block_11_XlCObz",+ type: "text",+ content:+ "[16] \u0141ukasz Kaiser and Samy Bengio. Can active memory replace attention? In Advances in Neural Information Processing Systems, (NIPS), 2016.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.902,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 224.17545875493627,+ y: 927.1137413655905,+ },+ {+ x: 1050.2528448174469,+ y: 927.1137413655905,+ },+ {+ x: 1050.2528448174469,+ y: 970.5487977795134,+ },+ {+ x: 224.17545875493627,+ y: 970.5487977795134,+ },+ ],+ boundingBox: {+ left: 224.17545875493627,+ top: 927.1137413655905,+ right: 1050.2528448174469,+ bottom: 970.5487977795134,+ },+ },+ {+ id: "block_11_48mMcn",+ type: "text",+ content:+ "[17] \u0141ukasz Kaiser and Ilya Sutskever. Neural GPUs learn algorithms. In International Conference on Learning Representations (ICLR), 2016.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.903,+ avgOcrConfidence: 0.987,+ },+ polygon: [+ {+ x: 224.42198286961465,+ y: 991.1752927392946,+ },+ {+ x: 1049.7810976348653,+ y: 991.1752927392946,+ },+ {+ x: 1049.7810976348653,+ y: 1034.8329123590227,+ },+ {+ x: 224.42198286961465,+ y: 1034.8329123590227,+ },+ ],+ boundingBox: {+ left: 224.42198286961465,+ top: 991.1752927392946,+ right: 1049.7810976348653,+ bottom: 1034.8329123590227,+ },+ },+ {+ id: "block_11_lBImir",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.934,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 224.23202486803933,+ y: 1055.1385374714557,+ },+ {+ x: 1052.4190192675069,+ y: 1055.1385374714557,+ },+ {+ x: 1052.4190192675069,+ y: 1117.975328259002,+ },+ {+ x: 224.23202486803933,+ y: 1117.975328259002,+ },+ ],+ boundingBox: {+ left: 224.23202486803933,+ top: 1055.1385374714557,+ right: 1052.4190192675069,+ bottom: 1117.975328259002,+ },+ },+ {+ id: "block_11_Y0ddKF",+ type: "text",+ content:+ "[19] Yoon Kim, Carl Denton, Luong Hoang, and Alexander M. Rush. Structured attention networks. In International Conference on Learning Representations, 2017.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.974,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 224.29036606837366,+ y: 1142.1438929622334,+ },+ {+ x: 1052.7023705252766,+ y: 1142.1438929622334,+ },+ {+ x: 1052.7023705252766,+ y: 1185.793178300212,+ },+ {+ x: 224.29036606837366,+ y: 1185.793178300212,+ },+ ],+ boundingBox: {+ left: 224.29036606837366,+ top: 1142.1438929622334,+ right: 1052.7023705252766,+ bottom: 1185.793178300212,+ },+ },+ {+ id: "block_11_nehypx",+ type: "text",+ content:+ "[20] Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In ICLR, 2015.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.912,+ avgOcrConfidence: 0.989,+ },+ polygon: [+ {+ x: 223.92950266817192,+ y: 1205.8213097134928,+ },+ {+ x: 1052.7550077786411,+ y: 1205.8213097134928,+ },+ {+ x: 1052.7550077786411,+ y: 1227.2851158658366,+ },+ {+ x: 223.92950266817192,+ y: 1227.2851158658366,+ },+ ],+ boundingBox: {+ left: 223.92950266817192,+ top: 1205.8213097134928,+ right: 1052.7550077786411,+ bottom: 1227.2851158658366,+ },+ },+ {+ id: "block_11_af7MVz",+ type: "text",+ content:+ "[21] Oleksii Kuchaiev and Boris Ginsburg. Factorization tricks for LSTM networks. arXiv preprint arXiv: 1703.10722, 2017.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.925,+ avgOcrConfidence: 0.989,+ },+ polygon: [+ {+ x: 223.78512890669552,+ y: 1247.11833873548,+ },+ {+ x: 1050.4177622551465,+ y: 1247.11833873548,+ },+ {+ x: 1050.4177622551465,+ y: 1289.109575544085,+ },+ {+ x: 223.78512890669552,+ y: 1289.109575544085,+ },+ ],+ boundingBox: {+ left: 223.78512890669552,+ top: 1247.11833873548,+ right: 1050.4177622551465,+ bottom: 1289.109575544085,+ },+ },+ {+ id: "block_11_vnPlfZ",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.913,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 223.74063338676507,+ y: 1311.0246641116034,+ },+ {+ x: 1050.2205618976677,+ y: 1311.0246641116034,+ },+ {+ x: 1050.2205618976677,+ y: 1375.8748468958345,+ },+ {+ x: 223.74063338676507,+ y: 1375.8748468958345,+ },+ ],+ boundingBox: {+ left: 223.74063338676507,+ top: 1311.0246641116034,+ right: 1050.2205618976677,+ bottom: 1375.8748468958345,+ },+ },+ {+ id: "block_11_g0SHxO",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.908,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 224.355428932357,+ y: 1397.7982697451025,+ },+ {+ x: 1050.4997476174015,+ y: 1397.7982697451025,+ },+ {+ x: 1050.4997476174015,+ y: 1441.9434448471643,+ },+ {+ x: 224.355428932357,+ y: 1441.9434448471643,+ },+ ],+ boundingBox: {+ left: 224.355428932357,+ top: 1397.7982697451025,+ right: 1050.4997476174015,+ bottom: 1441.9434448471643,+ },+ },+ {+ id: "block_11_gDtqYI",+ type: "text",+ content:+ "[24] Minh-Thang Luong, Hieu Pham, and Christopher D Manning. Effective approaches to attention- based neural machine translation. arXiv preprint arXiv: 1508.04025, 2015.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.927,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 224.7064228475529,+ y: 1461.612349775501,+ },+ {+ x: 1052.9802308465444,+ y: 1461.612349775501,+ },+ {+ x: 1052.9802308465444,+ y: 1506.2439438669305,+ },+ {+ x: 224.7064228475529,+ y: 1506.2439438669305,+ },+ ],+ boundingBox: {+ left: 224.7064228475529,+ top: 1461.612349775501,+ right: 1052.9802308465444,+ bottom: 1506.2439438669305,+ },+ },+ {+ id: "block_11_JWTkzE",+ type: "page_number",+ content: "11",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 629.039650241824,+ y: 1547.854550239735,+ },+ {+ x: 645.38100862155,+ y: 1547.854550239735,+ },+ {+ x: 645.38100862155,+ y: 1563.4467601919532,+ },+ {+ x: 629.039650241824,+ y: 1563.4467601919532,+ },+ ],+ boundingBox: {+ left: 629.039650241824,+ top: 1547.854550239735,+ right: 645.38100862155,+ bottom: 1563.4467601919532,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_12_TQ4Lbe",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.913,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 223.94512343580706,+ y: 154.85743054411464,+ },+ {+ x: 1050.2930801280222,+ y: 154.85743054411464,+ },+ {+ x: 1050.2930801280222,+ y: 198.76930494953817,+ },+ {+ x: 223.94512343580706,+ y: 198.76930494953817,+ },+ ],+ boundingBox: {+ left: 223.94512343580706,+ top: 154.85743054411464,+ right: 1050.2930801280222,+ bottom: 198.76930494953817,+ },+ },+ {+ id: "block_12_LvCkff",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.907,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.21323261121762,+ y: 226.782506971431,+ },+ {+ x: 1051.9384676522582,+ y: 226.782506971431,+ },+ {+ x: 1051.9384676522582,+ y: 292.8687442406676,+ },+ {+ x: 224.21323261121762,+ y: 292.8687442406676,+ },+ ],+ boundingBox: {+ left: 224.21323261121762,+ top: 226.782506971431,+ right: 1051.9384676522582,+ bottom: 292.8687442406676,+ },+ },+ {+ id: "block_12_Rm8AFL",+ type: "text",+ content:+ "[27] Ankur Parikh, Oscar T\u00e4ckstr\u00f6m, Dipanjan Das, and Jakob Uszkoreit. A decomposable attention model. In Empirical Methods in Natural Language Processing, 2016.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.916,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.08847948060418,+ y: 321.2656073462694,+ },+ {+ x: 1048.8436622341185,+ y: 321.2656073462694,+ },+ {+ x: 1048.8436622341185,+ y: 364.85913349811295,+ },+ {+ x: 224.08847948060418,+ y: 364.85913349811295,+ },+ ],+ boundingBox: {+ left: 224.08847948060418,+ top: 321.2656073462694,+ right: 1048.8436622341185,+ bottom: 364.85913349811295,+ },+ },+ {+ id: "block_12_cqas9e",+ type: "text",+ content:+ "[28] Romain Paulus, Caiming Xiong, and Richard Socher. A deep reinforced model for abstractive summarization. arXiv preprint arXiv: 1705.04304, 2017.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.912,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 224.67392691730583,+ y: 392.7383714116606,+ },+ {+ x: 1049.3349117084142,+ y: 392.7383714116606,+ },+ {+ x: 1049.3349117084142,+ y: 435.42904860991285,+ },+ {+ x: 224.67392691730583,+ y: 435.42904860991285,+ },+ ],+ boundingBox: {+ left: 224.67392691730583,+ top: 392.7383714116606,+ right: 1049.3349117084142,+ bottom: 435.42904860991285,+ },+ },+ {+ id: "block_12_hfa5dB",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.899,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 223.91392923619625,+ y: 463.67279296530813,+ },+ {+ x: 1051.5214404920591,+ y: 463.67279296530813,+ },+ {+ x: 1051.5214404920591,+ y: 549.7230681799408,+ },+ {+ x: 223.91392923619625,+ y: 549.7230681799408,+ },+ ],+ boundingBox: {+ left: 223.91392923619625,+ top: 463.67279296530813,+ right: 1051.5214404920591,+ bottom: 549.7230681799408,+ },+ },+ {+ id: "block_12_H2k7w4",+ type: "text",+ content:+ "[30] Ofir Press and Lior Wolf. Using the output embedding to improve language models. arXiv preprint arXiv: 1608.05859, 2016.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.898,+ avgOcrConfidence: 0.987,+ },+ polygon: [+ {+ x: 224.29183347381814,+ y: 581.8894180068396,+ },+ {+ x: 1049.7876299558764,+ y: 581.8894180068396,+ },+ {+ x: 1049.7876299558764,+ y: 624.918793785841,+ },+ {+ x: 224.29183347381814,+ y: 624.918793785841,+ },+ ],+ boundingBox: {+ left: 224.29183347381814,+ top: 581.8894180068396,+ right: 1049.7876299558764,+ bottom: 624.918793785841,+ },+ },+ {+ id: "block_12_UrZIEK",+ type: "text",+ content:+ "[31] Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words with subword units. arXiv preprint arXiv: 1508.07909, 2015.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.925,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 224.35140540129947,+ y: 653.3260510666926,+ },+ {+ x: 1049.4855337769445,+ y: 653.3260510666926,+ },+ {+ x: 1049.4855337769445,+ y: 696.2955715494944,+ },+ {+ x: 224.35140540129947,+ y: 696.2955715494944,+ },+ ],+ boundingBox: {+ left: 224.35140540129947,+ top: 653.3260510666926,+ right: 1049.4855337769445,+ bottom: 696.2955715494944,+ },+ },+ {+ id: "block_12_IIwlxZ",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.88,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 224.15238262092979,+ y: 724.7319041087216,+ },+ {+ x: 1051.274348349467,+ y: 724.7319041087216,+ },+ {+ x: 1051.274348349467,+ y: 791.0497254966793,+ },+ {+ x: 224.15238262092979,+ y: 791.0497254966793,+ },+ ],+ boundingBox: {+ left: 224.15238262092979,+ top: 724.7319041087216,+ right: 1051.274348349467,+ bottom: 791.0497254966793,+ },+ },+ {+ id: "block_12_pGLzhM",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.938,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 224.4417928431156,+ y: 819.0001126052741,+ },+ {+ x: 1053.3042907714844,+ y: 819.0001126052741,+ },+ {+ x: 1053.3042907714844,+ y: 885.2761205228649,+ },+ {+ x: 224.4417928431156,+ y: 885.2761205228649,+ },+ ],+ boundingBox: {+ left: 224.4417928431156,+ top: 819.0001126052741,+ right: 1053.3042907714844,+ bottom: 885.2761205228649,+ },+ },+ {+ id: "block_12_Bz8MfK",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.897,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.0948934624665,+ y: 913.8373252467105,+ },+ {+ x: 1051.823347328353,+ y: 913.8373252467105,+ },+ {+ x: 1051.823347328353,+ y: 1000.8878563328793,+ },+ {+ x: 224.0948934624665,+ y: 1000.8878563328793,+ },+ ],+ boundingBox: {+ left: 224.0948934624665,+ top: 913.8373252467105,+ right: 1051.823347328353,+ bottom: 1000.8878563328793,+ },+ },+ {+ id: "block_12_m0nnSr",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.899,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 224.52872478178818,+ y: 1030.965426796361,+ },+ {+ x: 1050.1110271815835,+ y: 1030.965426796361,+ },+ {+ x: 1050.1110271815835,+ y: 1074.9609636579241,+ },+ {+ x: 224.52872478178818,+ y: 1074.9609636579241,+ },+ ],+ boundingBox: {+ left: 224.52872478178818,+ top: 1030.965426796361,+ right: 1050.1110271815835,+ bottom: 1074.9609636579241,+ },+ },+ {+ id: "block_12_C1nzdD",+ type: "text",+ content:+ "[36] Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, and Zbigniew Wojna. Rethinking the inception architecture for computer vision. CoRR, abs/1512.00567, 2015.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.939,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.60145602261062,+ y: 1102.9526906981505,+ },+ {+ x: 1051.9790816481095,+ y: 1102.9526906981505,+ },+ {+ x: 1051.9790816481095,+ y: 1146.15116715969,+ },+ {+ x: 224.60145602261062,+ y: 1146.15116715969,+ },+ ],+ boundingBox: {+ left: 224.60145602261062,+ top: 1102.9526906981505,+ right: 1051.9790816481095,+ bottom: 1146.15116715969,+ },+ },+ {+ id: "block_12_smJ629",+ type: "text",+ content:+ "[37] Vinyals & Kaiser, Koo, Petrov, Sutskever, and Hinton. Grammar as a foreign language. In Advances in Neural Information Processing Systems, 2015.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.912,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.70363004364236,+ y: 1173.716330506748,+ },+ {+ x: 1049.93891472364,+ y: 1173.716330506748,+ },+ {+ x: 1049.93891472364,+ y: 1218.0808487512115,+ },+ {+ x: 224.70363004364236,+ y: 1218.0808487512115,+ },+ ],+ boundingBox: {+ left: 224.70363004364236,+ top: 1173.716330506748,+ right: 1049.93891472364,+ bottom: 1218.0808487512115,+ },+ },+ {+ id: "block_12_oKrqzS",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.935,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 224.222865417926,+ y: 1246.0137622804568,+ },+ {+ x: 1050.4285547855127,+ y: 1246.0137622804568,+ },+ {+ x: 1050.4285547855127,+ y: 1332.3901636224045,+ },+ {+ x: 224.222865417926,+ y: 1332.3901636224045,+ },+ ],+ boundingBox: {+ left: 224.222865417926,+ top: 1246.0137622804568,+ right: 1050.4285547855127,+ bottom: 1332.3901636224045,+ },+ },+ {+ id: "block_12_5hQUgX",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.977,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 224.40534438530025,+ y: 1362.7727877394598,+ },+ {+ x: 1049.6643678985372,+ y: 1362.7727877394598,+ },+ {+ x: 1049.6643678985372,+ y: 1404.796982844073,+ },+ {+ x: 224.40534438530025,+ y: 1404.796982844073,+ },+ ],+ boundingBox: {+ left: 224.40534438530025,+ top: 1362.7727877394598,+ right: 1049.6643678985372,+ bottom: 1404.796982844073,+ },+ },+ {+ id: "block_12_7qyMnf",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.905,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.04902520841057,+ y: 1434.5126750056904,+ },+ {+ x: 1049.9945814592124,+ y: 1434.5126750056904,+ },+ {+ x: 1049.9945814592124,+ y: 1501.148572362455,+ },+ {+ x: 224.04902520841057,+ y: 1501.148572362455,+ },+ ],+ boundingBox: {+ left: 224.04902520841057,+ top: 1434.5126750056904,+ right: 1049.9945814592124,+ bottom: 1501.148572362455,+ },+ },+ {+ id: "block_12_6o6JUd",+ type: "page_number",+ content: "12",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.998,+ avgOcrConfidence: 0.998,+ },+ polygon: [+ {+ x: 628.997000812614,+ y: 1547.789391309695,+ },+ {+ x: 647.0427269483133,+ y: 1547.789391309695,+ },+ {+ x: 647.0427269483133,+ y: 1563.398364533159,+ },+ {+ x: 628.997000812614,+ y: 1563.398364533159,+ },+ ],+ boundingBox: {+ left: 628.997000812614,+ top: 1547.789391309695,+ right: 647.0427269483133,+ bottom: 1563.398364533159,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_13_KlKk5h",+ type: "page_number",+ content: "13",+ metadata: {+ page: {+ number: 13,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.999,+ avgOcrConfidence: 0.999,+ },+ polygon: [+ {+ x: 103.29433033878627,+ y: 628.7723457726248,+ },+ {+ x: 103.29433033878627,+ y: 646.9001519418981,+ },+ {+ x: 87.59273293860883,+ y: 646.9001519418981,+ },+ {+ x: 87.59273293860883,+ y: 628.7723457726248,+ },+ ],+ boundingBox: {+ left: 87.59273293860883,+ top: 628.7723457726248,+ right: 103.29433033878627,+ bottom: 646.9001519418981,+ },+ },+ {+ id: "block_13_PkaOm5",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 13,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.937,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 999.8870322148603,+ y: 224.33585563715354,+ },+ {+ x: 999.8870322148603,+ y: 1052.0067256732577,+ },+ {+ x: 911.037953656419,+ y: 1052.0067256732577,+ },+ {+ x: 911.037953656419,+ y: 224.33585563715354,+ },+ ],+ boundingBox: {+ left: 911.037953656419,+ top: 224.33585563715354,+ right: 999.8870322148603,+ bottom: 1052.0067256732577,+ },+ },+ {+ id: "block_13_xamkHQ",+ type: "figure",+ content:+ "<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>",+ metadata: {+ page: {+ number: 13,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Picture/Figure/Image/Chart",+ minOcrConfidence: 0.717,+ avgOcrConfidence: 0.98,+ },+ polygon: [+ {+ x: 1444.0009233001479,+ y: 252.8656019781628,+ },+ {+ x: 1444.0009233001479,+ y: 1047.5539548553688,+ },+ {+ x: 1022.9538143416097,+ y: 1047.5539548553688,+ },+ {+ x: 1022.9538143416097,+ y: 252.8656019781628,+ },+ ],+ boundingBox: {+ left: 1022.9538143416097,+ top: 252.8656019781628,+ right: 1444.0009233001479,+ bottom: 1047.5539548553688,+ },+ },+ {+ id: "block_13_5eYqPZ",+ type: "heading",+ content: "# Attention Visualizations",+ metadata: {+ page: {+ number: 13,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Heading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 1498.6412794643775,+ y: 224.94428453654268,+ },+ {+ x: 1498.6412794643775,+ y: 480.8453803514912,+ },+ {+ x: 1479.199057528847,+ y: 480.8453803514912,+ },+ {+ x: 1479.199057528847,+ y: 224.94428453654268,+ },+ ],+ boundingBox: {+ left: 1479.199057528847,+ top: 224.94428453654268,+ right: 1498.6412794643775,+ bottom: 480.8453803514912,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_14_DaAuYi",+ type: "page_number",+ content: "14",+ metadata: {+ page: {+ number: 14,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.998,+ avgOcrConfidence: 0.998,+ },+ polygon: [+ {+ x: 103.12243577770732,+ y: 628.7327731612825,+ },+ {+ x: 103.12243577770732,+ y: 647.0026336447166,+ },+ {+ x: 87.74237117910752,+ y: 647.0026336447166,+ },+ {+ x: 87.74237117910752,+ y: 628.7327731612825,+ },+ ],+ boundingBox: {+ left: 87.74237117910752,+ top: 628.7327731612825,+ right: 103.12243577770732,+ bottom: 647.0026336447166,+ },+ },+ {+ id: "block_14_VDKMys",+ type: "text",+ content:+ "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:",+ metadata: {+ page: {+ number: 14,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.972,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 370.4634644357782,+ y: 224.1528559775248,+ },+ {+ x: 370.4634644357782,+ y: 1051.3102287793681,+ },+ {+ x: 303.81733864232115,+ y: 1051.3102287793681,+ },+ {+ x: 303.81733864232115,+ y: 224.1528559775248,+ },+ ],+ boundingBox: {+ left: 303.81733864232115,+ top: 224.1528559775248,+ right: 370.4634644357782,+ bottom: 1051.3102287793681,+ },+ },+ {+ id: "block_14_QRz2LE",+ type: "figure",+ content:+ "<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>",+ metadata: {+ page: {+ number: 14,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Picture/Figure/Image/Chart",+ minOcrConfidence: 0.379,+ avgOcrConfidence: 0.963,+ },+ polygon: [+ {+ x: 1294.7974623916741,+ y: 255.12043611846704,+ },+ {+ x: 1294.7974623916741,+ y: 1044.444475382784,+ },+ {+ x: 388.9633916410289,+ y: 1044.444475382784,+ },+ {+ x: 388.9633916410289,+ y: 255.12043611846704,+ },+ ],+ boundingBox: {+ left: 388.9633916410289,+ top: 255.12043611846704,+ right: 1294.7974623916741,+ bottom: 1044.444475382784,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_15_pV91a2",+ type: "page_number",+ content: "15",+ metadata: {+ page: {+ number: 15,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.998,+ avgOcrConfidence: 0.998,+ },+ polygon: [+ {+ x: 103.26014084206486,+ y: 628.7008215911197,+ },+ {+ x: 103.26014084206486,+ y: 647.1549124613296,+ },+ {+ x: 87.58487219559515,+ y: 647.1549124613296,+ },+ {+ x: 87.58487219559515,+ y: 628.7008215911197,+ },+ ],+ boundingBox: {+ left: 87.58487219559515,+ top: 628.7008215911197,+ right: 103.26014084206486,+ bottom: 647.1549124613296,+ },+ },+ {+ id: "block_15_2igWoi",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 15,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.976,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 394.6980404387739,+ y: 223.74716570777616,+ },+ {+ x: 394.6980404387739,+ y: 1049.736980800211,+ },+ {+ x: 328.87227315113955,+ y: 1049.736980800211,+ },+ {+ x: 328.87227315113955,+ y: 223.74716570777616,+ },+ ],+ boundingBox: {+ left: 328.87227315113955,+ top: 223.74716570777616,+ right: 394.6980404387739,+ bottom: 1049.736980800211,+ },+ },+ {+ id: "block_15_OqCqJD",+ type: "figure",+ content:+ "<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>",+ metadata: {+ page: {+ number: 15,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Picture/Figure/Image/Chart",+ minOcrConfidence: 0.651,+ avgOcrConfidence: 0.969,+ },+ polygon: [+ {+ x: 810.314180990807,+ y: 253.4944325467966,+ },+ {+ x: 810.314180990807,+ y: 1035.3522419059364,+ },+ {+ x: 421.96601087527165,+ y: 1035.3522419059364,+ },+ {+ x: 421.96601087527165,+ y: 253.4944325467966,+ },+ ],+ boundingBox: {+ left: 421.96601087527165,+ top: 253.4944325467966,+ right: 810.314180990807,+ bottom: 1035.3522419059364,+ },+ },+ {+ id: "block_15_sK8Nre",+ type: "figure",+ content:+ "<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>",+ metadata: {+ page: {+ number: 15,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Picture/Figure/Image/Chart",+ minOcrConfidence: 0.6,+ avgOcrConfidence: 0.968,+ },+ polygon: [+ {+ x: 1255.9501913113702,+ y: 254.50874105857238,+ },+ {+ x: 1255.9501913113702,+ y: 1034.3072598868043,+ },+ {+ x: 882.2701913360366,+ y: 1034.3072598868043,+ },+ {+ x: 882.2701913360366,+ y: 254.50874105857238,+ },+ ],+ boundingBox: {+ left: 882.2701913360366,+ top: 254.50874105857238,+ right: 1255.9501913113702,+ bottom: 1034.3072598868043,+ },+ },+ ],+ },+ ],+} satisfies ParsedOcrOutput++function getBlockType(block: ParsedOcrBlock): OcrBlockType | undefined {+ if (block.type === "heading" || block.type === "section_heading") {+ return "heading"+ }++ if (block.type === "header") {+ return "header"+ }++ if (block.type === "footer") {+ return "footer"+ }++ if (block.type === "page_number") {+ return "page_number"+ }++ if (block.type === "figure" || block.type === "image") {+ return "figure"+ }++ if (block.type === "table") {+ return "table"+ }++ if (block.metadata.layoutClass === "List Item") {+ return "list"+ }++ if (block.type === "text") {+ return "paragraph"+ }+}++function getOcrBlocks(output: ParsedOcrOutput): OcrBlock[] {+ return output.chunks.flatMap((chunk) =>+ chunk.blocks.flatMap((block) => {+ const type = getBlockType(block)+ const { page } = block.metadata++ if (!type || page.width <= 0 || page.height <= 0) {+ return []+ }++ return {+ id: block.id,+ type,+ text: block.content,+ page: page.number,+ pageWidth: page.width,+ pageHeight: page.height,+ confidence:+ block.metadata.avgOcrConfidence ??+ block.metadata.minOcrConfidence ??+ 1,+ polygon: block.polygon,+ boundingBox: block.boundingBox,+ }+ })+ )+}-function convertPolygonToHighlightArea(polygon: Point[]): HighlightArea {+function getBoundingBox(block: OcrBlock): BoundingBox {+ if (block.boundingBox) {+ return block.boundingBox+ }++ const polygon = block.polygon ?? []const xValues = polygon.map((point) => point.x)const yValues = polygon.map((point) => point.y)const left = Math.min(...xValues)@@ -224,11 +8088,17 @@ function convertPolygonToHighlightArea(polygon: Point[]): HighlightArea {const top = Math.min(...yValues)const bottom = Math.max(...yValues)+ return { left, top, right, bottom }+}++function convertBlockToHighlightArea(block: OcrBlock): HighlightArea {+ const { left, top, right, bottom } = getBoundingBox(block)+return {- left: (left / ANNOTATION_PAGE_WIDTH) * 100,- top: (top / ANNOTATION_PAGE_HEIGHT) * 100,- width: ((right - left) / ANNOTATION_PAGE_WIDTH) * 100,- height: ((bottom - top) / ANNOTATION_PAGE_HEIGHT) * 100,+ left: (left / block.pageWidth) * 100,+ top: (top / block.pageHeight) * 100,+ width: ((right - left) / block.pageWidth) * 100,+ height: ((bottom - top) / block.pageHeight) * 100,}}@@ -239,13 +8109,13 @@ function BlockOverlay({block: OcrBlockisActive: boolean}) {- const highlight = convertPolygonToHighlightArea(block.polygon)+ const highlight = convertBlockToHighlightArea(block)const style = BLOCK_STYLES[block.type]return (<divclassName={cn(- "pointer-events-none absolute z-10 rounded-[3px] border transition-[opacity,box-shadow]",+ "pointer-events-none absolute z-10 border transition-[opacity,box-shadow]",isActive? cn("opacity-100", style.overlay): cn("opacity-55", style.mutedOverlay)@@ -261,9 +8131,15 @@ function BlockOverlay({}function OcrBlockMarkdown({ text }: { text: string }) {+ const markdown = text.replace(OCR_MARKDOWN_FIGURE_CAPTION_PATTERN, (tag) =>+ tag.startsWith("</") ? "</figcaption>" : "<figcaption>"+ )+return (<div className="space-y-1 text-sm leading-5 text-foreground/90"><ReactMarkdown+ rehypePlugins={OCR_MARKDOWN_REHYPE_PLUGINS}+ remarkPlugins={OCR_MARKDOWN_REMARK_PLUGINS}components={{h1: ({ node: _node, ...props }) => (<h1@@ -295,6 +8171,9 @@ function OcrBlockMarkdown({ text }: { text: string }) {ul: ({ node: _node, ...props }) => (<ul className="my-0 list-disc space-y-0.5 pl-4" {...props} />),+ ol: ({ node: _node, ...props }) => (+ <ol className="my-0 list-decimal space-y-0.5 pl-4" {...props} />+ ),li: ({ node: _node, ...props }) => (<li className="pl-0.5 text-[13px] leading-5" {...props} />),@@ -303,6 +8182,24 @@ function OcrBlockMarkdown({ text }: { text: string }) {<table className="w-full border-collapse text-xs" {...props} /></div>),+ figure: ({ node: _node, ...props }) => (+ <figure+ className="my-0 space-y-2 rounded-md border bg-muted/20 p-2 text-[13px]"+ {...props}+ />+ ),+ figcaption: ({ node: _node, ...props }) => (+ <figcaption+ className="border-t pt-2 text-xs leading-5 text-muted-foreground"+ {...props}+ />+ ),+ caption: ({ node: _node, ...props }) => (+ <figcaption+ className="block border-t pt-2 text-xs leading-5 text-muted-foreground"+ {...props}+ />+ ),th: ({ node: _node, ...props }) => (<thclassName="border-b bg-muted px-2 py-1 text-left font-medium"@@ -314,7 +8211,7 @@ function OcrBlockMarkdown({ text }: { text: string }) {),}}>- {text}+ {markdown}</ReactMarkdown></div>)@@ -322,20 +8219,24 @@ function OcrBlockMarkdown({ text }: { text: string }) {function OcrBlocksPanel({activeBlockId,+ blocks,className,onBlockFocus,}: {activeBlockId?: string+ blocks: OcrBlock[]className?: stringonBlockFocus?: (block: OcrBlock) => void}) {+ const scrollViewportRef = React.useRef<HTMLDivElement | null>(null)const [localActiveBlockId, setLocalActiveBlockId] = React.useState(- activeBlockId ?? OCR_BLOCKS[0].id+ activeBlockId ?? blocks[0]?.id)+ const firstBlock = blocks[0]const activeBlock =- OCR_BLOCKS.find(+ blocks.find((block) => block.id === (activeBlockId ?? localActiveBlockId)- ) ?? OCR_BLOCKS[0]+ ) ?? firstBlockconst focusBlock = React.useCallback((block: OcrBlock) => {@@ -344,79 +8245,156 @@ function OcrBlocksPanel({},[onBlockFocus])+ const virtualizer = useVirtualizer({+ count: blocks.length,+ estimateSize: () => OCR_BLOCK_ROW_ESTIMATE,+ getItemKey: (index) => blocks[index]?.id ?? index,+ getScrollElement: () => scrollViewportRef.current,+ overscan: 8,+ })++ React.useEffect(() => {+ if (!firstBlock) return+ if (+ activeBlockId ||+ blocks.some((block) => block.id === localActiveBlockId)+ ) {+ return+ }++ setLocalActiveBlockId(firstBlock.id)+ }, [activeBlockId, blocks, firstBlock, localActiveBlockId])return (<asideclassName={cn("flex h-[420px] min-h-0 flex-col bg-background", className)}>- <ScrollArea className="min-h-0 flex-1" scrollFade>- <div className="p-3">- <div className="space-y-2">- {OCR_BLOCKS.map((block) => {- const isActive = block.id === activeBlock.id- const style = BLOCK_STYLES[block.type]+ <ScrollArea+ className="min-h-0 flex-1"+ scrollFade+ viewportRef={scrollViewportRef}+ >+ {blocks.length ? (+ <div+ className="relative"+ style={{+ height: virtualizer.getTotalSize() + OCR_BLOCK_LIST_PADDING * 2,+ }}+ >+ {virtualizer.getVirtualItems().map((virtualRow) => {+ const block = blocks[virtualRow.index]+ if (!block) return nullreturn (- <button- key={block.id}- type="button"- onClick={() => focusBlock(block)}- onFocus={() => focusBlock(block)}- onMouseEnter={() => focusBlock(block)}- className={cn(- "w-full rounded-lg border bg-background p-3 text-left transition-[border-color,background-color,box-shadow] hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",- isActive &&- cn("shadow-[0_0_0_1px_rgb(0_0_0_/_4%)]", style.ring)- )}+ <div+ key={virtualRow.key}+ ref={virtualizer.measureElement}+ data-index={virtualRow.index}+ className="absolute top-0 right-3 left-3"+ style={{+ transform: `translateY(${+ virtualRow.start + OCR_BLOCK_LIST_PADDING+ }px)`,+ }}>- <div className="flex items-start gap-3">- <div- className={cn(- "mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-md",- style.soft- )}- >- <HugeiconsIcon icon={style.icon} className="size-4" />- </div>- <div className="min-w-0 flex-1">- <div className="flex items-center justify-between gap-2">- <div className={cn("text-xs font-medium", style.text)}>- {style.label} · {Math.round(block.confidence * 100)}%- </div>- <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">- p. {block.page}- </div>- </div>- <div className="mt-2 text-sm text-foreground/90">- <OcrBlockMarkdown text={block.text} />- </div>- </div>- </div>- </button>+ <OcrBlockButton+ block={block}+ isActive={block.id === activeBlock?.id}+ onFocusBlock={focusBlock}+ />+ </div>)})}</div>- </div>+ ) : (+ <div className="p-3">+ <div className="rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground">+ No OCR blocks found.+ </div>+ </div>+ )}</ScrollArea></aside>)}+function OcrBlockButton({+ block,+ isActive,+ onFocusBlock,+}: {+ block: OcrBlock+ isActive: boolean+ onFocusBlock: (block: OcrBlock) => void+}) {+ const style = BLOCK_STYLES[block.type]++ return (+ <button+ type="button"+ onClick={() => onFocusBlock(block)}+ onFocus={() => onFocusBlock(block)}+ className={cn(+ "mb-2 w-full rounded-lg border bg-background p-3 text-left transition-[border-color,background-color,box-shadow] hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",+ isActive && cn("shadow-[0_0_0_1px_rgb(0_0_0_/_4%)]", style.ring)+ )}+ >+ <div className="flex items-start gap-3">+ <div+ className={cn(+ "mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-md",+ style.soft+ )}+ >+ <HugeiconsIcon icon={style.icon} className="size-4" />+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex items-center justify-between gap-2">+ <div className={cn("text-xs font-medium", style.text)}>+ {style.label} · {Math.round(block.confidence * 100)}%+ </div>+ <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">+ p. {block.page}+ </div>+ </div>+ <div className="mt-2 text-sm text-foreground/90">+ <OcrBlockMarkdown text={block.text} />+ </div>+ </div>+ </div>+ </button>+ )+}+export function OcrBlocks() {- return <OcrBlocksPanel />+ return <OcrBlocksPanel blocks={getOcrBlocks(ATTENTION_OCR_OUTPUT)} />}-export function OcrBlocksBlock() {- const [activeBlockId, setActiveBlockId] = React.useState(OCR_BLOCKS[0].id)+export function OcrBlocksBlock({+ file = PDF_URL,+ output = ATTENTION_OCR_OUTPUT,+}: {+ file?: string+ output?: ParsedOcrOutput+}) {+ const blocks = React.useMemo(() => getOcrBlocks(output), [output])+ const [activeBlockId, setActiveBlockId] = React.useState(blocks[0]?.id)const viewerRef = React.useRef<PDFViewerHandle>(null)- const activeBlock =- OCR_BLOCKS.find((block) => block.id === activeBlockId) ?? OCR_BLOCKS[0]+ const activeBlock = blocks.find((block) => block.id === activeBlockId)++ React.useEffect(() => {+ if (!blocks.length || blocks.some((block) => block.id === activeBlockId)) {+ return+ }++ setActiveBlockId(blocks[0].id)+ }, [activeBlockId, blocks])const focusBlock = React.useCallback((block: OcrBlock) => {setActiveBlockId(block.id)viewerRef.current?.scrollToPageArea(block.page,- convertPolygonToHighlightArea(block.polygon)+ convertBlockToHighlightArea(block))}, [])@@ -426,24 +8404,25 @@ export function OcrBlocksBlock() {left={<PDFViewerref={viewerRef}- file={PDF_URL}+ file={file}defaultZoom={DEFAULT_ZOOM}renderPageOverlay={({ pageNumber }) =>- OCR_BLOCKS.filter((block) => block.page === pageNumber).map(- (block) => (+ blocks+ .filter((block) => block.page === pageNumber)+ .map((block) => (<BlockOverlaykey={block.id}block={block}- isActive={activeBlock.id === block.id}+ isActive={activeBlock?.id === block.id}/>- )- )+ ))}/>}right={<OcrBlocksPanel- activeBlockId={activeBlock.id}+ activeBlockId={activeBlock?.id}+ blocks={blocks}className="h-full"onBlockFocus={focusBlock}/>@@ -633,7 +8612,7 @@ export function OcrBlocksExample() {}`const ocrBlocksSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n Heading01Icon,\n ParagraphIcon,\n Table01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport ReactMarkdown from "react-markdown"\n\nimport { cn } from "@/lib/utils"\nimport { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"\nimport { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"\nimport { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"\n\ntype OcrBlock = {\n id: string\n kind: string\n text: string\n page: number\n confidence: number\n icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]\n accentClassName: string\n polygon: { x: number; y: number }[]\n}\n\nconst PAGE_WIDTH = 792\nconst PAGE_HEIGHT = 612\nconst OCR_BLOCKS: OcrBlock[] = [\n {\n id: "title",\n kind: "Heading",\n text: "# Attention Is All You Need",\n page: 1,\n confidence: 0.99,\n icon: Heading01Icon,\n accentClassName: "border-violet-500/60 bg-violet-500/5 text-violet-600",\n polygon: [\n { x: 246, y: 188 },\n { x: 566, y: 188 },\n { x: 566, y: 222 },\n { x: 246, y: 222 },\n ],\n },\n {\n id: "abstract",\n kind: "Paragraph",\n text: "The model relies **only on attention**, avoiding recurrence and convolutions.",\n page: 1,\n confidence: 0.94,\n icon: ParagraphIcon,\n accentClassName: "border-blue-500/60 bg-blue-500/5 text-blue-600",\n polygon: [\n { x: 108, y: 346 },\n { x: 692, y: 346 },\n { x: 692, y: 458 },\n { x: 108, y: 458 },\n ],\n },\n {\n id: "table",\n kind: "Table",\n text: "- **Layer type**\\n- Path length\\n- Sequential operations",\n page: 6,\n confidence: 0.91,\n icon: Table01Icon,\n accentClassName: "border-amber-500/60 bg-amber-500/5 text-amber-700",\n polygon: [\n { x: 52, y: 58 },\n { x: 740, y: 58 },\n { x: 740, y: 190 },\n { x: 52, y: 190 },\n ],\n },\n]\n\nfunction polygonToArea(polygon: OcrBlock["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 {\n left: `${(left / PAGE_WIDTH) * 100}%`,\n top: `${(top / PAGE_HEIGHT) * 100}%`,\n width: `${((right - left) / PAGE_WIDTH) * 100}%`,\n height: `${((bottom - top) / PAGE_HEIGHT) * 100}%`,\n }\n}\n\nfunction OcrBlockMarkdown({ text }: { text: string }) {\n return (\n <div className="space-y-1 text-sm leading-5 text-foreground/90">\n <ReactMarkdown\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 h2: ({ node: _node, ...props }) => (\n <h2\n className="my-0 text-[15px] leading-5 font-semibold text-foreground"\n {...props}\n />\n ),\n h3: ({ node: _node, ...props }) => (\n <h3\n className="my-0 text-sm 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 strong: ({ node: _node, ...props }) => (\n <strong className="font-semibold text-foreground" {...props} />\n ),\n em: ({ node: _node, ...props }) => (\n <em className="text-foreground" {...props} />\n ),\n ul: ({ node: _node, ...props }) => (\n <ul className="my-0 list-disc space-y-0.5 pl-4" {...props} />\n ),\n li: ({ node: _node, ...props }) => (\n <li className="pl-0.5 text-[13px] leading-5" {...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 th: ({ node: _node, ...props }) => (\n <th\n className="border-b bg-muted px-2 py-1 text-left font-medium"\n {...props}\n />\n ),\n td: ({ node: _node, ...props }) => (\n <td className="border-t px-2 py-1" {...props} />\n ),\n }}\n >\n {text}\n </ReactMarkdown>\n </div>\n )\n}\n\nexport function OcrBlocksBlock({ file }: { file?: string }) {\n const [activeBlockId, setActiveBlockId] = React.useState(OCR_BLOCKS[0].id)\n const viewerRef = React.useRef<PDFViewerHandle>(null)\n const activeBlock =\n OCR_BLOCKS.find((block) => block.id === activeBlockId) ?? OCR_BLOCKS[0]\n\n const focusBlock = React.useCallback((block: OcrBlock) => {\n setActiveBlockId(block.id)\n viewerRef.current?.scrollToPageArea(block.page, {\n left: Number.parseFloat(polygonToArea(block.polygon).left),\n top: Number.parseFloat(polygonToArea(block.polygon).top),\n width: Number.parseFloat(polygonToArea(block.polygon).width),\n height: Number.parseFloat(polygonToArea(block.polygon).height),\n })\n }, [])\n\n return (\n <PdfBlockResizableShell\n autoSaveId="pdf-block-ocr"\n left={\n <PDFViewer\n ref={viewerRef}\n file={file}\n defaultZoom={0.75}\n renderPageOverlay={({ pageNumber }) =>\n OCR_BLOCKS.filter((block) => block.page === pageNumber).map(\n (block) => (\n <div\n key={block.id}\n className={cn(\n "pointer-events-none absolute z-10 rounded-[3px] border",\n block.id === activeBlock.id\n ? block.accentClassName\n : "border-muted-foreground/30 bg-muted/20"\n )}\n style={polygonToArea(block.polygon)}\n />\n )\n )\n }\n />\n }\n right={\n <aside className="min-h-0 bg-background">\n <ScrollArea className="h-full" scrollFade>\n <div className="space-y-2 p-3">\n {OCR_BLOCKS.map((block) => {\n const isActive = block.id === activeBlock.id\n\n return (\n <button\n key={block.id}\n type="button"\n onClick={() => focusBlock(block)}\n onFocus={() => focusBlock(block)}\n onMouseEnter={() => focusBlock(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 && block.accentClassName\n )}\n >\n <div className="flex items-start gap-3">\n <div className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-md bg-muted">\n <HugeiconsIcon icon={block.icon} className="size-4" />\n </div>\n <div className="min-w-0 flex-1">\n <div className="flex items-center justify-between gap-2">\n <div className="text-xs font-medium text-muted-foreground">\n {block.kind} - {Math.round(block.confidence * 100)}%\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 </div>\n </button>\n )\n })}\n </div>\n </ScrollArea>\n </aside>\n }\n />\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\n\nimport { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"\nimport { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"\n\ntype BoundingBox = {\n left: number\n top: number\n right: number\n bottom: number\n}\n\ntype ParsedOcrBlock = {\n id: string\n type: string\n content: string\n metadata: {\n page: { number: number; width: number; height: number }\n layoutClass?: string\n avgOcrConfidence?: number\n }\n boundingBox?: BoundingBox\n}\n\ntype ParsedOcrOutput = {\n chunks: { blocks: ParsedOcrBlock[] }[]\n}\n\nconst sampleOutput = {\n chunks: [\n {\n blocks: [\n {\n id: "block_1_eo9AoV",\n type: "heading",\n content: "# Attention Is All You Need",\n metadata: {\n page: { number: 1, width: 1275, height: 1651 },\n layoutClass: "Heading",\n avgOcrConfidence: 0.994,\n },\n boundingBox: {\n left: 440.0215455215343,\n top: 312.01490975860366,\n right: 831.4373211268961,\n bottom: 339.0022611402928,\n },\n },\n ],\n },\n ],\n} satisfies ParsedOcrOutput\n\nfunction blockToArea(block: ParsedOcrBlock) {\n const box = block.boundingBox\n const { page } = block.metadata\n\n if (!box) return undefined\n\n return {\n left: (box.left / page.width) * 100 + "%",\n top: (box.top / page.height) * 100 + "%",\n width: ((box.right - box.left) / page.width) * 100 + "%",\n height: ((box.bottom - box.top) / page.height) * 100 + "%",\n }\n}\n\nexport function OcrBlocksBlock({\n file,\n output = sampleOutput,\n}: {\n file?: string\n output?: ParsedOcrOutput\n}) {\n const blocks = output.chunks.flatMap((chunk) => chunk.blocks)\n const [activeBlockId, setActiveBlockId] = React.useState(blocks[0]?.id)\n const viewerRef = React.useRef<PDFViewerHandle>(null)\n\n return (\n <PdfBlockResizableShell\n autoSaveId="pdf-block-ocr"\n left={\n <PDFViewer\n ref={viewerRef}\n file={file}\n defaultZoom={0.75}\n renderPageOverlay={({ pageNumber }) =>\n blocks\n .filter((block) => block.metadata.page.number === pageNumber)\n .map((block) => (\n <div\n key={block.id}\n className="pointer-events-none absolute z-10 border border-blue-500/70 bg-blue-500/10"\n style={blockToArea(block)}\n />\n ))\n }\n />\n }\n right={\n <aside className="min-h-0 bg-background">\n {blocks.map((block) => (\n <button\n key={block.id}\n type="button"\n onClick={() => {\n setActiveBlockId(block.id)\n const area = blockToArea(block)\n if (!area) return\n viewerRef.current?.scrollToPageArea(block.metadata.page.number, {\n top: Number.parseFloat(area.top),\n })\n }}\n data-active={block.id === activeBlockId}\n >\n {block.content}\n </button>\n ))}\n </aside>\n }\n />\n )\n}'export function OcrBlocksSource() {return <HighlightedCodeBlock code={ocrBlocksSourceCode} />diff --git a/apps/v4/components/pdf-block-resizable-shell.tsx b/apps/v4/components/pdf-block-resizable-shell.tsxindex 52f802b..3cb3c7f 100644--- a/apps/v4/components/pdf-block-resizable-shell.tsx+++ b/apps/v4/components/pdf-block-resizable-shell.tsx@@ -26,7 +26,7 @@ type PdfBlockResizableShellProps = {export function PdfBlockResizableShell({autoSaveId,className,- heightClassName = "h-[620px]",+ heightClassName = "h-[680px]",left,leftDefaultSize,leftMinSize,diff --git a/apps/v4/components/pdf-dropzone-block.tsx b/apps/v4/components/pdf-dropzone-block.tsxindex 0560895..0940280 100644--- a/apps/v4/components/pdf-dropzone-block.tsx+++ b/apps/v4/components/pdf-dropzone-block.tsx@@ -73,6 +73,7 @@ export function PdfDropzoneBlock() {key={pdfFile.url}file={pdfFile.url}defaultZoom={DEFAULT_ZOOM}+ downloadFileName={pdfFile.name}onPdfUpload={(file) => loadPdf([file])}toolbarActions={<div className="hidden max-w-40 truncate text-xs text-muted-foreground sm:block">diff --git a/apps/v4/components/pdf-viewer-docs.tsx b/apps/v4/components/pdf-viewer-docs.tsxindex 494bdfa..020bdc1 100644--- a/apps/v4/components/pdf-viewer-docs.tsx+++ b/apps/v4/components/pdf-viewer-docs.tsx@@ -182,7 +182,7 @@ export function PdfViewerExample() {}`const pdfViewerSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n MinusSignCircleIcon,\n PlusSignCircleIcon,\n RotateClockwiseIcon,\n Search01Icon,\n SidebarLeftIcon,\n Upload01Icon,\n} from "@hugeicons/core-free-icons"\nimport { HugeiconsIcon } from "@hugeicons/react"\nimport type * as ReactPdf from "react-pdf"\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 { 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 { Input } from "@/registry/new-york-v4/ui/input"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from "@/registry/new-york-v4/ui/popover"\nimport { Separator } from "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\ntype ReactPdfModule = typeof ReactPdf\n\nexport type PDFViewerPageOverlayProps = {\n pageNumber: number\n pageWidth: number\n pageHeight: number\n scale: number\n rotation: number\n}\n\nexport type PDFViewerHandle = {\n scrollToPage: (pageNumber: number, options?: ScrollIntoViewOptions) => void\n scrollToPageArea: (\n pageNumber: number,\n area: { top: number; left?: number; width?: number; height?: number },\n options?: ScrollToOptions\n ) => void\n getViewportElement: () => HTMLDivElement | null\n}\n\nexport type PDFViewerProps = {\n file?: string\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n defaultZoom?: number\n pageWidth?: number\n pageHeight?: number\n pageNumbers?: number[]\n pageRenderBuffer?: number\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 = 0.75\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 THUMBNAIL_WIDTH = 92\ntype SearchHighlight = {\n id: string\n left: number\n top: number\n width: number\n height: number\n}\n\nfunction getPdfWorkerUrl(pdfjsVersion: string) {\n return `//unpkg.com/pdfjs-dist@${pdfjsVersion}/legacy/build/pdf.worker.min.mjs`\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 file,\n pageNumber,\n reactPdf,\n rotation,\n thumbnailAspectRatio,\n}: {\n file: string\n pageNumber: number\n reactPdf: ReactPdfModule\n rotation: number\n thumbnailAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `Page ${pageNumber}.pdf`,\n type: "application/pdf",\n source: file,\n }}\n previewAspectRatio={thumbnailAspectRatio}\n previewClassName="bg-background"\n previewContent={\n <reactPdf.Thumbnail\n pageNumber={pageNumber}\n width={THUMBNAIL_WIDTH}\n rotate={rotation}\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 renderDocumentPreview={false}\n showMetadata={false}\n className="w-full rounded-sm border shadow-xs"\n />\n )\n}\n\nfunction PDFViewerPage({\n reactPdf,\n pageNumber,\n pageStyle,\n renderedPageWidth,\n zoom,\n rotation,\n shouldRenderPage,\n searchQuery,\n pageClassName,\n renderPageOverlay,\n onPageSettled,\n onPagePointerDown,\n onPagePointerMove,\n onPagePointerUp,\n onPagePointerCancel,\n}: {\n reactPdf: ReactPdfModule\n pageNumber: number\n pageStyle: React.CSSProperties & { width: number; height: number }\n renderedPageWidth: number\n zoom: number\n rotation: number\n shouldRenderPage: boolean\n searchQuery: string\n pageClassName?: (pageNumber: number) => string | undefined\n renderPageOverlay?: (props: PDFViewerPageOverlayProps) => React.ReactNode\n onPageSettled: (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 pageRef = React.useRef<HTMLDivElement>(null)\n const [searchHighlights, setSearchHighlights] = React.useState<\n SearchHighlight[]\n >([])\n const hasSearchQuery = Boolean(searchQuery.trim())\n\n const updateSearchHighlights = React.useCallback(() => {\n const pageElement = pageRef.current\n const query = searchQuery.trim().toLowerCase()\n\n if (!pageElement || !query) {\n setSearchHighlights([])\n return\n }\n\n const textLayer = pageElement.querySelector<HTMLElement>(\n ".react-pdf__Page__textContent"\n )\n\n if (!textLayer) {\n setSearchHighlights([])\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 }, [pageNumber, searchQuery])\n\n React.useEffect(() => {\n if (!shouldRenderPage || !hasSearchQuery) {\n setSearchHighlights([])\n return\n }\n\n const frame = window.requestAnimationFrame(updateSearchHighlights)\n return () => window.cancelAnimationFrame(frame)\n }, [hasSearchQuery, shouldRenderPage, updateSearchHighlights])\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={rotation}\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(MAX_DEVICE_PIXEL_RATIO, 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={() => onPageSettled(pageNumber)}\n onRenderTextLayerSuccess={updateSearchHighlights}\n onRenderError={() => onPageSettled(pageNumber)}\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-muted/30 shadow-xs" />\n )}\n {renderPageOverlay?.({\n pageNumber,\n pageWidth: pageStyle.width,\n pageHeight: pageStyle.height,\n scale: zoom,\n rotation,\n })}\n </div>\n )\n}\n\nexport const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(\n function PDFViewer(\n {\n file,\n className,\n defaultThumbnailSidebarOpen = true,\n defaultZoom = DEFAULT_ZOOM,\n pageWidth = DEFAULT_PAGE_WIDTH,\n pageHeight = DEFAULT_PAGE_HEIGHT,\n pageNumbers,\n pageRenderBuffer = DEFAULT_PAGE_RENDER_BUFFER,\n showRotateControls = 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 [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 [rotation, setRotation] = React.useState(0)\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 [loadError, setLoadError] = React.useState(false)\n const viewportRef = React.useRef<HTMLDivElement>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const thumbnailClickScrollYRef = React.useRef<number | null>(null)\n\n React.useEffect(() => {\n setPdfFile(file ?? "")\n setLoadError(false)\n setIsDocumentLoading(Boolean(file))\n setIsFirstPageRendering(Boolean(file))\n setSettledPageNumbers(new Set())\n setNumPages(0)\n setActivePage(1)\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 isRotated = Math.abs(Math.round(rotation / 90)) % 2 === 1\n const renderedPageWidth = (isRotated ? pageHeight : pageWidth) * zoom\n const renderedPageHeight = (isRotated ? pageWidth : pageHeight) * zoom\n const hasPdfFile = Boolean(pdfFile)\n const controlsDisabled = !hasPdfFile || !reactPdf || !numPages\n const isLoading =\n hasPdfFile && (!reactPdf || isDocumentLoading || isFirstPageRendering)\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const thumbnailIsRotated = Math.abs(Math.round(rotation / 90)) % 2 === 1\n const thumbnailSize = {\n width: THUMBNAIL_WIDTH,\n height: Math.round(\n THUMBNAIL_WIDTH *\n (thumbnailIsRotated ? pageWidth / pageHeight : pageHeight / pageWidth)\n ),\n }\n const thumbnailAspectRatio = thumbnailSize.width / thumbnailSize.height\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 let closestPage = renderedPageNumbers[0] ?? 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>("[data-pdf-viewer-page]")\n .forEach((page) => {\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = Number(page.dataset.pdfViewerPage || "1")\n }\n })\n\n setActivePage((currentPage) => {\n if (currentPage === closestPage) return currentPage\n onActivePageChange?.(closestPage)\n return closestPage\n })\n }, [onActivePageChange, renderedPageNumbers])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !numPages) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [numPages, updateActivePageFromViewport])\n\n React.useImperativeHandle(\n ref,\n () => ({\n scrollToPage: (pageNumber, options) => {\n const page = viewportRef.current?.querySelector<HTMLElement>(\n `[data-pdf-viewer-page="${pageNumber}"]`\n )\n\n page?.scrollIntoView({\n block: "start",\n inline: "nearest",\n ...options,\n })\n },\n scrollToPageArea: (pageNumber, area, options) => {\n const viewport = viewportRef.current\n const page = viewport?.querySelector<HTMLElement>(\n `[data-pdf-viewer-page="${pageNumber}"]`\n )\n\n if (!viewport || !page) return\n\n const pageTop =\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop\n const targetTop =\n pageTop +\n (area.top / 100) * page.getBoundingClientRect().height -\n 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 )\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\n const viewport = viewportRef.current\n const page = viewport?.querySelector<HTMLElement>(\n `[data-pdf-viewer-page="${pageNumber}"]`\n )\n\n if (!viewport || !page) {\n restoreWindowScroll(windowScrollY)\n return\n }\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n restoreWindowScroll(windowScrollY)\n window.setTimeout(() => {\n if (thumbnailClickScrollYRef.current === windowScrollY) {\n thumbnailClickScrollYRef.current = null\n }\n }, 350)\n },\n [restoreWindowScroll]\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 handleLoadStart = React.useCallback(() => {\n setIsDocumentLoading(true)\n setIsFirstPageRendering(true)\n setLoadError(false)\n setNumPages(0)\n setActivePage(1)\n setSettledPageNumbers(new Set())\n onActivePageChange?.(1)\n setSearchQuery("")\n setSearchDraft("")\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [onActivePageChange])\n\n const handleLoadSuccess = React.useCallback(\n ({ numPages: nextNumPages }: { numPages: number }) => {\n setNumPages(nextNumPages)\n setIsDocumentLoading(false)\n setIsFirstPageRendering(true)\n setSettledPageNumbers(new Set())\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 [onActivePageChange, onDocumentLoadSuccess]\n )\n\n const handleLoadError = React.useCallback(() => {\n setIsDocumentLoading(false)\n setIsFirstPageRendering(false)\n setLoadError(true)\n setNumPages(0)\n }, [])\n\n const handlePageSettled = React.useCallback(\n (pageNumber: 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\n if (pageNumber === firstRenderedPage) {\n setIsFirstPageRendering(false)\n }\n },\n [firstRenderedPage]\n )\n\n React.useEffect(() => {\n setSettledPageNumbers(new Set())\n setIsFirstPageRendering(Boolean(pdfFile))\n }, [pdfFile, renderedPageWidth, rotation])\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 <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">\n <div className="flex 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 items-center gap-1">\n {showRotateControls ? (\n <>\n <ToolbarTooltip label="Rotate counterclockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate counterclockwise"\n disabled={controlsDisabled}\n onClick={() => setRotation((value) => value - 90)}\n >\n <HugeiconsIcon\n icon={RotateClockwiseIcon}\n className="size-4 -scale-x-100"\n />\n </Button>\n </ToolbarTooltip>\n <ToolbarTooltip label="Rotate clockwise">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Rotate clockwise"\n disabled={controlsDisabled}\n onClick={() => setRotation((value) => value + 90)}\n >\n <HugeiconsIcon\n icon={RotateClockwiseIcon}\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\n <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(ZOOM_OPTIONS[Math.max(0, currentIndex - 1)] ?? zoom)\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 icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <Popover>\n <ToolbarTooltip label="Search text">\n <PopoverTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Search text"\n disabled={controlsDisabled}\n >\n <HugeiconsIcon icon={Search01Icon} className="size-4" />\n </Button>\n </PopoverTrigger>\n </ToolbarTooltip>\n <PopoverContent align="end" className="w-64">\n <SearchInput\n value={searchDraft}\n onValueChange={setSearchDraft}\n onApply={() => setSearchQuery(searchDraft)}\n onClear={() => {\n setSearchDraft("")\n setSearchQuery("")\n }}\n />\n </PopoverContent>\n </Popover>\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n {showUpload ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <ToolbarTooltip label="Upload PDF">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Upload PDF"\n render={\n <label>\n <input\n type="file"\n accept="application/pdf,.pdf"\n className="sr-only"\n onChange={(event) => {\n const nextFile = event.target.files?.[0]\n\n if (nextFile) {\n handleUpload(nextFile)\n event.currentTarget.value = ""\n }\n }}\n />\n <HugeiconsIcon\n icon={Upload01Icon}\n className="size-4"\n />\n </label>\n }\n />\n </ToolbarTooltip>\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\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 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 >\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={Boolean(sidebarOpen && !isLoading && !loadError)}\n >\n <ScrollArea className="h-full" scrollFade>\n <div className="p-4">\n <div className="flex flex-col items-center gap-3">\n {renderedPageNumbers.map((pageNumber) => (\n <Button\n key={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 text-muted-foreground shadow-none hover:bg-sidebar-accent",\n pageNumber === activePage && "bg-sidebar-accent"\n )}\n onFocus={(event) => event.currentTarget.blur()}\n onMouseDown={preserveThumbnailClickScroll}\n onPointerDown={preserveThumbnailClickScroll}\n onClick={() => scrollToPage(pageNumber)}\n >\n <PDFSidebarThumbnail\n file={pdfFile}\n pageNumber={pageNumber}\n reactPdf={reactPdf}\n rotation={rotation}\n thumbnailAspectRatio={thumbnailAspectRatio}\n />\n {pageNumber}\n </Button>\n ))}\n </div>\n </div>\n </ScrollArea>\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 className="flex min-h-full w-max min-w-full flex-col items-center justify-start gap-6 p-6">\n {renderedPageNumbers.map((pageNumber) => {\n const shouldRenderPage =\n Math.abs(pageNumber - activePage) <= pageRenderBuffer ||\n settledPageNumbers.has(pageNumber) ||\n renderedPageNumbers.length <= pageRenderBuffer * 2 + 1\n const pageStyle = {\n width: renderedPageWidth,\n height: renderedPageHeight,\n }\n const pageSearchQuery =\n searchQuery.trim() &&\n Math.abs(pageNumber - activePage) <= 1\n ? searchQuery\n : ""\n\n return (\n <PDFViewerPage\n key={pageNumber}\n reactPdf={reactPdf}\n pageNumber={pageNumber}\n pageStyle={pageStyle}\n renderedPageWidth={renderedPageWidth}\n zoom={zoom}\n rotation={rotation}\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 )\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 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 type { PDFDocumentProxy } from "pdfjs-dist"\nimport type * as ReactPdf from "react-pdf"\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 { 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 { Input } from "@/registry/new-york-v4/ui/input"\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from "@/registry/new-york-v4/ui/popover"\nimport { Separator } from "@/registry/new-york-v4/ui/separator"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/registry/new-york-v4/ui/tooltip"\n\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 PDFViewerProps = {\n file?: string\n className?: string\n defaultThumbnailSidebarOpen?: boolean\n defaultZoom?: number\n pageWidth?: number\n pageHeight?: number\n pageNumbers?: number[]\n pageRenderBuffer?: number\n downloadFileName?: string\n showDownload?: 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 = 0.75\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 THUMBNAIL_WIDTH = 92\ntype SearchHighlight = {\n id: string\n left: number\n top: number\n width: number\n height: number\n}\n\nfunction getPdfWorkerUrl(pdfjsVersion: string) {\n return `//unpkg.com/pdfjs-dist@${pdfjsVersion}/legacy/build/pdf.worker.min.mjs`\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 getDocumentPageMetrics(pdf: PDFDocumentProxy) {\n const pageEntries = await Promise.all(\n Array.from({ length: pdf.numPages }, async (_, index) => {\n const pageNumber = index + 1\n const page = await pdf.getPage(pageNumber)\n const viewport = page.getViewport({ scale: 1, rotation: 0 })\n\n return [\n pageNumber,\n {\n width: viewport.width,\n height: viewport.height,\n rotation: normalizeRotation(page.rotate),\n },\n ] as const\n })\n )\n\n return new Map<number, PDFPageMetrics>(pageEntries)\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 file,\n pageMetrics,\n pageNumber,\n reactPdf,\n rotation,\n thumbnailAspectRatio,\n}: {\n file: string\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 source: file,\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 renderDocumentPreview={false}\n showMetadata={false}\n className="w-[92px] rounded-md border-0 shadow-xs ring-0"\n />\n )\n}\n\nfunction PDFViewerPage({\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 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) => 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\n const updateSearchHighlights = React.useCallback(() => {\n const pageElement = pageRef.current\n const query = searchQuery.trim().toLowerCase()\n\n if (!pageElement || !query) {\n setSearchHighlights([])\n return\n }\n\n const textLayer = pageElement.querySelector<HTMLElement>(\n ".react-pdf__Page__textContent"\n )\n\n if (!textLayer) {\n setSearchHighlights([])\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 }, [pageNumber, searchQuery])\n\n React.useEffect(() => {\n if (!shouldRenderPage || !hasSearchQuery) {\n setSearchHighlights([])\n return\n }\n\n const frame = window.requestAnimationFrame(updateSearchHighlights)\n return () => window.cancelAnimationFrame(frame)\n }, [hasSearchQuery, shouldRenderPage, updateSearchHighlights])\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(MAX_DEVICE_PIXEL_RATIO, 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={() => onPageSettled(pageNumber)}\n onRenderTextLayerSuccess={updateSearchHighlights}\n onRenderError={() => onPageSettled(pageNumber)}\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-muted/30 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 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 downloadFileName,\n showDownload = true,\n showRotateControls = 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 [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 [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\n React.useEffect(() => {\n setPdfFile(file ?? "")\n setLoadError(false)\n setIsDocumentLoading(Boolean(file))\n setIsFirstPageRendering(Boolean(file))\n setSettledPageNumbers(new Set())\n setNumPages(0)\n setActivePage(1)\n setPageMetrics(new Map())\n setPageRotationDeltas(new Map())\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 resolvedDownloadFileName = React.useMemo(\n () => getPdfDownloadFileName(downloadFileName, pdfFile),\n [downloadFileName, pdfFile]\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\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 let closestPage = renderedPageNumbers[0] ?? 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>("[data-pdf-viewer-page]")\n .forEach((page) => {\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = Number(page.dataset.pdfViewerPage || "1")\n }\n })\n\n setActivePage((currentPage) => {\n if (currentPage === closestPage) return currentPage\n onActivePageChange?.(closestPage)\n return closestPage\n })\n }, [onActivePageChange, renderedPageNumbers])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !numPages) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [numPages, updateActivePageFromViewport])\n\n React.useImperativeHandle(\n ref,\n () => ({\n scrollToPage: (pageNumber, options) => {\n const page = viewportRef.current?.querySelector<HTMLElement>(\n `[data-pdf-viewer-page="${pageNumber}"]`\n )\n\n page?.scrollIntoView({\n block: "start",\n inline: "nearest",\n ...options,\n })\n },\n scrollToPageArea: (pageNumber, area, options) => {\n const viewport = viewportRef.current\n const page = viewport?.querySelector<HTMLElement>(\n `[data-pdf-viewer-page="${pageNumber}"]`\n )\n\n if (!viewport || !page) return\n\n const pageTop =\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop\n const targetTop =\n pageTop +\n (area.top / 100) * page.getBoundingClientRect().height -\n 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 )\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\n const viewport = viewportRef.current\n const page = viewport?.querySelector<HTMLElement>(\n `[data-pdf-viewer-page="${pageNumber}"]`\n )\n\n if (!viewport || !page) {\n restoreWindowScroll(windowScrollY)\n return\n }\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n restoreWindowScroll(windowScrollY)\n window.setTimeout(() => {\n if (thumbnailClickScrollYRef.current === windowScrollY) {\n thumbnailClickScrollYRef.current = null\n }\n }, 350)\n },\n [restoreWindowScroll]\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 const viewport = thumbnailViewportRef.current\n const thumbnail = viewport?.querySelector<HTMLElement>(\n `[data-pdf-viewer-thumbnail="${activePage}"]`\n )\n\n if (!viewport || !thumbnail) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const thumbnailRect = thumbnail.getBoundingClientRect()\n const targetTop =\n thumbnailRect.top -\n viewportRect.top +\n viewport.scrollTop -\n (viewport.clientHeight - thumbnail.offsetHeight) / 2\n\n viewport.scrollTo({\n top: Math.max(0, targetTop),\n behavior: "auto",\n })\n }, [activePage])\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 setNumPages(0)\n setActivePage(1)\n setPageMetrics(new Map())\n setPageRotationDeltas(new Map())\n setSettledPageNumbers(new Set())\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\n setNumPages(nextNumPages)\n setIsFirstPageRendering(true)\n setSettledPageNumbers(new Set())\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 setPageMetrics(await getDocumentPageMetrics(pdf))\n setIsDocumentLoading(false)\n } catch {\n setPageMetrics(new Map())\n setIsDocumentLoading(false)\n }\n },\n [onActivePageChange, onDocumentLoadSuccess]\n )\n\n const handleLoadError = React.useCallback(() => {\n setIsDocumentLoading(false)\n setIsFirstPageRendering(false)\n setLoadError(true)\n setNumPages(0)\n setPageMetrics(new Map())\n setPageRotationDeltas(new Map())\n }, [])\n\n const handlePageSettled = React.useCallback(\n (pageNumber: 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\n if (pageNumber === firstRenderedPage) {\n setIsFirstPageRendering(false)\n }\n },\n [firstRenderedPage]\n )\n\n React.useEffect(() => {\n setSettledPageNumbers(new Set())\n setIsFirstPageRendering(Boolean(pdfFile))\n }, [pdfFile, pageMetrics])\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 <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">\n <div className="flex 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 items-center gap-1">\n {showRotateControls ? (\n <>\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 <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n </>\n ) : null}\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(ZOOM_OPTIONS[Math.max(0, currentIndex - 1)] ?? zoom)\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 icon={PlusSignCircleIcon} className="size-4" />\n </Button>\n </ToolbarTooltip>\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 {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n {showUpload ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n <ToolbarTooltip label="Upload PDF">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Upload PDF"\n render={\n <label>\n <input\n type="file"\n accept="application/pdf,.pdf"\n className="sr-only"\n onChange={(event) => {\n const nextFile = event.target.files?.[0]\n\n if (nextFile) {\n handleUpload(nextFile)\n event.currentTarget.value = ""\n }\n }}\n />\n <HugeiconsIcon\n icon={Upload01Icon}\n className="size-4"\n />\n </label>\n }\n />\n </ToolbarTooltip>\n </>\n ) : null}\n </div>\n </TooltipProvider>\n </div>\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 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 >\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 <ScrollArea\n className="h-full"\n scrollFade\n viewportRef={thumbnailViewportRef}\n >\n <div className="p-4">\n <div className="flex flex-col items-center gap-3">\n {renderedPageNumbers.map((pageNumber) => {\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 <Button\n key={pageNumber}\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) => event.currentTarget.blur()}\n onMouseDown={preserveThumbnailClickScroll}\n onPointerDown={preserveThumbnailClickScroll}\n onClick={() => scrollToPage(pageNumber)}\n >\n <PDFSidebarThumbnail\n file={pdfFile}\n pageMetrics={metrics}\n pageNumber={pageNumber}\n reactPdf={reactPdf}\n rotation={rotationDelta}\n thumbnailAspectRatio={thumbnailAspectRatio}\n />\n {pageNumber}\n </Button>\n )\n })}\n </div>\n </div>\n </ScrollArea>\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 className="flex min-h-full w-max min-w-full flex-col items-center justify-start gap-6 p-6">\n {renderedPageNumbers.map((pageNumber) => {\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 Math.abs(pageNumber - activePage) <= pageRenderBuffer ||\n settledPageNumbers.has(pageNumber) ||\n renderedPageNumbers.length <= pageRenderBuffer * 2 + 1\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 <PDFViewerPage\n key={pageNumber}\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 )\n })}\n </div>\n </ScrollArea>\n </div>\n </reactPdf.Document>\n ) : null}\n </div>\n </div>\n )\n }\n)\n'export function PdfViewerDemo() {const [isCodeVisible, setIsCodeVisible] = React.useState(false)diff --git a/apps/v4/components/ui/document-viewer-sidebar.tsx b/apps/v4/components/ui/document-viewer-sidebar.tsxindex 57ae675..e31ad51 100644--- a/apps/v4/components/ui/document-viewer-sidebar.tsx+++ b/apps/v4/components/ui/document-viewer-sidebar.tsx@@ -70,7 +70,7 @@ export function DocumentViewerSidebarSkeleton({ inline }: { inline: boolean }) {return (<div className="w-40 shrink-0 border-r bg-sidebar p-4">- <div className="mx-auto h-28 w-20 rounded-sm border bg-background shadow-xs">+ <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs"><div className="h-full animate-pulse bg-muted" /></div><div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />diff --git a/apps/v4/components/ui/docx-editor.tsx b/apps/v4/components/ui/docx-editor.tsxindex 4b1ddfb..3208abf 100644--- a/apps/v4/components/ui/docx-editor.tsx+++ b/apps/v4/components/ui/docx-editor.tsx@@ -690,7 +690,7 @@ function DocxSidebarThumbnail({type: DOCX_MIME_TYPE,}}previewAspectRatio={previewAspectRatio}- previewClassName="bg-white"+ previewClassName="rounded-md bg-white"previewContent={<canvasref={canvasRef}@@ -704,8 +704,8 @@ function DocxSidebarThumbnail({hasError={hasError}showMetadata={false}className={cn(- "w-full rounded-sm border shadow-xs transition-[border-color,box-shadow] duration-150",- isActive && "border-primary shadow-sm"+ "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",+ isActive && "shadow-sm")}/>)@@ -1899,7 +1899,7 @@ function DocxEditorContent({<div className="p-4">{isLoadingDocument ? (<>- <div className="mx-auto h-28 w-20 rounded-sm border bg-background shadow-xs">+ <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs"><div className="h-full animate-pulse bg-muted" /></div><div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />@@ -1913,9 +1913,11 @@ function DocxEditorContent({variant="ghost"size="sm"className={cn(- "!h-auto w-full flex-col items-center gap-2 p-2 text-xs text-muted-foreground shadow-none hover:bg-sidebar-accent",+ "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",thumbnail.pageNumber === activePage &&- "bg-sidebar-accent"+ "bg-sidebar-accent text-foreground",+ thumbnail.pageNumber !== activePage &&+ "text-muted-foreground")}onFocus={(event) => event.currentTarget.blur()}onClick={() => scrollToPage(thumbnail.pageNumber)}diff --git a/apps/v4/components/ui/docx-viewer.tsx b/apps/v4/components/ui/docx-viewer.tsxindex c1c28e6..31e89d5 100644--- a/apps/v4/components/ui/docx-viewer.tsx+++ b/apps/v4/components/ui/docx-viewer.tsx@@ -424,7 +424,7 @@ function DocxSidebarThumbnail({type: DOCX_MIME_TYPE,}}previewAspectRatio={previewAspectRatio}- previewClassName="bg-white"+ previewClassName="rounded-md bg-white"previewContent={<canvasref={canvasRef}@@ -438,8 +438,8 @@ function DocxSidebarThumbnail({hasError={hasError}showMetadata={false}className={cn(- "w-full rounded-sm border shadow-xs transition-[border-color,box-shadow] duration-150",- isActive && "border-primary shadow-sm"+ "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",+ isActive && "shadow-sm")}/>)@@ -447,7 +447,7 @@ function DocxSidebarThumbnail({export function DocxViewerPreview({className,- defaultThumbnailSidebarOpen = true,+ defaultThumbnailSidebarOpen = false,defaultIsDark = false,fileName,isDark: controlledIsDark,@@ -781,7 +781,7 @@ function DocxViewerContent({<div className="p-4">{isLoadingDocument ? (<>- <div className="mx-auto h-28 w-20 rounded-sm border bg-background shadow-xs">+ <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs"><div className="h-full animate-pulse bg-muted" /></div><div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />@@ -795,9 +795,11 @@ function DocxViewerContent({variant="ghost"size="sm"className={cn(- "!h-auto w-full flex-col items-center gap-2 p-2 text-xs text-muted-foreground shadow-none hover:bg-sidebar-accent",+ "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",thumbnail.pageNumber === activePage &&- "bg-sidebar-accent"+ "bg-sidebar-accent text-foreground",+ thumbnail.pageNumber !== activePage &&+ "text-muted-foreground")}onFocus={(event) => event.currentTarget.blur()}onClick={() => scrollToPage(thumbnail.pageNumber)}diff --git a/apps/v4/components/ui/file-thumbnail.tsx b/apps/v4/components/ui/file-thumbnail.tsxindex ce57b4f..0ba3f81 100644--- a/apps/v4/components/ui/file-thumbnail.tsx+++ b/apps/v4/components/ui/file-thumbnail.tsx@@ -314,9 +314,7 @@ function FileThumbnailShell({previewImageUrl && failedPreviewImageUrl === previewImageUrl)const isImageLoading = Boolean(- previewImageUrl &&- loadedPreviewImageUrl !== previewImageUrl &&- !imageFailed+ previewImageUrl && loadedPreviewImageUrl !== previewImageUrl && !imageFailed)const showLoading = isLoading || isImageLoadingconst hasPreviewContent = Boolean(previewContent)@@ -379,7 +377,7 @@ function FileThumbnailShell({><divclassName={cn(- "relative aspect-square overflow-hidden bg-muted",+ "relative aspect-square overflow-hidden bg-muted [contain:layout_paint]",previewClassName)}style={@@ -397,10 +395,8 @@ function FileThumbnailShell({loading="lazy"decoding="async"className={cn(- "size-full object-cover transition-[opacity,filter,transform] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",- showLoading- ? "scale-[1.01] opacity-0 blur-sm"- : "blur-0 scale-100 opacity-100"+ "absolute inset-0 block size-full object-cover transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",+ showLoading ? "opacity-0 blur-sm" : "blur-0 opacity-100")}onLoad={(event) => {markImageLoaded(event.currentTarget, previewImageUrl)@@ -419,10 +415,8 @@ function FileThumbnailShell({{previewContent ? (<divclassName={cn(- "size-full transition-[opacity,filter,transform] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",- showLoading- ? "scale-[1.01] opacity-0 blur-sm"- : "blur-0 scale-100 opacity-100"+ "absolute inset-0 size-full transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",+ showLoading ? "opacity-0 blur-sm" : "blur-0 opacity-100")}>{previewContent}@@ -579,7 +573,7 @@ function PdfFileThumbnail({<divref={rootRef}aria-hidden="true"- className="pointer-events-none fixed top-0 left-[-10000px] w-[560px] overflow-hidden bg-white"+ className="pointer-events-none fixed top-0 left-0 -z-10 w-[560px] overflow-hidden bg-white opacity-0 [contain:layout_paint]"><reactPdf.Documentfile={sourceUrl}@@ -839,7 +833,7 @@ function DocxFileThumbnail({<divref={hiddenDocxViewerRef}aria-hidden="true"- className="pointer-events-none fixed top-[100vh] left-0 -z-10 h-[1056px] w-[816px] overflow-hidden bg-white"+ className="pointer-events-none fixed top-0 left-0 -z-10 h-[1056px] w-[816px] overflow-hidden bg-white opacity-0 [contain:layout_paint]"><div className="w-[816px]"><DocxEditorViewerdiff --git a/apps/v4/components/ui/pdf-viewer.tsx b/apps/v4/components/ui/pdf-viewer.tsxindex d998ca9..fc7c724 100644--- a/apps/v4/components/ui/pdf-viewer.tsx+++ b/apps/v4/components/ui/pdf-viewer.tsx@@ -2,6 +2,7 @@import * as React from "react"import {+ Download01Icon,MinusSignCircleIcon,PlusSignCircleIcon,RotateClockwiseIcon,@@ -10,6 +11,7 @@ import {Upload01Icon,} from "@hugeicons/core-free-icons"import { HugeiconsIcon } from "@hugeicons/react"+import type { PDFDocumentProxy } from "pdfjs-dist"import type * as ReactPdf from "react-pdf"import { cn } from "@/lib/utils"@@ -45,6 +47,13 @@ import {} from "@/registry/new-york-v4/ui/tooltip"type ReactPdfModule = typeof ReactPdf+type PageRotationDeltas = Map<number, number>++type PDFPageMetrics = {+ width: number+ height: number+ rotation: number+}export type PDFViewerPageOverlayProps = {pageNumber: number@@ -73,6 +82,8 @@ export type PDFViewerProps = {pageHeight?: numberpageNumbers?: number[]pageRenderBuffer?: number+ downloadFileName?: string+ showDownload?: booleanshowRotateControls?: booleanshowUpload?: booleantoolbarActions?: React.ReactNode@@ -118,6 +129,118 @@ function getPdfWorkerUrl(pdfjsVersion: string) {return `//unpkg.com/pdfjs-dist@${pdfjsVersion}/legacy/build/pdf.worker.min.mjs`}+function normalizeRotation(rotation: number) {+ return (((Math.round(rotation / 90) * 90) % 360) + 360) % 360+}++function isQuarterTurn(rotation: number) {+ return Math.abs(normalizeRotation(rotation) / 90) % 2 === 1+}++function getPageDimensions(metrics: PDFPageMetrics, rotation: number) {+ return isQuarterTurn(rotation)+ ? { width: metrics.height, height: metrics.width }+ : { width: metrics.width, height: metrics.height }+}++function ensurePdfExtension(fileName: string) {+ return fileName.toLowerCase().endsWith(".pdf") ? fileName : `${fileName}.pdf`+}++function getPdfDownloadFileName(fileName: string | undefined, file: string) {+ if (fileName?.trim()) return ensurePdfExtension(fileName.trim())++ const pathname = file.split(/[?#]/)[0] ?? ""+ const rawName = pathname.split("/").pop() || "document.pdf"++ try {+ return ensurePdfExtension(decodeURIComponent(rawName))+ } catch {+ return ensurePdfExtension(rawName)+ }+}++function getRotatedPdfDownloadFileName(fileName: string) {+ return fileName.replace(/\.pdf$/i, "-rotated.pdf")+}++function downloadBlob(blob: Blob, fileName: string) {+ const url = URL.createObjectURL(blob)+ const anchor = document.createElement("a")++ anchor.href = url+ anchor.download = fileName+ anchor.rel = "noopener"+ document.body.append(anchor)+ anchor.click()+ anchor.remove()+ window.setTimeout(() => URL.revokeObjectURL(url), 0)+}++async function getDocumentPageMetrics(pdf: PDFDocumentProxy) {+ const pageEntries = await Promise.all(+ Array.from({ length: pdf.numPages }, async (_, index) => {+ const pageNumber = index + 1+ const page = await pdf.getPage(pageNumber)+ const viewport = page.getViewport({ scale: 1, rotation: 0 })++ return [+ pageNumber,+ {+ width: viewport.width,+ height: viewport.height,+ rotation: normalizeRotation(page.rotate),+ },+ ] as const+ })+ )++ return new Map<number, PDFPageMetrics>(pageEntries)+}++async function downloadPdfWithPageRotations({+ file,+ fileName,+ pageRotationDeltas,+}: {+ file: string+ fileName: string+ pageRotationDeltas: PageRotationDeltas+}) {+ const response = await fetch(file)++ if (!response.ok) {+ throw new Error(`Failed to download PDF (${response.status})`)+ }++ const [{ PDFDocument, degrees }, pdfBytes] = await Promise.all([+ import("pdf-lib"),+ response.arrayBuffer(),+ ])+ const pdfDocument = await PDFDocument.load(pdfBytes)++ pdfDocument.getPages().forEach((page, index) => {+ const pageNumber = index + 1+ const rotationDelta = pageRotationDeltas.get(pageNumber) ?? 0++ if (!rotationDelta) return++ page.setRotation(+ degrees(normalizeRotation(page.getRotation().angle + rotationDelta))+ )+ })++ const nextPdfBytes = await pdfDocument.save()+ const nextPdfBuffer = new ArrayBuffer(nextPdfBytes.byteLength)+ new Uint8Array(nextPdfBuffer).set(nextPdfBytes)+ const hasPageRotationChanges = pageRotationDeltas.size > 0++ downloadBlob(+ new Blob([nextPdfBuffer], { type: "application/pdf" }),+ hasPageRotationChanges ? getRotatedPdfDownloadFileName(fileName) : fileName+ )+}+function PDFViewerLoadingSkeleton({sidebarOpen,sidebarInline,@@ -193,17 +316,21 @@ function SearchInput({function PDFSidebarThumbnail({file,+ pageMetrics,pageNumber,reactPdf,rotation,thumbnailAspectRatio,}: {file: string+ pageMetrics: PDFPageMetricspageNumber: numberreactPdf: ReactPdfModulerotation: numberthumbnailAspectRatio: number}) {+ const effectiveRotation = normalizeRotation(pageMetrics.rotation + rotation)+return (<FileThumbnailfile={{@@ -212,29 +339,29 @@ function PDFSidebarThumbnail({source: file,}}previewAspectRatio={thumbnailAspectRatio}- previewClassName="bg-background"+ previewClassName="rounded-md bg-white"previewContent={<reactPdf.ThumbnailpageNumber={pageNumber}width={THUMBNAIL_WIDTH}- rotate={rotation}+ rotate={effectiveRotation}className="flex size-full items-center justify-center [&_.react-pdf__Thumbnail__page]:!m-0 [&_.react-pdf__Thumbnail__page]:!h-auto [&_.react-pdf__Thumbnail__page]:!w-full [&_.react-pdf__Thumbnail__page]:overflow-hidden [&_canvas]:!h-auto [&_canvas]:!w-full"/>}renderDocumentPreview={false}showMetadata={false}- className="w-full rounded-sm border shadow-xs"+ className="w-[92px] rounded-md border-0 shadow-xs ring-0"/>)}function PDFViewerPage({+ effectiveRotation,reactPdf,pageNumber,pageStyle,renderedPageWidth,zoom,- rotation,shouldRenderPage,searchQuery,pageClassName,@@ -245,12 +372,12 @@ function PDFViewerPage({onPagePointerUp,onPagePointerCancel,}: {+ effectiveRotation: numberreactPdf: ReactPdfModulepageNumber: numberpageStyle: React.CSSProperties & { width: number; height: number }renderedPageWidth: numberzoom: number- rotation: numbershouldRenderPage: booleansearchQuery: stringpageClassName?: (pageNumber: number) => string | undefined@@ -359,7 +486,7 @@ function PDFViewerPage({<reactPdf.PagepageNumber={pageNumber}width={renderedPageWidth}- rotate={rotation}+ rotate={effectiveRotation}className="overflow-hidden border bg-background shadow-xs"renderAnnotationLayer={false}renderTextLayer={hasSearchQuery}@@ -402,7 +529,7 @@ function PDFViewerPage({pageWidth: pageStyle.width,pageHeight: pageStyle.height,scale: zoom,- rotation,+ rotation: effectiveRotation,})}</div>)@@ -413,12 +540,14 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>({file,className,- defaultThumbnailSidebarOpen = true,+ defaultThumbnailSidebarOpen = false,defaultZoom = DEFAULT_ZOOM,pageWidth = DEFAULT_PAGE_WIDTH,pageHeight = DEFAULT_PAGE_HEIGHT,pageNumbers,pageRenderBuffer = DEFAULT_PAGE_RENDER_BUFFER,+ downloadFileName,+ showDownload = true,showRotateControls = true,showUpload = true,toolbarActions,@@ -442,7 +571,11 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(const [numPages, setNumPages] = React.useState(0)const [activePage, setActivePage] = React.useState(1)const [zoom, setZoom] = React.useState(defaultZoom)- const [rotation, setRotation] = React.useState(0)+ const [pageRotationDeltas, setPageRotationDeltas] =+ React.useState<PageRotationDeltas>(() => new Map())+ const [pageMetrics, setPageMetrics] = React.useState<+ Map<number, PDFPageMetrics>+ >(() => new Map())const [sidebarOpen, setSidebarOpen] = React.useState(defaultThumbnailSidebarOpen)@@ -454,7 +587,10 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(Set<number>>(() => new Set())const [loadError, setLoadError] = React.useState(false)+ const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)const viewportRef = React.useRef<HTMLDivElement>(null)+ const thumbnailViewportRef = React.useRef<HTMLDivElement>(null)+ const wasThumbnailSidebarVisibleRef = React.useRef(false)const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()const thumbnailClickScrollYRef = React.useRef<number | null>(null)@@ -466,6 +602,8 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(setSettledPageNumbers(new Set())setNumPages(0)setActivePage(1)+ setPageMetrics(new Map())+ setPageRotationDeltas(new Map())}, [file])React.useEffect(() => {@@ -509,23 +647,27 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(}, [numPages, pageNumbers])const firstRenderedPage = renderedPageNumbers[0] ?? 1- const isRotated = Math.abs(Math.round(rotation / 90)) % 2 === 1- const renderedPageWidth = (isRotated ? pageHeight : pageWidth) * zoom- const renderedPageHeight = (isRotated ? pageWidth : pageHeight) * zoom+ const defaultPageMetrics = React.useMemo<PDFPageMetrics>(+ () => ({ width: pageWidth, height: pageHeight, rotation: 0 }),+ [pageHeight, pageWidth]+ )+ const getPageMetrics = React.useCallback(+ (pageNumber: number) => pageMetrics.get(pageNumber) ?? defaultPageMetrics,+ [defaultPageMetrics, pageMetrics]+ )+ const resolvedDownloadFileName = React.useMemo(+ () => getPdfDownloadFileName(downloadFileName, pdfFile),+ [downloadFileName, pdfFile]+ )const hasPdfFile = Boolean(pdfFile)const controlsDisabled = !hasPdfFile || !reactPdf || !numPages+ const downloadDisabled = controlsDisabled || isPreparingDownloadconst isLoading =hasPdfFile && (!reactPdf || isDocumentLoading || isFirstPageRendering)const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)- const thumbnailIsRotated = Math.abs(Math.round(rotation / 90)) % 2 === 1- const thumbnailSize = {- width: THUMBNAIL_WIDTH,- height: Math.round(- THUMBNAIL_WIDTH *- (thumbnailIsRotated ? pageWidth / pageHeight : pageHeight / pageWidth)- ),- }- const thumbnailAspectRatio = thumbnailSize.width / thumbnailSize.height+ const thumbnailSidebarVisible = Boolean(+ sidebarOpen && !isLoading && !loadError+ )const updateActivePageFromViewport = React.useCallback(() => {const viewport = viewportRef.current@@ -676,12 +818,49 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>([])+ const scrollActiveThumbnailIntoView = React.useCallback(() => {+ const viewport = thumbnailViewportRef.current+ const thumbnail = viewport?.querySelector<HTMLElement>(+ `[data-pdf-viewer-thumbnail="${activePage}"]`+ )++ if (!viewport || !thumbnail) return++ const viewportRect = viewport.getBoundingClientRect()+ const thumbnailRect = thumbnail.getBoundingClientRect()+ const targetTop =+ thumbnailRect.top -+ viewportRect.top ++ viewport.scrollTop -+ (viewport.clientHeight - thumbnail.offsetHeight) / 2++ viewport.scrollTo({+ top: Math.max(0, targetTop),+ behavior: "auto",+ })+ }, [activePage])++ React.useEffect(() => {+ const wasThumbnailSidebarVisible = wasThumbnailSidebarVisibleRef.current+ wasThumbnailSidebarVisibleRef.current = thumbnailSidebarVisible++ if (!thumbnailSidebarVisible || wasThumbnailSidebarVisible) return++ const frameId = window.requestAnimationFrame(+ scrollActiveThumbnailIntoView+ )++ return () => window.cancelAnimationFrame(frameId)+ }, [scrollActiveThumbnailIntoView, thumbnailSidebarVisible])+const handleLoadStart = React.useCallback(() => {setIsDocumentLoading(true)setIsFirstPageRendering(true)setLoadError(false)setNumPages(0)setActivePage(1)+ setPageMetrics(new Map())+ setPageRotationDeltas(new Map())setSettledPageNumbers(new Set())onActivePageChange?.(1)setSearchQuery("")@@ -690,9 +869,10 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(}, [onActivePageChange])const handleLoadSuccess = React.useCallback(- ({ numPages: nextNumPages }: { numPages: number }) => {+ async (pdf: PDFDocumentProxy) => {+ const nextNumPages = pdf.numPages+setNumPages(nextNumPages)- setIsDocumentLoading(false)setIsFirstPageRendering(true)setSettledPageNumbers(new Set())setLoadError(false)@@ -702,6 +882,14 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(setSearchQuery("")setSearchDraft("")viewportRef.current?.scrollTo({ top: 0, left: 0 })++ try {+ setPageMetrics(await getDocumentPageMetrics(pdf))+ setIsDocumentLoading(false)+ } catch {+ setPageMetrics(new Map())+ setIsDocumentLoading(false)+ }},[onActivePageChange, onDocumentLoadSuccess])@@ -711,6 +899,8 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(setIsFirstPageRendering(false)setLoadError(true)setNumPages(0)+ setPageMetrics(new Map())+ setPageRotationDeltas(new Map())}, [])const handlePageSettled = React.useCallback(@@ -733,7 +923,51 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(React.useEffect(() => {setSettledPageNumbers(new Set())setIsFirstPageRendering(Boolean(pdfFile))- }, [pdfFile, renderedPageWidth, rotation])+ }, [pdfFile, pageMetrics])++ const rotateActivePage = React.useCallback(+ (rotationDelta: number) => {+ setPageRotationDeltas((currentRotations) => {+ const currentRotation = currentRotations.get(activePage) ?? 0+ const nextRotation = normalizeRotation(+ currentRotation + rotationDelta+ )+ const nextRotations = new Map(currentRotations)++ if (nextRotation) {+ nextRotations.set(activePage, nextRotation)+ } else {+ nextRotations.delete(activePage)+ }++ return nextRotations+ })+ },+ [activePage]+ )++ const handleDownload = React.useCallback(async () => {+ if (!pdfFile || isPreparingDownload) return++ setIsPreparingDownload(true)++ try {+ await downloadPdfWithPageRotations({+ file: pdfFile,+ fileName: resolvedDownloadFileName,+ pageRotationDeltas,+ })+ } catch (error) {+ console.error(error)+ } finally {+ setIsPreparingDownload(false)+ }+ }, [+ isPreparingDownload,+ pageRotationDeltas,+ pdfFile,+ resolvedDownloadFileName,+ ])const handleUpload = React.useCallback((file: File) => {@@ -781,14 +1015,14 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(<div className="flex min-w-0 items-center gap-1">{showRotateControls ? (<>- <ToolbarTooltip label="Rotate counterclockwise">+ <ToolbarTooltip label="Rotate page counterclockwise"><Buttontype="button"variant="ghost"size="icon-sm"- aria-label="Rotate counterclockwise"+ aria-label="Rotate page counterclockwise"disabled={controlsDisabled}- onClick={() => setRotation((value) => value - 90)}+ onClick={() => rotateActivePage(-90)}><HugeiconsIconicon={RotateClockwiseIcon}@@ -796,14 +1030,14 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(/></Button></ToolbarTooltip>- <ToolbarTooltip label="Rotate clockwise">+ <ToolbarTooltip label="Rotate page clockwise"><Buttontype="button"variant="ghost"size="icon-sm"- aria-label="Rotate clockwise"+ aria-label="Rotate page clockwise"disabled={controlsDisabled}- onClick={() => setRotation((value) => value + 90)}+ onClick={() => rotateActivePage(90)}><HugeiconsIconicon={RotateClockwiseIcon}@@ -880,6 +1114,33 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(orientation="vertical"className="mx-1 h-4 self-center"/>+ {showDownload ? (+ <>+ <ToolbarTooltip label="Download PDF">+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Download PDF"+ disabled={downloadDisabled}+ onClick={handleDownload}+ >+ {isPreparingDownload ? (+ <Spinner className="size-4" />+ ) : (+ <HugeiconsIcon+ icon={Download01Icon}+ className="size-4"+ />+ )}+ </Button>+ </ToolbarTooltip>+ <Separator+ orientation="vertical"+ className="mx-1 h-4 self-center"+ />+ </>+ ) : null}<Popover><ToolbarTooltip label="Search text"><PopoverTrigger asChild>@@ -999,36 +1260,60 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(<div className="flex h-full max-h-full min-h-0 w-full flex-1 overflow-hidden"><DocumentViewerThumbnailSidebarinline={sidebarInline}- open={Boolean(sidebarOpen && !isLoading && !loadError)}+ open={thumbnailSidebarVisible}>- <ScrollArea className="h-full" scrollFade>+ <ScrollArea+ className="h-full"+ scrollFade+ viewportRef={thumbnailViewportRef}+ ><div className="p-4"><div className="flex flex-col items-center gap-3">- {renderedPageNumbers.map((pageNumber) => (- <Button- key={pageNumber}- type="button"- variant="ghost"- size="sm"- className={cn(- "!h-auto w-full flex-col items-center gap-2 p-2 text-xs text-muted-foreground shadow-none hover:bg-sidebar-accent",- pageNumber === activePage && "bg-sidebar-accent"- )}- onFocus={(event) => event.currentTarget.blur()}- onMouseDown={preserveThumbnailClickScroll}- onPointerDown={preserveThumbnailClickScroll}- onClick={() => scrollToPage(pageNumber)}- >- <PDFSidebarThumbnail- file={pdfFile}- pageNumber={pageNumber}- reactPdf={reactPdf}- rotation={rotation}- thumbnailAspectRatio={thumbnailAspectRatio}- />- {pageNumber}- </Button>- ))}+ {renderedPageNumbers.map((pageNumber) => {+ const metrics = getPageMetrics(pageNumber)+ const rotationDelta =+ pageRotationDeltas.get(pageNumber) ?? 0+ const effectiveRotation = normalizeRotation(+ metrics.rotation + rotationDelta+ )+ const thumbnailDimensions = getPageDimensions(+ metrics,+ effectiveRotation+ )+ const thumbnailAspectRatio =+ thumbnailDimensions.width /+ thumbnailDimensions.height++ return (+ <Button+ key={pageNumber}+ data-pdf-viewer-thumbnail={pageNumber}+ type="button"+ variant="ghost"+ size="sm"+ className={cn(+ "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",+ pageNumber === activePage+ ? "bg-sidebar-accent text-foreground"+ : "text-muted-foreground"+ )}+ onFocus={(event) => event.currentTarget.blur()}+ onMouseDown={preserveThumbnailClickScroll}+ onPointerDown={preserveThumbnailClickScroll}+ onClick={() => scrollToPage(pageNumber)}+ >+ <PDFSidebarThumbnail+ file={pdfFile}+ pageMetrics={metrics}+ pageNumber={pageNumber}+ reactPdf={reactPdf}+ rotation={rotationDelta}+ thumbnailAspectRatio={thumbnailAspectRatio}+ />+ {pageNumber}+ </Button>+ )+ })}</div></div></ScrollArea>@@ -1042,13 +1327,23 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(><div className="flex min-h-full w-max min-w-full flex-col items-center justify-start gap-6 p-6">{renderedPageNumbers.map((pageNumber) => {+ const metrics = getPageMetrics(pageNumber)+ const rotationDelta =+ pageRotationDeltas.get(pageNumber) ?? 0+ const effectiveRotation = normalizeRotation(+ metrics.rotation + rotationDelta+ )+ const dimensions = getPageDimensions(+ metrics,+ effectiveRotation+ )const shouldRenderPage =Math.abs(pageNumber - activePage) <= pageRenderBuffer ||settledPageNumbers.has(pageNumber) ||renderedPageNumbers.length <= pageRenderBuffer * 2 + 1const pageStyle = {- width: renderedPageWidth,- height: renderedPageHeight,+ width: dimensions.width * zoom,+ height: dimensions.height * zoom,}const pageSearchQuery =searchQuery.trim() &&@@ -1059,12 +1354,12 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(return (<PDFViewerPagekey={pageNumber}+ effectiveRotation={effectiveRotation}reactPdf={reactPdf}pageNumber={pageNumber}pageStyle={pageStyle}- renderedPageWidth={renderedPageWidth}+ renderedPageWidth={pageStyle.width}zoom={zoom}- rotation={rotation}shouldRenderPage={shouldRenderPage}searchQuery={pageSearchQuery}pageClassName={pageClassName}diff --git a/apps/v4/lib/block-code-samples.ts b/apps/v4/lib/block-code-samples.tsnew file mode 100644index 0000000..3df3f74--- /dev/null+++ b/apps/v4/lib/block-code-samples.ts@@ -0,0 +1,178 @@+import { promises as fs } from "node:fs"+import path from "node:path"+import { fileURLToPath } from "node:url"++import { highlightCode } from "@/lib/highlight-code"++type RegistryFile = {+ path: string+ target?: string+}++type RegistryItem = {+ name: string+ registryDependencies?: string[]+ files?: RegistryFile[]+}++export type BlockCodeFile = {+ sourcePath: string+ targetPath: string+ language: string+}++export type LoadedBlockCodeFile = BlockCodeFile & {+ content: string+ highlightedContent: string | null+ lineCount: number+}++export const blockIds = [+ "human-review",+ "pdf-dropzone",+ "ocr-blocks",+ "e-signature",+ "document-splits",+ "excel-document-splits",+ "docx-editor-block",+]++const LARGE_CODE_HIGHLIGHT_LIMIT = 80_000++const blockCodeDependencies: Record<string, string[]> = {+ "pdf-dropzone": ["file-upload", "pdf-viewer", "file-thumbnail"],+ "ocr-blocks": ["pdf-block-resizable-shell", "pdf-viewer", "file-thumbnail"],+ "e-signature": ["pdf-block-resizable-shell", "pdf-viewer", "file-thumbnail"],+ "human-review": ["pdf-block-resizable-shell", "pdf-viewer", "file-thumbnail"],+ "document-splits": [+ "file-thumbnail",+ "pdf-block-resizable-shell",+ "pdf-viewer",+ ],+ "excel-document-splits": [+ "file-thumbnail",+ "pdf-block-resizable-shell",+ "xlsx-viewer",+ ],+ "docx-editor-block": ["docx-editor", "file-thumbnail"],+}++const appRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "../"+)++export async function getBlockCodeFileManifest(): Promise<+ Record<string, BlockCodeFile[]>+> {+ const itemsByName = await getRegistryItemsByName()++ return Object.fromEntries(+ blockIds.map((id) => {+ const files = collectRegistryFiles(id, itemsByName).map((file) => ({+ sourcePath: file.path,+ targetPath: normalizeRegistryTarget(file),+ language: getCodeLanguage(file.path),+ }))++ return [id, files] satisfies [string, BlockCodeFile[]]+ })+ )+}++export async function getLoadedBlockCodeFile({+ blockId,+ targetPath,+}: {+ blockId: string+ targetPath: string+}): Promise<LoadedBlockCodeFile | null> {+ const itemsByName = await getRegistryItemsByName()+ const file = collectRegistryFiles(blockId, itemsByName).find(+ (candidate) => normalizeRegistryTarget(candidate) === targetPath+ )++ if (!file) return null++ const language = getCodeLanguage(file.path)+ const content = await fs.readFile(path.join(appRoot, file.path), "utf8")+ const highlightedContent =+ content.length <= LARGE_CODE_HIGHLIGHT_LIMIT+ ? await highlightCode(content, language)+ : null++ return {+ sourcePath: file.path,+ targetPath,+ language,+ content,+ highlightedContent,+ lineCount: content.split("\n").length,+ }+}++async function getRegistryItemsByName() {+ const registryPath = path.join(appRoot, "registry.json")+ const registry = JSON.parse(await fs.readFile(registryPath, "utf8")) as {+ items: RegistryItem[]+ }++ return new Map(registry.items.map((item) => [item.name, item] as const))+}++function getCodeLanguage(filePath: string) {+ const extension = filePath.split(".").pop()++ if (extension === "ts" || extension === "tsx") return "tsx"+ if (extension === "js" || extension === "jsx") return "jsx"+ if (extension === "css") return "css"+ if (extension === "json") return "json"+ if (extension === "md" || extension === "mdx") return "mdx"++ return "tsx"+}++function collectRegistryFiles(+ name: string,+ itemsByName: Map<string, RegistryItem>+): RegistryFile[] {+ const sampleItems = [name, ...(blockCodeDependencies[name] ?? [])].flatMap(+ (itemName) => itemsByName.get(itemName)?.files ?? []+ )++ return dedupeFiles(sampleItems)+}++function dedupeFiles(files: RegistryFile[]) {+ const seen = new Set<string>()++ return files.filter((file) => {+ const key = file.target ?? file.path+ if (seen.has(key)) return false++ seen.add(key)+ return true+ })+}++function normalizeRegistryTarget(file: RegistryFile) {+ const target = file.target ?? file.path++ if (target.startsWith("@components/")) {+ return target.replace("@components/", "components/")+ }++ if (target.startsWith("@ui/")) {+ return target.replace("@ui/", "components/ui/")+ }++ if (target.startsWith("@hooks/")) {+ return target.replace("@hooks/", "hooks/")+ }++ if (target.startsWith("@lib/")) {+ return target.replace("@lib/", "lib/")+ }++ return target+}diff --git a/apps/v4/package.json b/apps/v4/package.jsonindex 97f2460..ef80e4d 100644--- a/apps/v4/package.json+++ b/apps/v4/package.json@@ -31,6 +31,7 @@"@pierre/diffs": "^1.1.22","@pierre/trees": "1.0.0-beta.4","@tabler/icons-react": "^3.31.0",+ "@tanstack/react-virtual": "3.13.26","border-beam": "^1.0.1","class-variance-authority": "^0.7.1","clsx": "^2.1.1",@@ -54,6 +55,9 @@"react-resizable-panels": "^3.0.5","react-responsive-carousel": "^3.2.23","rehype-pretty-code": "^0.14.1",+ "rehype-raw": "^7.0.0",+ "rehype-sanitize": "^6.0.0",+ "remark-gfm": "4.0.1","shadcn": "^4.8.2","shiki": "^1.10.1","signature_pad": "^5.1.3",diff --git a/apps/v4/public/samples/attention-rotated.pdf b/apps/v4/public/samples/attention-rotated.pdfnew file mode 100644index 0000000..3cec1f2Binary files /dev/null and b/apps/v4/public/samples/attention-rotated.pdf differdiff --git a/apps/v4/public/samples/bank-statement-x4uhhi7t.pdf b/apps/v4/public/samples/bank-statement-x4uhhi7t.pdfnew file mode 100644index 0000000..5d5e860Binary files /dev/null and b/apps/v4/public/samples/bank-statement-x4uhhi7t.pdf differdiff --git a/apps/v4/public/samples/loan-application.pdf b/apps/v4/public/samples/loan-application.pdfnew file mode 100644index 0000000..bc89a01Binary files /dev/null and b/apps/v4/public/samples/loan-application.pdf differdiff --git a/apps/v4/registry/new-york-v4/blocks/document-splits.tsx b/apps/v4/registry/new-york-v4/blocks/document-splits.tsxindex 9dbdf2b..ba95cea 100644--- a/apps/v4/registry/new-york-v4/blocks/document-splits.tsx+++ b/apps/v4/registry/new-york-v4/blocks/document-splits.tsx@@ -143,27 +143,27 @@ function getGroupPages(groups: SplitGroup[], groupId: string | null) {}function movePageToGroup({- activePageId,+ draggedPageId,groups,insertIndex,targetGroupId,}: {- activePageId: PageId+ draggedPageId: PageIdgroups: SplitGroup[]insertIndex: numbertargetGroupId: string}) {return groups.map((group) => {- const pagesWithoutActive = group.pages.filter(- (pageId) => pageId !== activePageId+ const pagesWithoutDragged = group.pages.filter(+ (pageId) => pageId !== draggedPageId)if (group.id !== targetGroupId) {- return { ...group, pages: pagesWithoutActive }+ return { ...group, pages: pagesWithoutDragged }}- const nextPages = [...pagesWithoutActive]- nextPages.splice(insertIndex, 0, activePageId)+ const nextPages = [...pagesWithoutDragged]+ nextPages.splice(insertIndex, 0, draggedPageId)return { ...group, pages: nextPages }})@@ -189,26 +189,26 @@ function areSplitGroupsEqual(left: SplitGroup[], right: SplitGroup[]) {}function reorderPageInGroup({- activePageId,+ draggedPageId,groups,overPageId,}: {- activePageId: PageId+ draggedPageId: PageIdgroups: SplitGroup[]overPageId: PageId}) {- const groupId = findGroupId(groups, activePageId)+ const groupId = findGroupId(groups, draggedPageId)const pages = getGroupPages(groups, groupId)- const activeIndex = pages.indexOf(activePageId)+ const draggedIndex = pages.indexOf(draggedPageId)const overIndex = pages.indexOf(overPageId)- if (!groupId || activeIndex === -1 || overIndex === -1) return groups+ if (!groupId || draggedIndex === -1 || overIndex === -1) return groupsreturn groups.map((group) =>group.id === groupId? {...group,- pages: arrayMove(group.pages, activeIndex, overIndex),+ pages: arrayMove(group.pages, draggedIndex, overIndex),}: group)@@ -247,12 +247,10 @@ function SplitGroupDropzone({function PageThumbnail({imageUrl,- isActive,onSelect,pageId,}: {imageUrl?: string- isActive: booleanonSelect: (pageNumber: number) => voidpageId: PageId}) {@@ -274,10 +272,7 @@ function PageThumbnail({ref={setNodeRef}type="button"className={cn(- "relative shrink-0 cursor-grab overflow-hidden rounded-md border bg-muted text-left shadow-xs transition-[border-color,box-shadow,opacity] active:cursor-grabbing",- isActive- ? "border-blue-500 shadow-[0_0_0_2px_rgb(59_130_246_/_14%)]"- : "border-border hover:border-foreground/30",+ "relative shrink-0 cursor-grab overflow-hidden rounded-md border border-border bg-muted text-left shadow-xs transition-[border-color,opacity] hover:border-foreground/30 active:cursor-grabbing",isDragging && "opacity-0")}style={{@@ -302,7 +297,9 @@ function PageThumbnail({previewClassName="h-full aspect-auto"className="size-full rounded-[inherit] border-0"/>- <span className="absolute right-1 bottom-1 rounded bg-background/90 px-1.5 py-0.5 text-[10px] font-medium shadow-xs">+ <span+ className="absolute right-1 bottom-1 rounded bg-background/95 px-1.5 py-0.5 text-[10px] font-semibold text-foreground shadow-xs ring-1 ring-border/80"+ >{pageNumber}</span></button>@@ -310,7 +307,6 @@ function PageThumbnail({}function SplitGroupCard({- activePage,canRemove,group,dragHandleProps,@@ -318,7 +314,6 @@ function SplitGroupCard({onRemove,onSelectPage,}: {- activePage: numbercanRemove: booleangroup: SplitGroupdragHandleProps?: React.ComponentPropsWithoutRef<"button">@@ -380,7 +375,6 @@ function SplitGroupCard({key={pageId}pageId={pageId}imageUrl={thumbnailImages[pageId]}- isActive={activePage === getPageNumber(pageId)}onSelect={onSelectPage}/>))}@@ -398,14 +392,12 @@ function SplitGroupCard({}function SortableSplitGroupCard({- activePage,canRemove,group,thumbnailImages,onRemove,onSelectPage,}: {- activePage: numbercanRemove: booleangroup: SplitGroupthumbnailImages: Record<PageId, string>@@ -434,7 +426,6 @@ function SortableSplitGroupCard({}}><SplitGroupCard- activePage={activePage}canRemove={canRemove}group={group}thumbnailImages={thumbnailImages}@@ -447,13 +438,11 @@ function SortableSplitGroupCard({}function SplitGroupDragOverlay({- activePage,group,thumbnailImages,width,onSelectPage,}: {- activePage: numbergroup: SplitGroupthumbnailImages: Record<PageId, string>width?: number@@ -465,7 +454,6 @@ function SplitGroupDragOverlay({style={{ width }}><SplitGroupCard- activePage={activePage}canRemove={false}group={group}thumbnailImages={thumbnailImages}@@ -477,7 +465,6 @@ function SplitGroupDragOverlay({}export function DocumentSplits({- activePage,className,splits,thumbnailImages = {},@@ -485,7 +472,6 @@ export function DocumentSplits({onSelectPage,onSplitsChange,}: {- activePage: numberclassName?: stringsplits: SplitGroup[]thumbnailImages?: Record<PageId, string>@@ -493,7 +479,7 @@ export function DocumentSplits({onSelectPage: (pageNumber: number) => voidonSplitsChange: (splits: SplitGroup[]) => void}) {- const [activePageId, setActivePageId] = React.useState<PageId | null>(null)+ const [draggedPageId, setDraggedPageId] = React.useState<PageId | null>(null)const [activeSplitGroupId, setActiveSplitGroupId] = React.useState<string | null>(null)@@ -513,7 +499,7 @@ export function DocumentSplits({if (dragType === "split") {dragStartGroupIdRef.current = nulldragStartSplitsRef.current = null- setActivePageId(null)+ setDraggedPageId(null)setActiveSplitGroupId((event.active.data.current?.groupId as string | undefined) ?? null)@@ -524,7 +510,7 @@ export function DocumentSplits({if (dragType !== "page") {dragStartGroupIdRef.current = nulldragStartSplitsRef.current = null- setActivePageId(null)+ setDraggedPageId(null)setActiveSplitGroupId(null)setActiveSplitGroupWidth(undefined)return@@ -533,7 +519,7 @@ export function DocumentSplits({const pageId = String(event.active.id) as PageIddragStartGroupIdRef.current = findGroupId(splits, pageId)dragStartSplitsRef.current = splits- setActivePageId(pageId)+ setDraggedPageId(pageId)setActiveSplitGroupId(null)setActiveSplitGroupWidth(undefined)},@@ -559,7 +545,7 @@ export function DocumentSplits({const insertIndex = overIndex === -1 ? targetPages.length : overIndexconst nextSplits = movePageToGroup({- activePageId: pageId,+ draggedPageId: pageId,groups: splits,insertIndex,targetGroupId,@@ -578,13 +564,13 @@ export function DocumentSplits({const activeGroupId = event.active.data.current.groupIdconst overGroupId = event.over.data.current?.groupId- const activeIndex = splits.findIndex(+ const draggedIndex = splits.findIndex((group) => group.id === activeGroupId)const overIndex = splits.findIndex((group) => group.id === overGroupId)- if (activeIndex !== -1 && overIndex !== -1) {- const nextSplits = arrayMove(splits, activeIndex, overIndex)+ if (draggedIndex !== -1 && overIndex !== -1) {+ const nextSplits = arrayMove(splits, draggedIndex, overIndex)if (!areSplitGroupsEqual(splits, nextSplits)) {onSplitsChange(nextSplits)@@ -593,7 +579,7 @@ export function DocumentSplits({dragStartGroupIdRef.current = nulldragStartSplitsRef.current = null- setActivePageId(null)+ setDraggedPageId(null)setActiveSplitGroupId(null)setActiveSplitGroupWidth(undefined)return@@ -602,7 +588,7 @@ export function DocumentSplits({if (event.active.data.current?.type !== "page" || !event.over) {dragStartGroupIdRef.current = nulldragStartSplitsRef.current = null- setActivePageId(null)+ setDraggedPageId(null)setActiveSplitGroupId(null)setActiveSplitGroupWidth(undefined)return@@ -614,7 +600,7 @@ export function DocumentSplits({if (dragStartGroupIdRef.current === overGroupId) {const nextSplits = reorderPageInGroup({- activePageId: pageId,+ draggedPageId: pageId,groups: splits,overPageId: overId,})@@ -626,7 +612,7 @@ export function DocumentSplits({dragStartGroupIdRef.current = nulldragStartSplitsRef.current = null- setActivePageId(null)+ setDraggedPageId(null)setActiveSplitGroupId(null)setActiveSplitGroupWidth(undefined)},@@ -640,7 +626,7 @@ export function DocumentSplits({dragStartSplitsRef.current = nulldragStartGroupIdRef.current = null- setActivePageId(null)+ setDraggedPageId(null)setActiveSplitGroupId(null)setActiveSplitGroupWidth(undefined)}, [onSplitsChange])@@ -695,9 +681,6 @@ export function DocumentSplits({{splits.map((group) => (<SortableSplitGroupCardkey={group.id}- activePage={- activePageId ? getPageNumber(activePageId) : activePage- }canRemove={splits.length > 1}group={group}thumbnailImages={thumbnailImages}@@ -714,23 +697,22 @@ export function DocumentSplits({</SortableContext></ScrollArea><DragOverlay dropAnimation={DRAG_OVERLAY_DROP_ANIMATION} zIndex={1000}>- {activePageId ? (+ {draggedPageId ? (<divclassName="relative overflow-hidden rounded-md border bg-background shadow-lg shadow-black/10"style={{ width: THUMBNAIL_WIDTH, height: THUMBNAIL_HEIGHT }}><FileThumbnail- file={{ name: `${activePageId}.pdf`, type: "application/pdf" }}+ file={{ name: `${draggedPageId}.pdf`, type: "application/pdf" }}showMetadata={false}- previewImageUrl={thumbnailImages[activePageId]}- isLoading={!thumbnailImages[activePageId]}+ previewImageUrl={thumbnailImages[draggedPageId]}+ isLoading={!thumbnailImages[draggedPageId]}previewClassName="h-full aspect-auto"className="size-full rounded-[inherit] border-0"/></div>) : activeSplitGroup ? (<SplitGroupDragOverlay- activePage={activePage}group={activeSplitGroup}thumbnailImages={thumbnailImages}width={activeSplitGroupWidth}@@ -750,7 +732,6 @@ export function DocumentSplitsBlock({file?: stringthumbnailImages?: Record<PageId, string>}) {- const [activePage, setActivePage] = React.useState(1)const [splits, setSplits] = React.useState<DocumentSplit[]>(INITIAL_SPLITS)const [pdfFile, setPdfFile] = React.useState(file)const viewerRef = React.useRef<PDFViewerHandle>(null)@@ -758,7 +739,6 @@ export function DocumentSplitsBlock({React.useEffect(() => {setPdfFile(file)- setActivePage(1)}, [file])React.useEffect(() => {@@ -778,7 +758,6 @@ export function DocumentSplitsBlock({uploadedPdfUrlRef.current = nextUrlsetPdfFile(nextUrl)- setActivePage(1)}, [])const handleDocumentLoadSuccess = React.useCallback((pageCount: number) => {@@ -786,7 +765,6 @@ export function DocumentSplitsBlock({}, [])const handleSelectPage = React.useCallback((pageNumber: number) => {- setActivePage(pageNumber)viewerRef.current?.scrollToPage(pageNumber, {block: "start",behavior: "auto",@@ -805,7 +783,6 @@ export function DocumentSplitsBlock({ref={viewerRef}file={pdfFile}defaultZoom={0.75}- onActivePageChange={setActivePage}onDocumentLoadSuccess={handleDocumentLoadSuccess}onPdfUpload={handlePdfUpload}/>@@ -819,7 +796,6 @@ export function DocumentSplitsBlock({</p></div><DocumentSplits- activePage={activePage}className="min-h-0 flex-1"splits={splits}thumbnailImages={thumbnailImages}diff --git a/apps/v4/registry/new-york-v4/blocks/e-signature.tsx b/apps/v4/registry/new-york-v4/blocks/e-signature.tsxindex 911dbbc..37832ab 100644--- a/apps/v4/registry/new-york-v4/blocks/e-signature.tsx+++ b/apps/v4/registry/new-york-v4/blocks/e-signature.tsx@@ -43,6 +43,8 @@ const PAGE_WIDTH = 612const PAGE_HEIGHT = 792const DEFAULT_ZOOM = 0.75const SIGNATURE_PAD_PADDING = 8+const SIGNATURE_PAD_BACKGROUND_COLOR = "#ffffff"+const SIGNATURE_PAD_PEN_COLOR = "#000000"const DEFAULT_SIGNATURE_ASPECT_RATIO = 3const INITIAL_FIELD: SignatureField = {@@ -282,7 +284,7 @@ function SignatureDialog({const signaturePad = new SignaturePadConstructor(canvas, {minWidth: 1.4,maxWidth: 2.8,- penColor: "rgb(15, 23, 42)",+ penColor: SIGNATURE_PAD_PEN_COLOR,})signaturePadRef.current = signaturePad@@ -352,13 +354,14 @@ function SignatureDialog({><divclassName={cn(- "relative overflow-hidden rounded-md border border-dashed border-input bg-background shadow-xs",+ "relative overflow-hidden rounded-md border border-dashed border-input bg-white shadow-xs",isReady ? "cursor-crosshair" : "cursor-wait")}style={{width: guideSize ? `${guideSize.width}px` : undefined,height: guideSize ? `${guideSize.height}px` : undefined,opacity: guideSize ? 1 : 0,+ backgroundColor: SIGNATURE_PAD_BACKGROUND_COLOR,}}><canvas@@ -367,7 +370,10 @@ function SignatureDialog({"absolute inset-0 size-full touch-none",!isReady && "pointer-events-none")}- style={{ touchAction: "none" }}+ style={{+ backgroundColor: SIGNATURE_PAD_BACKGROUND_COLOR,+ touchAction: "none",+ }}/></div></div>diff --git a/apps/v4/registry/new-york-v4/blocks/human-review.tsx b/apps/v4/registry/new-york-v4/blocks/human-review.tsxindex 7d58646..1723c88 100644--- a/apps/v4/registry/new-york-v4/blocks/human-review.tsx+++ b/apps/v4/registry/new-york-v4/blocks/human-review.tsx@@ -5,9 +5,11 @@ import {DataEditor,emptyGridSelection,GridCellKind,+ TextCellEntry,type EditableGridCell,type GridCell,type GridColumn,+ type GridMouseEventArgs,type GridSelection,type Item,type NumberCell,@@ -85,10 +87,24 @@ export type ReviewField = {schema: ReviewFieldSchemaactual: JsonValueexpected: JsonValue- location?: {- page: number- area: HighlightArea- }+ location?: ReviewLocation+ metadataPath?: string+}++export type ReviewLocation = {+ page: number+ area: HighlightArea+}++export type ReviewCitation = {+ page: number+ polygon?: Array<{ x: number; y: number }>+ pageWidth: number+ pageHeight: number+}++export type ReviewMetadataEntry = {+ citations?: ReviewCitation[]}const DEFAULT_ZOOM = 0.75@@ -218,110 +234,73 @@ function useHumanReviewGridTheme() {const REVIEW_FIELDS: ReviewField[] = [{- key: "vendor_name",+ key: "statement_period",schema: {type: "string",- title: "Vendor name",- description: "Supplier shown on the invoice header.",+ title: "Statement period",+ description: "Date range covered by the bank statement.",},- actual: "Acme Supplies LLC",- expected: "Acme Supply LLC",+ actual: "Jan 1-31, 2026",+ expected: "January 1-31, 2026",location: {page: 1,area: { left: 31, top: 30, width: 40, height: 5.8 },},},{- key: "line_items",+ key: "transactions",schema: {type: "array",- title: "Line items",- description: "Invoice rows with nested allocation details.",+ title: "Transactions",+ description: "Posted account activity during the statement period.",items: {type: "object",properties: {+ date: {+ type: "string",+ title: "Date",+ },description: {type: "string",title: "Description",},- quantity: {+ amount: {type: "number",- title: "Qty",- },- unit_price: {- type: "number",- title: "Unit price",- },- tax_detail: {- type: "object",- title: "Tax detail",- properties: {- code: {- type: "string",- title: "Code",- },- jurisdiction: {- type: "string",- title: "Jurisdiction",- },- },+ title: "Amount",},- allocations: {- type: "array",- title: "Allocations",- items: {- type: "object",- properties: {- department: {- type: "string",- title: "Department",- },- percent: {- type: "number",- title: "Percent",- },- },- },+ category: {+ type: "string",+ title: "Category",},},},},actual: [{- description: "Transformer implementation support",- quantity: 2,- unit_price: 4200,- tax_detail: { code: "TX-CA", jurisdiction: "CA" },- allocations: [- { department: "Research", percent: 70 },- { department: "Platform", percent: 20 },- ],+ date: "2026-01-03",+ description: "ACH CREDIT PAYROLL",+ amount: 4250,+ category: "Deposit",},{- description: "Attention model review",- quantity: 1,- unit_price: 4080,- tax_detail: { code: "TX-NY", jurisdiction: "NY" },- allocations: [{ department: "Research", percent: 100 }],+ date: "2026-01-12",+ description: "POS PURCHASE GROCERY MART",+ amount: -86.42,+ category: "Debit",},],expected: [{- description: "Transformer implementation support",- quantity: 2,- unit_price: 4200,- tax_detail: { code: "TX-CA", jurisdiction: "CA" },- allocations: [- { department: "Research", percent: 70 },- { department: "Platform", percent: 30 },- ],+ date: "2026-01-03",+ description: "ACH CREDIT PAYROLL",+ amount: 4250,+ category: "Deposit",},{- description: "Attention model review",- quantity: 1,- unit_price: 4080.75,- tax_detail: { code: "TX-NY", jurisdiction: "NY" },- allocations: [{ department: "Research", percent: 100 }],+ date: "2026-01-12",+ description: "POS PURCHASE GROCERY MART",+ amount: -68.42,+ category: "Debit",},],location: {@@ -330,39 +309,25 @@ const REVIEW_FIELDS: ReviewField[] = [},},{- key: "total_amount",+ key: "ending_balance",schema: {type: "number",- title: "Total amount",- description: "Final amount due including tax.",+ title: "Ending balance",+ description: "Final account balance at the end of the statement period.",},- actual: 12480,- expected: 12480.75,+ actual: 12840.18,+ expected: 12858.18,location: {page: 1,area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },},},{- key: "payment_terms",- schema: {- type: "string",- title: "Payment terms",- enum: ["Due on receipt", "Net 15", "Net 30"],- },- actual: "Net 15",- expected: "Net 30",- location: {- page: 1,- area: { left: 13.5, top: 55.5, width: 73.5, height: 7.5 },- },- },- {- key: "requires_review",+ key: "overdraft_protection_enabled",schema: {type: "boolean",- title: "Requires review",- description: "Whether a human should verify this document before export.",+ title: "Overdraft protection enabled",+ description: "Whether overdraft protection is enabled for the account.",},actual: false,expected: true,@@ -372,39 +337,98 @@ const REVIEW_FIELDS: ReviewField[] = [},},{- key: "remittance",+ key: "account_details",schema: {type: "object",- title: "Remittance details",- description: "Payment destination used for invoice reconciliation.",+ title: "Account details",+ description: "Account owner and identifying details from the statement.",properties: {- account_holder: {+ holder_name: {type: "string",- title: "Account holder",+ title: "Holder name",},- routing_number: {+ account_last_four: {type: "string",- title: "Routing number",+ title: "Account last four",},- verified: {- type: "boolean",- title: "Verified",+ account_type: {+ type: "string",+ title: "Account type",},},},actual: {- account_holder: "Acme Supplies LLC",- routing_number: "021000021",- verified: false,+ holder_name: "Jordan Lee",+ account_last_four: "4821",+ account_type: "Checking",},expected: {- account_holder: "Acme Supply LLC",- routing_number: "021000021",- verified: true,+ holder_name: "Jordan Lee",+ account_last_four: "4821",+ account_type: "Premier Checking",},},]+function getCitationLocation(+ citation: ReviewCitation+): ReviewLocation | undefined {+ const polygon = citation.polygon+ if (!polygon?.length || !citation.pageWidth || !citation.pageHeight) {+ return undefined+ }++ const xs = polygon.map((point) => point.x)+ const ys = polygon.map((point) => point.y)+ const left = Math.min(...xs)+ const top = Math.min(...ys)+ const right = Math.max(...xs)+ const bottom = Math.max(...ys)++ return {+ page: citation.page,+ area: {+ left: (left / citation.pageWidth) * 100,+ top: (top / citation.pageHeight) * 100,+ width: ((right - left) / citation.pageWidth) * 100,+ height: ((bottom - top) / citation.pageHeight) * 100,+ },+ }+}++function getMetadataLocation(+ metadata: Record<string, ReviewMetadataEntry> | undefined,+ metadataPath: string | undefined+) {+ if (!metadata || !metadataPath) return undefined++ const citation = metadata[metadataPath]?.citations?.find(+ (candidate) => candidate.polygon?.length+ )++ return citation ? getCitationLocation(citation) : undefined+}++function getReviewFieldLocation(+ field: ReviewField | undefined,+ resolveLocation?: (metadataPath: string) => ReviewLocation | undefined+) {+ if (!field) return undefined++ return (+ field.location ??+ resolveLocation?.(field.metadataPath ?? field.key) ??+ undefined+ )+}++function getReviewLocationKey(location: ReviewLocation | undefined) {+ if (!location) return null++ const { area } = location+ return [location.page, area.left, area.top, area.width, area.height].join(":")+}+function valuesFromFields(fields: ReviewField[],valueKey: "actual" | "expected"@@ -476,6 +500,7 @@ function countReviewFields(fields: ReviewField[]): number {schema,actual: getObjectValue(field.actual, key),expected: getObjectValue(field.expected, key),+ metadataPath: `${field.metadataPath ?? field.key}.${key}`,}))@@ -499,6 +524,7 @@ function findReviewField(schema,actual: getObjectValue(field.actual, key),expected: getObjectValue(field.expected, key),+ metadataPath: `${field.metadataPath ?? field.key}.${key}`,}))const childField = findReviewField(childFields, fieldKey)@@ -602,9 +628,9 @@ function HumanReviewTextOverlayEditor({validatedSelection,value,}: HumanReviewTextOverlayEditorProps) {- const inputRef = React.useRef<HTMLTextAreaElement | null>(null)const initialValue =value.kind === GridCellKind.Number ? value.displayData : value.data+ const [entryValue, setEntryValue] = React.useState(initialValue)const latestValueRef = React.useRef(initialValue)const finishedRef = React.useRef(false)@@ -649,24 +675,16 @@ function HumanReviewTextOverlayEditor({[onFinishedEditing, overlayOpenRef, readOnly, value])- React.useEffect(() => {- overlayOpenRef.current = true-- const input = inputRef.current- if (!input) {- return () => {- overlayOpenRef.current = false- }- }-- const handleInput = (event: Event) => {- event.stopPropagation()- latestValueRef.current = input.value- }- const stopTextInputPropagation = (event: Event) => {+ const handleEntryChange = React.useCallback(+ (event: React.ChangeEvent<HTMLTextAreaElement>) => {event.stopPropagation()- }- const handleKeyDown = (event: KeyboardEvent) => {+ latestValueRef.current = event.target.value+ setEntryValue(event.target.value)+ },+ []+ )+ const handleKeyDown = React.useCallback(+ (event: React.KeyboardEvent<HTMLTextAreaElement>) => {event.stopPropagation()if (event.key === "Escape") {@@ -685,43 +703,21 @@ function HumanReviewTextOverlayEditor({event.preventDefault()finishEditing(true, [0, 1])}- }+ },+ [finishEditing]+ )- input.addEventListener("input", handleInput)- input.addEventListener("beforeinput", stopTextInputPropagation, true)- input.addEventListener("keydown", handleKeyDown, true)-- input.focus()-- if (validatedSelection !== undefined) {- const selectionRange =- typeof validatedSelection === "number"- ? [validatedSelection, validatedSelection]- : validatedSelection- input.setSelectionRange(selectionRange[0], selectionRange[1])- } else if (isHighlighted) {- input.setSelectionRange(0, input.value.length)- } else {- input.setSelectionRange(input.value.length, input.value.length)- }+ React.useEffect(() => {+ overlayOpenRef.current = truereturn () => {- input.removeEventListener("input", handleInput)- input.removeEventListener("beforeinput", stopTextInputPropagation, true)- input.removeEventListener("keydown", handleKeyDown, true)overlayOpenRef.current = false}- }, [- finishEditing,- isHighlighted,- overlayOpenRef,- validatedSelection,- readOnly,- ])+ }, [overlayOpenRef])React.useEffect(() => {const handlePointerOutside = (event: PointerEvent | MouseEvent) => {- const input = inputRef.current+ const input = document.querySelector<HTMLTextAreaElement>(".gdg-input")const overlayRoot = input?.closest(".gdg-clip-region")if (!overlayRoot || overlayRoot.contains(event.target as Node | null)) {@@ -741,14 +737,15 @@ function HumanReviewTextOverlayEditor({}, [finishEditing])return (- <textarea- ref={inputRef}- className="gdg-input"- defaultValue={initialValue}- readOnly={readOnly}- aria-readonly={readOnly}- dir="auto"- style={{ height: "100%", minHeight: 32, resize: "none", width: "100%" }}+ <TextCellEntry+ autoFocus={!readOnly}+ disabled={readOnly}+ highlight={isHighlighted}+ value={entryValue}+ validatedSelection={validatedSelection}+ altNewline+ onChange={handleEntryChange}+ onKeyDown={handleKeyDown}/>)}@@ -1024,9 +1021,13 @@ function HumanReviewArrayValueGrid({sharedNestedStack,value,viewSide = "expected",+ metadataPath,onChange,onGridSelectionChange,+ onLocationHover,onNestedStackChange,+ resolveArrayItemMetadataPath,+ resolveLocation,}: {activeNestedSide?: ArrayReviewSide | nullactiveSelectionSide?: ArrayReviewSide | null@@ -1039,6 +1040,7 @@ function HumanReviewArrayValueGrid({sharedNestedStack?: ArrayNestedView[]value: JsonValueviewSide?: ArrayReviewSide+ metadataPath?: stringonChange?: (value: JsonValue) => voidonGridSelectionChange?: (selection: GridSelection,@@ -1049,6 +1051,13 @@ function HumanReviewArrayValueGrid({stack: ArrayNestedView[],side: ArrayReviewSide) => void+ onLocationHover?: (location?: ReviewLocation) => void+ resolveArrayItemMetadataPath?: (+ metadataPath: string,+ rowIndex: number,+ rowValue: JsonValue+ ) => string | undefined+ resolveLocation?: (metadataPath: string) => ReviewLocation | undefined}) {const rows = getArrayValue(value)const itemSchema = getArrayItemSchema(schema)@@ -1215,7 +1224,7 @@ function HumanReviewArrayValueGrid({allowOverlay: false,readonly: true,cursor: "pointer",- activationBehaviorOverride: "second-click",+ activationBehaviorOverride: "double-click",themeOverride: {textDark: blueCellText,...(nestedCellTheme ?? {}),@@ -1239,7 +1248,6 @@ function HumanReviewArrayValueGrid({displayData: typeof cellValue === "number" ? String(cellValue) : "",allowOverlay: true,readonly: false,- activationBehaviorOverride: readOnly ? "single-click" : undefined,}}@@ -1259,7 +1267,6 @@ function HumanReviewArrayValueGrid({: String(cellValue),allowOverlay: true,readonly: false,- activationBehaviorOverride: readOnly ? "single-click" : undefined,}},[@@ -1334,6 +1341,52 @@ function HumanReviewArrayValueGrid({() => !fastTextOverlayOpenRef.current,[])+ const handleItemHovered = React.useCallback(+ (args: GridMouseEventArgs) => {+ if (!onLocationHover || !resolveLocation || !metadataPath) return++ if (args.kind !== "cell") {+ onLocationHover(undefined)+ return+ }++ const [col, row] = args.location+ const column = columns[col]+ const rowValue = rows[row]+ if (!column || rowValue === undefined) {+ onLocationHover(undefined)+ return+ }++ const columnId = String(column.id ?? "value")+ const rowMetadataPath = resolveArrayItemMetadataPath+ ? resolveArrayItemMetadataPath(metadataPath, row, rowValue)+ : `${metadataPath}[${row}]`+ if (!rowMetadataPath) {+ onLocationHover(undefined)+ return+ }++ const propertyMetadataPath =+ itemSchema.type === "object"+ ? `${rowMetadataPath}.${columnId}`+ : rowMetadataPath++ onLocationHover(+ resolveLocation(propertyMetadataPath) ??+ resolveLocation(rowMetadataPath)+ )+ },+ [+ columns,+ itemSchema.type,+ metadataPath,+ onLocationHover,+ resolveArrayItemMetadataPath,+ resolveLocation,+ rows,+ ]+ )const openNestedCell = React.useCallback(([col, row]: Item) => {@@ -1401,6 +1454,7 @@ function HumanReviewArrayValueGrid({return (<div+ onMouseLeave={() => onLocationHover?.(undefined)}className={cn("relative overflow-hidden rounded-md border bg-background transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:shadow-[0_0_0_1px_rgb(59_130_246_/_8%)] hover:border-blue-500/50",isActiveNestedSource &&@@ -1417,12 +1471,13 @@ function HumanReviewArrayValueGrid({columns={columns}rows={rows.length}getCellContent={getCellContent}- cellActivationBehavior={readOnly ? "single-click" : "second-click"}+ cellActivationBehavior="double-click"gridSelection={localGridSelection}highlightRegions={mirroredHighlightRegions}onCellEdited={updateCellValue}onCellActivated={openNestedCell}onGridSelectionChange={handleGridSelectionChange}+ onItemHovered={handleItemHovered}provideEditor={provideEditor}isOutsideClick={handleOutsideClick}rowMarkers="number"@@ -1479,6 +1534,8 @@ function HumanReviewArrayValueGrid({onChange={updateNestedValue}onGridSelectionChange={onGridSelectionChange}onNestedStackChange={onNestedStackChange}+ resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}+ resolveLocation={resolveLocation}/>) : (<HumanReviewObjectValueEditor@@ -1565,8 +1622,15 @@ type HumanReviewFieldCardProps = {readOnly?: booleanonChange: (value: JsonValue) => voidonFieldFocus?: (field: ReviewField) => void+ onLocationHover?: (location?: ReviewLocation) => voidonUndo: () => voidonSetNull: () => void+ resolveArrayItemMetadataPath?: (+ metadataPath: string,+ rowIndex: number,+ rowValue: JsonValue+ ) => string | undefined+ resolveLocation?: (metadataPath: string) => ReviewLocation | undefined}function areHumanReviewFieldCardPropsEqual(@@ -1580,7 +1644,11 @@ function areHumanReviewFieldCardPropsEqual(previous.active === next.active &&previous.activeFieldKey === next.activeFieldKey &&previous.readOnly === next.readOnly &&- previous.onFieldFocus === next.onFieldFocus+ previous.onFieldFocus === next.onFieldFocus &&+ previous.onLocationHover === next.onLocationHover &&+ previous.resolveArrayItemMetadataPath ===+ next.resolveArrayItemMetadataPath &&+ previous.resolveLocation === next.resolveLocation)}@@ -1598,8 +1666,11 @@ function HumanReviewFieldCardBase({readOnly = false,onChange,onFieldFocus,+ onLocationHover,onUndo,onSetNull,+ resolveArrayItemMetadataPath,+ resolveLocation,}: HumanReviewFieldCardProps) {const modified = !jsonValuesEqual(value, originalValue)const Icon = getFieldIcon(field.schema.type)@@ -1642,12 +1713,17 @@ function HumanReviewFieldCardBase({},[])+ const focusAndHoverField = React.useCallback(() => {+ onFieldFocus?.(field)+ onLocationHover?.(getReviewFieldLocation(field, resolveLocation))+ }, [field, onFieldFocus, onLocationHover, resolveLocation])return (<divtabIndex={0}- onFocusCapture={() => onFieldFocus?.(field)}- onMouseEnter={() => onFieldFocus?.(field)}+ onFocusCapture={focusAndHoverField}+ onMouseEnter={focusAndHoverField}+ onMouseLeave={() => onLocationHover?.(undefined)}className={cn("rounded-lg border bg-background p-3 transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:bg-blue-500/5 hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",active &&@@ -1728,6 +1804,7 @@ function HumanReviewFieldCardBase({schema,actual: getObjectValue(field.actual, propertyKey),expected: getObjectValue(originalValue, propertyKey),+ metadataPath: `${field.metadataPath ?? field.key}.${propertyKey}`,}return (@@ -1743,6 +1820,7 @@ function HumanReviewFieldCardBase({onChange(setObjectValue(value, propertyKey, childValue))}onFieldFocus={onFieldFocus}+ onLocationHover={onLocationHover}onUndo={() =>onChange(setObjectValue(value, propertyKey, childField.expected)@@ -1751,6 +1829,8 @@ function HumanReviewFieldCardBase({onSetNull={() =>onChange(setObjectValue(value, propertyKey, null))}+ resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}+ resolveLocation={resolveLocation}/>)})@@ -1767,7 +1847,10 @@ function HumanReviewFieldCardBase({activeNestedSide={syncedArrayNestedView.activeSide}activeSelectionSide={syncedArraySelection.activeSide}label="Actual"+ metadataPath={field.metadataPath ?? field.key}readOnly+ resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}+ resolveLocation={resolveLocation}schema={field.schema}selectionDepth={syncedArraySelection.depth}sharedGridSelection={syncedArraySelection.gridSelection}@@ -1775,13 +1858,17 @@ function HumanReviewFieldCardBase({value={field.actual}viewSide="actual"onGridSelectionChange={updateSyncedArraySelection}+ onLocationHover={onLocationHover}onNestedStackChange={updateSyncedArrayNestedView}/><HumanReviewArrayValueGridactiveNestedSide={syncedArrayNestedView.activeSide}activeSelectionSide={syncedArraySelection.activeSide}label="Expected"+ metadataPath={field.metadataPath ?? field.key}readOnly={readOnly}+ resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}+ resolveLocation={resolveLocation}schema={field.schema}selectionDepth={syncedArraySelection.depth}sharedGridSelection={syncedArraySelection.gridSelection}@@ -1790,6 +1877,7 @@ function HumanReviewFieldCardBase({viewSide="expected"onChange={onChange}onGridSelectionChange={updateSyncedArraySelection}+ onLocationHover={onLocationHover}onNestedStackChange={updateSyncedArrayNestedView}/></div>@@ -1825,15 +1913,13 @@ function HumanReviewFieldCardBase({)}-function HumanReviewHighlight({ field }: { field: ReviewField }) {- const area = field.location?.area-- if (!area) return null+function HumanReviewHighlight({ location }: { location: ReviewLocation }) {+ const area = location.areareturn (<divclassName={cn(- "pointer-events-none absolute z-10 rounded-[3px] border",+ "pointer-events-none absolute z-10 border",REVIEW_HIGHLIGHT_STYLE)}style={{@@ -1905,12 +1991,22 @@ export function HumanReviewPanel({activeFieldKey,className,onFieldFocus,+ onLocationHover,+ resolveArrayItemMetadataPath,+ resolveLocation,theme = "light",}: {fields?: ReviewField[]activeFieldKey?: stringclassName?: stringonFieldFocus?: (field: ReviewField) => void+ onLocationHover?: (location?: ReviewLocation) => void+ resolveArrayItemMetadataPath?: (+ metadataPath: string,+ rowIndex: number,+ rowValue: JsonValue+ ) => string | undefined+ resolveLocation?: (metadataPath: string) => ReviewLocation | undefinedtheme?: HumanReviewTheme} = {}) {const [activeTab, setActiveTab] = React.useState("form")@@ -1976,8 +2072,11 @@ export function HumanReviewPanel({activeFieldKey={activeFieldKey}onChange={(value) => updateValue(field.key, value)}onFieldFocus={onFieldFocus}+ onLocationHover={onLocationHover}onUndo={() => updateValue(field.key, field.expected)}onSetNull={() => updateValue(field.key, null)}+ resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}+ resolveLocation={resolveLocation}/>))}</div>@@ -1999,16 +2098,37 @@ export function HumanReviewBlock({file,fields = REVIEW_FIELDS,className,+ metadata,+ resolveArrayItemMetadataPath,+ resolveLocation,theme,}: {file?: stringfields?: ReviewField[]className?: string+ metadata?: Record<string, ReviewMetadataEntry>+ resolveArrayItemMetadataPath?: (+ metadataPath: string,+ rowIndex: number,+ rowValue: JsonValue+ ) => string | undefined+ resolveLocation?: (metadataPath: string) => ReviewLocation | undefinedtheme?: HumanReviewTheme}) {const [activeFieldKey, setActiveFieldKey] = React.useState(fields[0]?.key)+ const [hoverLocation, setHoverLocation] =+ React.useState<ReviewLocation | null>(null)const viewerRef = React.useRef<PDFViewerHandle>(null)+ const hoverLocationKeyRef = React.useRef<string | null>(null)+ const resolveFieldLocation = React.useCallback(+ (metadataPath: string) =>+ resolveLocation?.(metadataPath) ??+ getMetadataLocation(metadata, metadataPath),+ [metadata, resolveLocation]+ )const activeField = findReviewField(fields, activeFieldKey) ?? fields[0]+ const activeLocation =+ hoverLocation ?? getReviewFieldLocation(activeField, resolveFieldLocation)React.useEffect(() => {if (activeFieldKey || !fields[0]) return@@ -2021,15 +2141,28 @@ export function HumanReviewBlock({setActiveFieldKey(field.key)- if (field.location) {- viewerRef.current?.scrollToPageArea(- field.location.page,- field.location.area- )+ const location = getReviewFieldLocation(field, resolveFieldLocation)+ if (location) {+ viewerRef.current?.scrollToPageArea(location.page, location.area)}},- [activeFieldKey]+ [activeFieldKey, resolveFieldLocation])+ const handleLocationHover = React.useCallback((location?: ReviewLocation) => {+ setHoverLocation(location ?? null)++ const locationKey = getReviewLocationKey(location)+ if (!location) {+ hoverLocationKeyRef.current = null+ return+ }+ if (locationKey === hoverLocationKeyRef.current) return++ hoverLocationKeyRef.current = locationKey+ viewerRef.current?.scrollToPageArea(location.page, location.area, {+ behavior: "auto",+ })+ }, [])return (<PdfBlockResizableShell@@ -2044,8 +2177,8 @@ export function HumanReviewBlock({file={file}defaultZoom={DEFAULT_ZOOM}renderPageOverlay={({ pageNumber }) =>- activeField?.location?.page === pageNumber ? (- <HumanReviewHighlight field={activeField} />+ activeLocation?.page === pageNumber ? (+ <HumanReviewHighlight location={activeLocation} />) : null}/>@@ -2058,6 +2191,9 @@ export function HumanReviewBlock({className="h-full min-h-0"theme={theme}onFieldFocus={focusField}+ onLocationHover={handleLocationHover}+ resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}+ resolveLocation={resolveFieldLocation}/></aside>}diff --git a/apps/v4/registry/new-york-v4/blocks/ocr-blocks.tsx b/apps/v4/registry/new-york-v4/blocks/ocr-blocks.tsxindex 27d650d..6ac8d48 100644--- a/apps/v4/registry/new-york-v4/blocks/ocr-blocks.tsx+++ b/apps/v4/registry/new-york-v4/blocks/ocr-blocks.tsx@@ -2,80 +2,8059 @@import * as React from "react"import {+ AlignBoxBottomCenterIcon,Heading01Icon,+ ImageCompositionIcon,+ LeftToRightListBulletIcon,ParagraphIcon,Table01Icon,+ TextCenterlineCenterTopIcon,+ TextNumberSignIcon,} from "@hugeicons/core-free-icons"import { HugeiconsIcon } from "@hugeicons/react"+import { useVirtualizer } from "@tanstack/react-virtual"import ReactMarkdown from "react-markdown"+import rehypeRaw from "rehype-raw"+import rehypeSanitize, { defaultSchema } from "rehype-sanitize"+import remarkGfm from "remark-gfm"import { cn } from "@/lib/utils"import { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"import { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"+type Point = {+ x: number+ y: number+}++type BoundingBox = {+ left: number+ top: number+ right: number+ bottom: number+}++type OcrBlockType =+ | "heading"+ | "paragraph"+ | "list"+ | "table"+ | "figure"+ | "header"+ | "footer"+ | "page_number"++type ParsedOcrBlock = {+ id: string+ type: string+ content: string+ metadata: {+ page: {+ number: number+ width: number+ height: number+ }+ layoutClass?: string+ minOcrConfidence?: number+ avgOcrConfidence?: number+ }+ polygon?: Point[]+ boundingBox?: BoundingBox+}++type ParsedOcrOutput = {+ chunks: {+ blocks: ParsedOcrBlock[]+ }[]+}+type OcrBlock = {id: string- kind: string+ type: OcrBlockTypetext: stringpage: number+ pageWidth: number+ pageHeight: numberconfidence: number- icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]- accentClassName: string- polygon: { x: number; y: number }[]+ polygon?: Point[]+ boundingBox?: BoundingBox+}++const PDF_URL = "/samples/attention-rotated.pdf"+const OCR_BLOCK_ROW_ESTIMATE = 132+const OCR_BLOCK_LIST_PADDING = 12+const OCR_MARKDOWN_SCHEMA = {+ ...defaultSchema,+ attributes: {+ ...defaultSchema.attributes,+ figure: [...(defaultSchema.attributes?.figure ?? []), "type"],+ },+ tagNames: [+ ...(defaultSchema.tagNames ?? []),+ "caption",+ "figcaption",+ "figure",+ ],}+const OCR_MARKDOWN_REHYPE_PLUGINS: NonNullable<+ React.ComponentProps<typeof ReactMarkdown>["rehypePlugins"]+> = [rehypeRaw, [rehypeSanitize, OCR_MARKDOWN_SCHEMA]]+const OCR_MARKDOWN_REMARK_PLUGINS: NonNullable<+ React.ComponentProps<typeof ReactMarkdown>["remarkPlugins"]+> = [remarkGfm]+const OCR_MARKDOWN_FIGURE_CAPTION_PATTERN = /<\/?caption>/gi++const ATTENTION_OCR_OUTPUT = {+ chunks: [+ {+ blocks: [+ {+ id: "block_1_IKDP4i",+ type: "header",+ content: "arXiv:1706.03762v7 [cs.CL] 2 Aug 2023",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Header",+ minOcrConfidence: 0.959,+ avgOcrConfidence: 0.98,+ },+ polygon: [+ {+ x: 36.16179897837395,+ y: 447.38040863840206,+ },+ {+ x: 75.85163708150822,+ y: 447.38040863840206,+ },+ {+ x: 75.85163708150822,+ y: 1155.1796566956025,+ },+ {+ x: 36.16179897837395,+ y: 1155.1796566956025,+ },+ ],+ boundingBox: {+ left: 36.16179897837395,+ top: 447.38040863840206,+ right: 75.85163708150822,+ bottom: 1155.1796566956025,+ },+ },+ {+ id: "block_1_rtNdsr",+ type: "header",+ content:+ "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.",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Header",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 258.50183528705236,+ y: 151.7837261257315,+ },+ {+ x: 1016.8830982960054,+ y: 151.7837261257315,+ },+ {+ x: 1016.8830982960054,+ y: 233.84929126366637,+ },+ {+ x: 258.50183528705236,+ y: 233.84929126366637,+ },+ ],+ boundingBox: {+ left: 258.50183528705236,+ top: 151.7837261257315,+ right: 1016.8830982960054,+ bottom: 233.84929126366637,+ },+ },+ {+ id: "block_1_eo9AoV",+ type: "heading",+ content: "# Attention Is All You Need",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Heading",+ minOcrConfidence: 0.99,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 440.0215455215343,+ y: 312.01490975860366,+ },+ {+ x: 831.4373211268961,+ y: 312.01490975860366,+ },+ {+ x: 831.4373211268961,+ y: 339.0022611402928,+ },+ {+ x: 440.0215455215343,+ y: 339.0022611402928,+ },+ ],+ boundingBox: {+ left: 440.0215455215343,+ top: 312.01490975860366,+ right: 831.4373211268961,+ bottom: 339.0022611402928,+ },+ },+ {+ id: "block_1_Kdt5Cu",+ type: "text",+ content: "Ashish Vaswani* Google Brain [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.977,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 242.9606625633518,+ y: 490.4495616712068,+ },+ {+ x: 449.64758323056856,+ y: 490.4495616712068,+ },+ {+ x: 449.64758323056856,+ y: 555.9028907431696,+ },+ {+ x: 242.9606625633518,+ y: 555.9028907431696,+ },+ ],+ boundingBox: {+ left: 242.9606625633518,+ top: 490.4495616712068,+ right: 449.64758323056856,+ bottom: 555.9028907431696,+ },+ },+ {+ id: "block_1_6Xv6uR",+ type: "text",+ content: "Llion Jones* Google Research [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.927,+ avgOcrConfidence: 0.982,+ },+ polygon: [+ {+ x: 264.3723327748097,+ y: 594.5307239733245,+ },+ {+ x: 438.3605845653227,+ y: 594.5307239733245,+ },+ {+ x: 438.3605845653227,+ y: 660.7685646688132,+ },+ {+ x: 264.3723327748097,+ y: 660.7685646688132,+ },+ ],+ boundingBox: {+ left: 264.3723327748097,+ top: 594.5307239733245,+ right: 438.3605845653227,+ bottom: 660.7685646688132,+ },+ },+ {+ id: "block_1_Lx35WU",+ type: "text",+ content: "Noam Shazeer* Google Brain [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.983,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 479.08373644752226,+ y: 490.1169480632122,+ },+ {+ x: 643.7573955006842,+ y: 490.1169480632122,+ },+ {+ x: 643.7573955006842,+ y: 556.2343205043247,+ },+ {+ x: 479.08373644752226,+ y: 556.2343205043247,+ },+ ],+ boundingBox: {+ left: 479.08373644752226,+ top: 490.1169480632122,+ right: 643.7573955006842,+ bottom: 556.2343205043247,+ },+ },+ {+ id: "block_1_VxOJIL",+ type: "text",+ content:+ "Aidan N. Gomez* * University of Toronto [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.095,+ avgOcrConfidence: 0.875,+ },+ polygon: [+ {+ x: 489.9820146769503,+ y: 593.5908916444707,+ },+ {+ x: 708.1676900821881,+ y: 593.5908916444707,+ },+ {+ x: 708.1676900821881,+ y: 657.7173651788468,+ },+ {+ x: 489.9820146769503,+ y: 657.7173651788468,+ },+ ],+ boundingBox: {+ left: 489.9820146769503,+ top: 593.5908916444707,+ right: 708.1676900821881,+ bottom: 657.7173651788468,+ },+ },+ {+ id: "block_1_m1Gb17",+ type: "text",+ content: "Niki Parmar* Google Research [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.99,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 673.3537325893875,+ y: 490.2837284059453,+ },+ {+ x: 848.6601168221802,+ y: 490.2837284059453,+ },+ {+ x: 848.6601168221802,+ y: 556.287735673718,+ },+ {+ x: 673.3537325893875,+ y: 556.287735673718,+ },+ ],+ boundingBox: {+ left: 673.3537325893875,+ top: 490.2837284059453,+ right: 848.6601168221802,+ bottom: 556.287735673718,+ },+ },+ {+ id: "block_1_otnY8T",+ type: "text",+ content: "\u0141ukasz Kaiser* Google Brain [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.984,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 759.3324257509552,+ y: 594.2661578816579,+ },+ {+ x: 1011.1333304078039,+ y: 594.2661578816579,+ },+ {+ x: 1011.1333304078039,+ y: 660.9298993160851,+ },+ {+ x: 759.3324257509552,+ y: 660.9298993160851,+ },+ ],+ boundingBox: {+ left: 759.3324257509552,+ top: 594.2661578816579,+ right: 1011.1333304078039,+ bottom: 660.9298993160851,+ },+ },+ {+ id: "block_1_ICaos6",+ type: "text",+ content: "Illia Polosukhin* * [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.107,+ avgOcrConfidence: 0.766,+ },+ polygon: [+ {+ x: 495.9563429338219,+ y: 697.325802423004,+ },+ {+ x: 778.5449758933407,+ y: 697.325802423004,+ },+ {+ x: 778.5449758933407,+ y: 742.1158899292909,+ },+ {+ x: 495.9563429338219,+ y: 742.1158899292909,+ },+ ],+ boundingBox: {+ left: 495.9563429338219,+ top: 697.325802423004,+ right: 778.5449758933407,+ bottom: 742.1158899292909,+ },+ },+ {+ id: "block_1_zNN0g5",+ type: "section_heading",+ content: "### Abstract",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 590.8429918498018,+ y: 804.3203170891095,+ },+ {+ x: 683.8031267597728,+ y: 804.3203170891095,+ },+ {+ x: 683.8031267597728,+ y: 823.7656170264223,+ },+ {+ x: 590.8429918498018,+ y: 823.7656170264223,+ },+ ],+ boundingBox: {+ left: 590.8429918498018,+ top: 804.3203170891095,+ right: 683.8031267597728,+ bottom: 823.7656170264223,+ },+ },+ {+ id: "block_1_Pzc7ia",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.987,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 298.2268201173657,+ y: 861.5167879950731,+ },+ {+ x: 978.0244980415288,+ y: 861.5167879950731,+ },+ {+ x: 978.0244980415288,+ y: 1201.6481075430274,+ },+ {+ x: 298.2268201173657,+ y: 1201.6481075430274,+ },+ ],+ boundingBox: {+ left: 298.2268201173657,+ top: 861.5167879950731,+ right: 978.0244980415288,+ bottom: 1201.6481075430274,+ },+ },+ {+ id: "block_1_bHnLKj",+ type: "text",+ content:+ "*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.",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.951,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 222.8755505415645,+ y: 1247.2573697082978,+ },+ {+ x: 1049.6971241749116,+ y: 1247.2573697082978,+ },+ {+ x: 1049.6971241749116,+ y: 1429.7100451476592,+ },+ {+ x: 222.8755505415645,+ y: 1429.7100451476592,+ },+ ],+ boundingBox: {+ left: 222.8755505415645,+ top: 1247.2573697082978,+ right: 1049.6971241749116,+ bottom: 1429.7100451476592,+ },+ },+ {+ id: "block_1_J3Olku",+ type: "text",+ content: "+ Work performed while at Google Brain.",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.11,+ avgOcrConfidence: 0.869,+ },+ polygon: [+ {+ x: 250.1677060649343,+ y: 1434.3817888991277,+ },+ {+ x: 555.1793119333087,+ y: 1434.3817888991277,+ },+ {+ x: 555.1793119333087,+ y: 1456.532320926064,+ },+ {+ x: 250.1677060649343,+ y: 1456.532320926064,+ },+ ],+ boundingBox: {+ left: 250.1677060649343,+ top: 1434.3817888991277,+ right: 555.1793119333087,+ bottom: 1456.532320926064,+ },+ },+ {+ id: "block_1_aQsakB",+ type: "text",+ content: "#Work performed while at Google Research.",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.652,+ avgOcrConfidence: 0.94,+ },+ polygon: [+ {+ x: 249.36288151427775,+ y: 1458.4100914288283,+ },+ {+ x: 582.4047478446125,+ y: 1458.4100914288283,+ },+ {+ x: 582.4047478446125,+ y: 1479.773507369192,+ },+ {+ x: 249.36288151427775,+ y: 1479.773507369192,+ },+ ],+ boundingBox: {+ left: 249.36288151427775,+ top: 1458.4100914288283,+ right: 582.4047478446125,+ bottom: 1479.773507369192,+ },+ },+ {+ id: "block_1_iKp4Ae",+ type: "footer",+ content:+ "31st Conference on Neural Information Processing Systems (NIPS 2017), Long Beach, CA, USA.",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Footer",+ minOcrConfidence: 0.99,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 224.27405893367575,+ y: 1527.1945287374626,+ },+ {+ x: 958.2568426201814,+ y: 1527.1945287374626,+ },+ {+ x: 958.2568426201814,+ y: 1546.3855383736748,+ },+ {+ x: 224.27405893367575,+ y: 1546.3855383736748,+ },+ ],+ boundingBox: {+ left: 224.27405893367575,+ top: 1527.1945287374626,+ right: 958.2568426201814,+ bottom: 1546.3855383736748,+ },+ },+ {+ id: "block_1_zPHQaR",+ type: "text",+ content: "Jakob Uszkoreit* Google Research [email protected]",+ metadata: {+ page: {+ number: 1,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 879.2488933479699,+ y: 489.58686880240765,+ },+ {+ x: 1035.003756780694,+ y: 489.58686880240765,+ },+ {+ x: 1035.003756780694,+ y: 555.848623204052,+ },+ {+ x: 879.2488933479699,+ y: 555.848623204052,+ },+ ],+ boundingBox: {+ left: 879.2488933479699,+ top: 489.58686880240765,+ right: 1035.003756780694,+ bottom: 555.848623204052,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_2_UD1C1k",+ type: "heading",+ content: "# 1 Introduction",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Heading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 225.86025321570625,+ y: 152.1792611932396,+ },+ {+ x: 396.86960095036636,+ y: 152.1792611932396,+ },+ {+ x: 396.86960095036636,+ y: 171.96800693712737,+ },+ {+ x: 225.86025321570625,+ y: 171.96800693712737,+ },+ ],+ boundingBox: {+ left: 225.86025321570625,+ top: 152.1792611932396,+ right: 396.86960095036636,+ bottom: 171.96800693712737,+ },+ },+ {+ id: "block_2_C25o9D",+ type: "text",+ content:+ "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].",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.908,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 223.64054213475134,+ y: 206.4059457563816,+ },+ {+ x: 1050.9159227357293,+ y: 206.4059457563816,+ },+ {+ x: 1050.9159227357293,+ y: 316.89823061720773,+ },+ {+ x: 223.64054213475134,+ y: 316.89823061720773,+ },+ ],+ boundingBox: {+ left: 223.64054213475134,+ top: 206.4059457563816,+ right: 1050.9159227357293,+ bottom: 316.89823061720773,+ },+ },+ {+ id: "block_2_Cw1VyU",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.9,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 223.69928568819142,+ y: 331.227654822787,+ },+ {+ x: 1049.6158961832089,+ y: 331.227654822787,+ },+ {+ x: 1049.6158961832089,+ y: 511.80734250061494,+ },+ {+ x: 223.69928568819142,+ y: 511.80734250061494,+ },+ ],+ boundingBox: {+ left: 223.69928568819142,+ top: 331.227654822787,+ right: 1049.6158961832089,+ bottom: 511.80734250061494,+ },+ },+ {+ id: "block_2_FR7zlH",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.959,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 223.38852708357095,+ y: 525.5238181666324,+ },+ {+ x: 1052.1732525233804,+ y: 525.5238181666324,+ },+ {+ x: 1052.1732525233804,+ y: 613.7107948647406,+ },+ {+ x: 223.38852708357095,+ y: 613.7107948647406,+ },+ ],+ boundingBox: {+ left: 223.38852708357095,+ top: 525.5238181666324,+ right: 1052.1732525233804,+ bottom: 613.7107948647406,+ },+ },+ {+ id: "block_2_ZyhlFh",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.991,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 223.20226126343667,+ y: 627.2328828797304,+ },+ {+ x: 1052.7354108156078,+ y: 627.2328828797304,+ },+ {+ x: 1052.7354108156078,+ y: 716.0174654623619,+ },+ {+ x: 223.20226126343667,+ y: 716.0174654623619,+ },+ ],+ boundingBox: {+ left: 223.20226126343667,+ top: 627.2328828797304,+ right: 1052.7354108156078,+ bottom: 716.0174654623619,+ },+ },+ {+ id: "block_2_MZBXjP",+ type: "section_heading",+ content: "### 2 Background",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.994,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 224.22355178498873,+ y: 757.4257287333783,+ },+ {+ x: 392.45446198178036,+ y: 757.4257287333783,+ },+ {+ x: 392.45446198178036,+ y: 781.2853567654029,+ },+ {+ x: 224.22355178498873,+ y: 781.2853567654029,+ },+ ],+ boundingBox: {+ left: 224.22355178498873,+ top: 757.4257287333783,+ right: 392.45446198178036,+ bottom: 781.2853567654029,+ },+ },+ {+ id: "block_2_JeOnOk",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.893,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 223.30221050847186,+ y: 810.9956032315591,+ },+ {+ x: 1051.187440078624,+ y: 810.9956032315591,+ },+ {+ x: 1051.187440078624,+ y: 1010.7095232511822,+ },+ {+ x: 223.30221050847186,+ y: 1010.7095232511822,+ },+ ],+ boundingBox: {+ left: 223.30221050847186,+ top: 810.9956032315591,+ right: 1051.187440078624,+ bottom: 1010.7095232511822,+ },+ },+ {+ id: "block_2_tEzlrD",+ type: "text",+ content:+ "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].",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.984,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 224.00045882176306,+ y: 1028.0413251030714,+ },+ {+ x: 1051.4467448213675,+ y: 1028.0413251030714,+ },+ {+ x: 1051.4467448213675,+ y: 1116.9915041815966,+ },+ {+ x: 224.00045882176306,+ y: 1116.9915041815966,+ },+ ],+ boundingBox: {+ left: 224.00045882176306,+ top: 1028.0413251030714,+ right: 1051.4467448213675,+ bottom: 1116.9915041815966,+ },+ },+ {+ id: "block_2_AFJ4ch",+ type: "text",+ content:+ "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].",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.963,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 224.05524984763485,+ y: 1129.9793457949072,+ },+ {+ x: 1052.8165441359918,+ y: 1129.9793457949072,+ },+ {+ x: 1052.8165441359918,+ y: 1196.1117767678168,+ },+ {+ x: 224.05524984763485,+ y: 1196.1117767678168,+ },+ ],+ boundingBox: {+ left: 224.05524984763485,+ top: 1129.9793457949072,+ right: 1052.8165441359918,+ bottom: 1196.1117767678168,+ },+ },+ {+ id: "block_2_CBbJP3",+ type: "text",+ content:+ "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].",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.898,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 222.86987026242443,+ y: 1210.5673043387276,+ },+ {+ x: 1052.2374396776631,+ y: 1210.5673043387276,+ },+ {+ x: 1052.2374396776631,+ y: 1298.352294004053,+ },+ {+ x: 222.86987026242443,+ y: 1298.352294004053,+ },+ ],+ boundingBox: {+ left: 222.86987026242443,+ top: 1210.5673043387276,+ right: 1052.2374396776631,+ bottom: 1298.352294004053,+ },+ },+ {+ id: "block_2_RlRHBW",+ type: "section_heading",+ content: "### 3 Model Architecture",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.993,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 224.20267675914906,+ y: 1339.2827093368187,+ },+ {+ x: 470.2105250671832,+ y: 1339.2827093368187,+ },+ {+ x: 470.2105250671832,+ y: 1359.0320211424864,+ },+ {+ x: 224.20267675914906,+ y: 1359.0320211424864,+ },+ ],+ boundingBox: {+ left: 224.20267675914906,+ top: 1339.2827093368187,+ right: 470.2105250671832,+ bottom: 1359.0320211424864,+ },+ },+ {+ id: "block_2_OhVaOm",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.619,+ avgOcrConfidence: 0.969,+ },+ polygon: [+ {+ x: 223.9033023806384,+ y: 1394.2295871247027,+ },+ {+ x: 1051.703398767179,+ y: 1394.2295871247027,+ },+ {+ x: 1051.703398767179,+ y: 1505.850527885265,+ },+ {+ x: 223.9033023806384,+ y: 1505.850527885265,+ },+ ],+ boundingBox: {+ left: 223.9033023806384,+ top: 1394.2295871247027,+ right: 1051.703398767179,+ bottom: 1505.850527885265,+ },+ },+ {+ id: "block_2_MzhUlf",+ type: "page_number",+ content: "2",+ metadata: {+ page: {+ number: 2,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 631.4816022441336,+ y: 1547.6769732138268,+ },+ {+ x: 642.0810031194757,+ y: 1547.6769732138268,+ },+ {+ x: 642.0810031194757,+ y: 1563.2578182363868,+ },+ {+ x: 631.4816022441336,+ y: 1563.2578182363868,+ },+ ],+ boundingBox: {+ left: 631.4816022441336,+ top: 1547.6769732138268,+ right: 642.0810031194757,+ bottom: 1563.2578182363868,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_3_afwbz8",+ type: "figure",+ content:+ '<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>',+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Picture/Figure/Image/Chart",+ minOcrConfidence: 0.868,+ avgOcrConfidence: 0.987,+ },+ polygon: [+ {+ x: 409.83791490540887,+ y: 150.86351013900642,+ },+ {+ x: 863.1759754932709,+ y: 150.86351013900642,+ },+ {+ x: 863.1759754932709,+ y: 821.7723977798806,+ },+ {+ x: 409.83791490540887,+ y: 821.7723977798806,+ },+ ],+ boundingBox: {+ left: 409.83791490540887,+ top: 150.86351013900642,+ right: 863.1759754932709,+ bottom: 821.7723977798806,+ },+ },+ {+ id: "block_3_1WIk1S",+ type: "text",+ content: "Figure 1: The Transformer - model architecture.",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.989,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 436.4703770101505,+ y: 843.2910397178248,+ },+ {+ x: 836.1937028648209,+ y: 843.2910397178248,+ },+ {+ x: 836.1937028648209,+ y: 863.7018851373429,+ },+ {+ x: 436.4703770101505,+ y: 863.7018851373429,+ },+ ],+ boundingBox: {+ left: 436.4703770101505,+ top: 843.2910397178248,+ right: 836.1937028648209,+ bottom: 863.7018851373429,+ },+ },+ {+ id: "block_3_jyPEOL",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.973,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 222.86804783953366,+ y: 910.1303693154701,+ },+ {+ x: 1051.9256870241932,+ y: 910.1303693154701,+ },+ {+ x: 1051.9256870241932,+ y: 977.3362178945899,+ },+ {+ x: 222.86804783953366,+ y: 977.3362178945899,+ },+ ],+ boundingBox: {+ left: 222.86804783953366,+ top: 910.1303693154701,+ right: 1051.9256870241932,+ bottom: 977.3362178945899,+ },+ },+ {+ id: "block_3_nEQfm1",+ type: "section_heading",+ content: "### 3.1 Encoder and Decoder Stacks",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 223.72352154585568,+ y: 1007.3903008367782,+ },+ {+ x: 527.4041196725664,+ y: 1007.3903008367782,+ },+ {+ x: 527.4041196725664,+ y: 1023.9329030316575,+ },+ {+ x: 223.72352154585568,+ y: 1023.9329030316575,+ },+ ],+ boundingBox: {+ left: 223.72352154585568,+ top: 1007.3903008367782,+ right: 527.4041196725664,+ bottom: 1023.9329030316575,+ },+ },+ {+ id: "block_3_W2U9b2",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.657,+ avgOcrConfidence: 0.984,+ },+ polygon: [+ {+ x: 223.8025010937322,+ y: 1048.091523421438,+ },+ {+ x: 1053.5889674277203,+ y: 1048.091523421438,+ },+ {+ x: 1053.5889674277203,+ y: 1206.3018568225373,+ },+ {+ x: 223.8025010937322,+ y: 1206.3018568225373,+ },+ ],+ boundingBox: {+ left: 223.8025010937322,+ top: 1048.091523421438,+ right: 1053.5889674277203,+ bottom: 1206.3018568225373,+ },+ },+ {+ id: "block_3_8wxg0F",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.633,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 224.16407452882643,+ y: 1233.3413921729066,+ },+ {+ x: 1049.721170689938,+ y: 1233.3413921729066,+ },+ {+ x: 1049.721170689938,+ y: 1391.0596241198086,+ },+ {+ x: 224.16407452882643,+ y: 1391.0596241198086,+ },+ ],+ boundingBox: {+ left: 224.16407452882643,+ top: 1233.3413921729066,+ right: 1049.721170689938,+ bottom: 1391.0596241198086,+ },+ },+ {+ id: "block_3_i0stGS",+ type: "section_heading",+ content: "### 3.2 Attention",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 224.0832962258889,+ y: 1421.7722100279386,+ },+ {+ x: 354.57085797386446,+ y: 1421.7722100279386,+ },+ {+ x: 354.57085797386446,+ y: 1437.668053017523,+ },+ {+ x: 224.0832962258889,+ y: 1437.668053017523,+ },+ ],+ boundingBox: {+ left: 224.0832962258889,+ top: 1421.7722100279386,+ right: 354.57085797386446,+ bottom: 1437.668053017523,+ },+ },+ {+ id: "block_3_LwJLS3",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.986,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.38670466068018,+ y: 1462.3713376611695,+ },+ {+ x: 1052.432178580848,+ y: 1462.3713376611695,+ },+ {+ x: 1052.432178580848,+ y: 1506.3117546138906,+ },+ {+ x: 223.38670466068018,+ y: 1506.3117546138906,+ },+ ],+ boundingBox: {+ left: 223.38670466068018,+ top: 1462.3713376611695,+ right: 1052.432178580848,+ bottom: 1506.3117546138906,+ },+ },+ {+ id: "block_3_gqT8MC",+ type: "page_number",+ content: "3",+ metadata: {+ page: {+ number: 3,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.997,+ avgOcrConfidence: 0.997,+ },+ polygon: [+ {+ x: 632.2706403523466,+ y: 1547.236487481827,+ },+ {+ x: 642.0801037419451,+ y: 1547.236487481827,+ },+ {+ x: 642.0801037419451,+ y: 1562.977578012567,+ },+ {+ x: 632.2706403523466,+ y: 1562.977578012567,+ },+ ],+ boundingBox: {+ left: 632.2706403523466,+ top: 1547.236487481827,+ right: 642.0801037419451,+ bottom: 1562.977578012567,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_4_PplY2k",+ type: "header",+ content: "Scaled Dot-Product Attention",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Header",+ minOcrConfidence: 0.993,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 307.9120037329458,+ y: 148.57123934236685,+ },+ {+ x: 554.1308270753735,+ y: 148.57123934236685,+ },+ {+ x: 554.1308270753735,+ y: 164.4924521697195,+ },+ {+ x: 307.9120037329458,+ y: 164.4924521697195,+ },+ ],+ boundingBox: {+ left: 307.9120037329458,+ top: 148.57123934236685,+ right: 554.1308270753735,+ bottom: 164.4924521697195,+ },+ },+ {+ id: "block_4_TZACGH",+ type: "text",+ content: "Multi-Head Attention",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.993,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 756.6973442578839,+ y: 148.30866211339045,+ },+ {+ x: 937.5759876557511,+ y: 148.30866211339045,+ },+ {+ x: 937.5759876557511,+ y: 164.44492071911804,+ },+ {+ x: 756.6973442578839,+ y: 164.44492071911804,+ },+ ],+ boundingBox: {+ left: 756.6973442578839,+ top: 148.30866211339045,+ right: 937.5759876557511,+ bottom: 164.44492071911804,+ },+ },+ {+ id: "block_4_yRQL9Y",+ type: "figure",+ content:+ '<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>',+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Picture/Figure/Image/Chart",+ minOcrConfidence: 0.226,+ avgOcrConfidence: 0.815,+ },+ polygon: [+ {+ x: 364.7714322500855,+ y: 195.77549835434533,+ },+ {+ x: 497.28713766501767,+ y: 195.77549835434533,+ },+ {+ x: 497.28713766501767,+ y: 457.62115733784844,+ },+ {+ x: 364.7714322500855,+ y: 457.62115733784844,+ },+ ],+ boundingBox: {+ left: 364.7714322500855,+ top: 195.77549835434533,+ right: 497.28713766501767,+ bottom: 457.62115733784844,+ },+ },+ {+ id: "block_4_goCdts",+ type: "figure",+ content:+ '<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>',+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Picture/Figure/Image/Chart",+ minOcrConfidence: 0.981,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 723.0441991430129,+ y: 171.2063080421964,+ },+ {+ x: 971.0292342805515,+ y: 171.2063080421964,+ },+ {+ x: 971.0292342805515,+ y: 495.8982404264292,+ },+ {+ x: 723.0441991430129,+ y: 495.8982404264292,+ },+ ],+ boundingBox: {+ left: 723.0441991430129,+ top: 171.2063080421964,+ right: 971.0292342805515,+ bottom: 495.8982404264292,+ },+ },+ {+ id: "block_4_ZQ6XHX",+ type: "text",+ content:+ "Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel.",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.991,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 224.32437673972473,+ y: 572.2067347074809,+ },+ {+ x: 1050.060662039875,+ y: 572.2067347074809,+ },+ {+ x: 1050.060662039875,+ y: 615.706381804961,+ },+ {+ x: 224.32437673972473,+ y: 615.706381804961,+ },+ ],+ boundingBox: {+ left: 224.32437673972473,+ top: 572.2067347074809,+ right: 1050.060662039875,+ bottom: 615.706381804961,+ },+ },+ {+ id: "block_4_seZO33",+ type: "text",+ content:+ "of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.989,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 224.44408862260138,+ y: 661.3754045586836,+ },+ {+ x: 1049.3653012018135,+ y: 661.3754045586836,+ },+ {+ x: 1049.3653012018135,+ y: 705.0281940833071,+ },+ {+ x: 224.44408862260138,+ y: 705.0281940833071,+ },+ ],+ boundingBox: {+ left: 224.44408862260138,+ top: 661.3754045586836,+ right: 1049.3653012018135,+ bottom: 705.0281940833071,+ },+ },+ {+ id: "block_4_CMgLHk",+ type: "section_heading",+ content: "### 3.2.1 Scaled Dot-Product Attention",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.53467593227862,+ y: 732.4767248397483,+ },+ {+ x: 549.2687448097842,+ y: 732.4767248397483,+ },+ {+ x: 549.2687448097842,+ y: 748.6887496431967,+ },+ {+ x: 223.53467593227862,+ y: 748.6887496431967,+ },+ ],+ boundingBox: {+ left: 223.53467593227862,+ top: 732.4767248397483,+ right: 549.2687448097842,+ bottom: 748.6887496431967,+ },+ },+ {+ id: "block_4_fmfLoy",+ type: "text",+ content:+ '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.',+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.594,+ avgOcrConfidence: 0.98,+ },+ polygon: [+ {+ x: 223.39593511428276,+ y: 771.1101458269851,+ },+ {+ x: 1051.4275265436104,+ y: 771.1101458269851,+ },+ {+ x: 1051.4275265436104,+ y: 856.1295272138783,+ },+ {+ x: 223.39593511428276,+ y: 856.1295272138783,+ },+ ],+ boundingBox: {+ left: 223.39593511428276,+ top: 771.1101458269851,+ right: 1051.4275265436104,+ bottom: 856.1295272138783,+ },+ },+ {+ id: "block_4_cDuW6h",+ type: "text",+ content:+ "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:",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.976,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 224.08788778486044,+ y: 873.4355685585424,+ },+ {+ x: 1050.3812191260122,+ y: 873.4355685585424,+ },+ {+ x: 1050.3812191260122,+ y: 938.6725377821385,+ },+ {+ x: 224.08788778486044,+ y: 938.6725377821385,+ },+ ],+ boundingBox: {+ left: 224.08788778486044,+ top: 873.4355685585424,+ right: 1050.3812191260122,+ bottom: 938.6725377821385,+ },+ },+ {+ id: "block_4_VaSWNE",+ type: "text",+ content: "QKT Attention(Q, K, V) = softmax( V Vdk",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Formula",+ minOcrConfidence: 0.908,+ avgOcrConfidence: 0.961,+ },+ polygon: [+ {+ x: 458.52888900868214,+ y: 968.9788274549901,+ },+ {+ x: 816.6205023327013,+ y: 968.9788274549901,+ },+ {+ x: 816.6205023327013,+ y: 1021.9395890773686,+ },+ {+ x: 458.52888900868214,+ y: 1021.9395890773686,+ },+ ],+ boundingBox: {+ left: 458.52888900868214,+ top: 968.9788274549901,+ right: 816.6205023327013,+ bottom: 1021.9395890773686,+ },+ },+ {+ id: "block_4_Wtl7xI",+ type: "text",+ content: "(1)",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 1026.9459968065694,+ y: 986.4570474839747,+ },+ {+ x: 1051.0514920645387,+ y: 986.4570474839747,+ },+ {+ x: 1051.0514920645387,+ y: 1005.8566982871607,+ },+ {+ x: 1026.9459968065694,+ y: 1005.8566982871607,+ },+ ],+ boundingBox: {+ left: 1026.9459968065694,+ top: 986.4570474839747,+ right: 1051.0514920645387,+ bottom: 1005.8566982871607,+ },+ },+ {+ id: "block_4_HVInAp",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.098,+ avgOcrConfidence: 0.981,+ },+ polygon: [+ {+ x: 223.11696240501684,+ y: 1041.6009173859331,+ },+ {+ x: 1052.8067929901345,+ y: 1041.6009173859331,+ },+ {+ x: 1052.8067929901345,+ y: 1180.0422397699572,+ },+ {+ x: 223.11696240501684,+ y: 1180.0422397699572,+ },+ ],+ boundingBox: {+ left: 223.11696240501684,+ top: 1041.6009173859331,+ right: 1052.8067929901345,+ bottom: 1180.0422397699572,+ },+ },+ {+ id: "block_4_6NHlzf",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.58,+ avgOcrConfidence: 0.98,+ },+ polygon: [+ {+ x: 223.18699551324775,+ y: 1194.0708248167111,+ },+ {+ x: 1050.8364934990875,+ y: 1194.0708248167111,+ },+ {+ x: 1050.8364934990875,+ y: 1289.5664457163416,+ },+ {+ x: 223.18699551324775,+ y: 1289.5664457163416,+ },+ ],+ boundingBox: {+ left: 223.18699551324775,+ top: 1194.0708248167111,+ right: 1050.8364934990875,+ bottom: 1289.5664457163416,+ },+ },+ {+ id: "block_4_4VWmvI",+ type: "section_heading",+ content: "### 3.2.2 Multi-Head Attention",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.994,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.5976323594142,+ y: 1315.4335938647278,+ },+ {+ x: 479.8474026422431,+ y: 1315.4335938647278,+ },+ {+ x: 479.8474026422431,+ y: 1331.4542616650574,+ },+ {+ x: 223.5976323594142,+ y: 1331.4542616650574,+ },+ ],+ boundingBox: {+ left: 223.5976323594142,+ top: 1315.4335938647278,+ right: 479.8474026422431,+ bottom: 1331.4542616650574,+ },+ },+ {+ id: "block_4_n7aPpb",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.619,+ avgOcrConfidence: 0.979,+ },+ polygon: [+ {+ x: 223.83094982509195,+ y: 1354.33461159154,+ },+ {+ x: 1052.0098498267848,+ y: 1354.33461159154,+ },+ {+ x: 1052.0098498267848,+ y: 1442.8801044664883,+ },+ {+ x: 223.83094982509195,+ y: 1442.8801044664883,+ },+ ],+ boundingBox: {+ left: 223.83094982509195,+ top: 1354.33461159154,+ right: 1052.0098498267848,+ bottom: 1442.8801044664883,+ },+ },+ {+ id: "block_4_rfqNPC",+ type: "text",+ content:+ "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-",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.105,+ avgOcrConfidence: 0.921,+ },+ polygon: [+ {+ x: 224.42529636577967,+ y: 1459.9841341864794,+ },+ {+ x: 1049.4534401998033,+ y: 1459.9841341864794,+ },+ {+ x: 1049.4534401998033,+ y: 1506.815978659723,+ },+ {+ x: 224.42529636577967,+ y: 1506.815978659723,+ },+ ],+ boundingBox: {+ left: 224.42529636577967,+ top: 1459.9841341864794,+ right: 1049.4534401998033,+ bottom: 1506.815978659723,+ },+ },+ {+ id: "block_4_35BhDQ",+ type: "page_number",+ content: "4",+ metadata: {+ page: {+ number: 4,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.996,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 631.2688757903385,+ y: 1548.1330857241064,+ },+ {+ x: 642.0564832478544,+ y: 1548.1330857241064,+ },+ {+ x: 642.0564832478544,+ y: 1562.0727401962854,+ },+ {+ x: 631.2688757903385,+ y: 1562.0727401962854,+ },+ ],+ boundingBox: {+ left: 631.2688757903385,+ top: 1548.1330857241064,+ right: 642.0564832478544,+ bottom: 1562.0727401962854,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_5_Zc8VSW",+ type: "text",+ content:+ "output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure 2.",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.988,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 224.67903916853186,+ y: 155.68632458564932,+ },+ {+ x: 1049.4719957783275,+ y: 155.68632458564932,+ },+ {+ x: 1049.4719957783275,+ y: 199.30535079841326,+ },+ {+ x: 224.67903916853186,+ y: 199.30535079841326,+ },+ ],+ boundingBox: {+ left: 224.67903916853186,+ top: 155.68632458564932,+ right: 1049.4719957783275,+ bottom: 199.30535079841326,+ },+ },+ {+ id: "block_5_P72mUL",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 224.58133836732293,+ y: 212.29537068990837,+ },+ {+ x: 1049.5524663994781,+ y: 212.29537068990837,+ },+ {+ x: 1049.5524663994781,+ y: 255.9039790504857,+ },+ {+ x: 224.58133836732293,+ y: 255.9039790504857,+ },+ ],+ boundingBox: {+ left: 224.58133836732293,+ top: 212.29537068990837,+ right: 1049.5524663994781,+ bottom: 255.9039790504857,+ },+ },+ {+ id: "block_5_zTpvNY",+ type: "text",+ content:+ "MultiHead(Q,K,V)=Concat(head1, ... , headh)W\u00ba where head; = Attention(Qw?, KWK,VW)",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Formula",+ minOcrConfidence: 0.581,+ avgOcrConfidence: 0.796,+ },+ polygon: [+ {+ x: 388.73733464818804,+ y: 302.5467395065422,+ },+ {+ x: 883.3280911410811,+ y: 302.5467395065422,+ },+ {+ x: 883.3280911410811,+ y: 364.6030674267532,+ },+ {+ x: 388.73733464818804,+ y: 364.6030674267532,+ },+ ],+ boundingBox: {+ left: 388.73733464818804,+ top: 302.5467395065422,+ right: 883.3280911410811,+ bottom: 364.6030674267532,+ },+ },+ {+ id: "block_5_cOSQOc",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.252,+ avgOcrConfidence: 0.682,+ },+ polygon: [+ {+ x: 223.51567066498916,+ y: 424.5787134959285,+ },+ {+ x: 1047.1388211215499,+ y: 424.5787134959285,+ },+ {+ x: 1047.1388211215499,+ y: 472.1556711698833,+ },+ {+ x: 223.51567066498916,+ y: 472.1556711698833,+ },+ ],+ boundingBox: {+ left: 223.51567066498916,+ top: 424.5787134959285,+ right: 1047.1388211215499,+ bottom: 472.1556711698833,+ },+ },+ {+ id: "block_5_4oR3J2",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.557,+ avgOcrConfidence: 0.98,+ },+ polygon: [+ {+ x: 223.83189653828197,+ y: 488.323372747665,+ },+ {+ x: 1049.9097559573877,+ y: 488.323372747665,+ },+ {+ x: 1049.9097559573877,+ y: 555.0531728357302,+ },+ {+ x: 223.83189653828197,+ y: 555.0531728357302,+ },+ ],+ boundingBox: {+ left: 223.83189653828197,+ top: 488.323372747665,+ right: 1049.9097559573877,+ bottom: 555.0531728357302,+ },+ },+ {+ id: "block_5_oGR7Tp",+ type: "section_heading",+ content: "### 3.2.3 Applications of Attention in our Model",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.994,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 223.9031130380004,+ y: 584.1135347409356,+ },+ {+ x: 629.6546824657133,+ y: 584.1135347409356,+ },+ {+ x: 629.6546824657133,+ y: 605.02614180486,+ },+ {+ x: 223.9031130380004,+ y: 605.02614180486,+ },+ ],+ boundingBox: {+ left: 223.9031130380004,+ top: 584.1135347409356,+ right: 629.6546824657133,+ bottom: 605.02614180486,+ },+ },+ {+ id: "block_5_b34egv",+ type: "text",+ content:+ "The Transformer uses multi-head attention in three different ways:",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.3985859112148,+ y: 623.9660812033746,+ },+ {+ x: 775.7513199409428,+ y: 623.9660812033746,+ },+ {+ x: 775.7513199409428,+ y: 644.7702005429376,+ },+ {+ x: 223.3985859112148,+ y: 644.7702005429376,+ },+ ],+ boundingBox: {+ left: 223.3985859112148,+ top: 623.9660812033746,+ right: 775.7513199409428,+ bottom: 644.7702005429376,+ },+ },+ {+ id: "block_5_NSYaLO",+ type: "text",+ content:+ '\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].',+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.586,+ avgOcrConfidence: 0.984,+ },+ polygon: [+ {+ x: 281.7719981618171,+ y: 667.4162908568419,+ },+ {+ x: 1052.1352893244612,+ y: 667.4162908568419,+ },+ {+ x: 1052.1352893244612,+ y: 778.3123385207098,+ },+ {+ x: 281.7719981618171,+ y: 778.3123385207098,+ },+ ],+ boundingBox: {+ left: 281.7719981618171,+ top: 667.4162908568419,+ right: 1052.1352893244612,+ bottom: 778.3123385207098,+ },+ },+ {+ id: "block_5_ZbEUX6",+ type: "text",+ content:+ "\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.",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.407,+ avgOcrConfidence: 0.983,+ },+ polygon: [+ {+ x: 282.1731915439132,+ y: 791.5420637202442,+ },+ {+ x: 1049.6795153095775,+ y: 791.5420637202442,+ },+ {+ x: 1049.6795153095775,+ y: 876.9418387735697,+ },+ {+ x: 282.1731915439132,+ y: 876.9418387735697,+ },+ ],+ boundingBox: {+ left: 282.1731915439132,+ top: 791.5420637202442,+ right: 1049.6795153095775,+ bottom: 876.9418387735697,+ },+ },+ {+ id: "block_5_wkxEH8",+ type: "text",+ content:+ "\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.",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.543,+ avgOcrConfidence: 0.985,+ },+ polygon: [+ {+ x: 281.12820952478114,+ y: 893.687589086088,+ },+ {+ x: 1049.8325041610829,+ y: 893.687589086088,+ },+ {+ x: 1049.8325041610829,+ y: 1005.0602061336201,+ },+ {+ x: 281.12820952478114,+ y: 1005.0602061336201,+ },+ ],+ boundingBox: {+ left: 281.12820952478114,+ top: 893.687589086088,+ right: 1049.8325041610829,+ bottom: 1005.0602061336201,+ },+ },+ {+ id: "block_5_vVMF0e",+ type: "section_heading",+ content: "### 3.3 Position-wise Feed-Forward Networks",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.59919443617773,+ y: 1037.180243872162,+ },+ {+ x: 609.3837069768975,+ y: 1037.180243872162,+ },+ {+ x: 609.3837069768975,+ y: 1053.935843790384,+ },+ {+ x: 223.59919443617773,+ y: 1053.935843790384,+ },+ ],+ boundingBox: {+ left: 223.59919443617773,+ top: 1037.180243872162,+ right: 609.3837069768975,+ bottom: 1053.935843790384,+ },+ },+ {+ id: "block_5_WtW3Xc",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.986,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.937928415563,+ y: 1079.1571798109471,+ },+ {+ x: 1049.736412772297,+ y: 1079.1571798109471,+ },+ {+ x: 1049.736412772297,+ y: 1142.9025967246607,+ },+ {+ x: 223.937928415563,+ y: 1142.9025967246607,+ },+ ],+ boundingBox: {+ left: 223.937928415563,+ top: 1079.1571798109471,+ right: 1049.736412772297,+ bottom: 1142.9025967246607,+ },+ },+ {+ id: "block_5_TCB4QK",+ type: "text",+ content: "FFN(x)=max(0,xW1+b1)W2+b2",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Formula",+ minOcrConfidence: 0.668,+ avgOcrConfidence: 0.668,+ },+ polygon: [+ {+ x: 471.6477776965956,+ y: 1184.1576702146604,+ },+ {+ x: 801.1487473536581,+ y: 1184.1576702146604,+ },+ {+ x: 801.1487473536581,+ y: 1206.444581397494,+ },+ {+ x: 471.6477776965956,+ y: 1206.444581397494,+ },+ ],+ boundingBox: {+ left: 471.6477776965956,+ top: 1184.1576702146604,+ right: 801.1487473536581,+ bottom: 1206.444581397494,+ },+ },+ {+ id: "block_5_olGJjx",+ type: "text",+ content: "(2)",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.997,+ avgOcrConfidence: 0.997,+ },+ polygon: [+ {+ x: 1026.9936164800267,+ y: 1185.5856736262042,+ },+ {+ x: 1051.1806237436558,+ y: 1185.5856736262042,+ },+ {+ x: 1051.1806237436558,+ y: 1204.3962422421102,+ },+ {+ x: 1026.9936164800267,+ y: 1204.3962422421102,+ },+ ],+ boundingBox: {+ left: 1026.9936164800267,+ top: 1185.5856736262042,+ right: 1051.1806237436558,+ bottom: 1204.3962422421102,+ },+ },+ {+ id: "block_5_KTjDsL",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.881,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 222.78797957148865,+ y: 1230.1093008858818,+ },+ {+ x: 1052.541145269018,+ y: 1230.1093008858818,+ },+ {+ x: 1052.541145269018,+ y: 1320.3967533541802,+ },+ {+ x: 222.78797957148865,+ y: 1320.3967533541802,+ },+ ],+ boundingBox: {+ left: 222.78797957148865,+ top: 1230.1093008858818,+ right: 1052.541145269018,+ bottom: 1320.3967533541802,+ },+ },+ {+ id: "block_5_Pwzvu2",+ type: "section_heading",+ content: "### 3.4 Embeddings and Softmax",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.997,+ },+ polygon: [+ {+ x: 223.80512822283447,+ y: 1351.0096120045598,+ },+ {+ x: 499.655388045485,+ y: 1351.0096120045598,+ },+ {+ x: 499.655388045485,+ y: 1371.2419333206979,+ },+ {+ x: 223.80512822283447,+ y: 1371.2419333206979,+ },+ ],+ boundingBox: {+ left: 223.80512822283447,+ top: 1351.0096120045598,+ right: 499.655388045485,+ bottom: 1371.2419333206979,+ },+ },+ {+ id: "block_5_6y9ZGB",+ type: "text",+ content:+ "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 -",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.275,+ avgOcrConfidence: 0.983,+ },+ polygon: [+ {+ x: 224.49331770848184,+ y: 1394.318801822519,+ },+ {+ x: 1052.2855327077154,+ y: 1394.318801822519,+ },+ {+ x: 1052.2855327077154,+ y: 1505.8341434450076,+ },+ {+ x: 224.49331770848184,+ y: 1505.8341434450076,+ },+ ],+ boundingBox: {+ left: 224.49331770848184,+ top: 1394.318801822519,+ right: 1052.2855327077154,+ bottom: 1505.8341434450076,+ },+ },+ {+ id: "block_5_o8MKrc",+ type: "page_number",+ content: "5",+ metadata: {+ page: {+ number: 5,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 631.5606054598397,+ y: 1547.4356578740858,+ },+ {+ x: 641.9868998283888,+ y: 1547.4356578740858,+ },+ {+ x: 641.9868998283888,+ y: 1563.1716341864794,+ },+ {+ x: 631.5606054598397,+ y: 1563.1716341864794,+ },+ ],+ boundingBox: {+ left: 631.5606054598397,+ top: 1547.4356578740858,+ right: 641.9868998283888,+ bottom: 1563.1716341864794,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_6_YmUPFZ",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.977,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 222.7798615058843,+ y: 148.2273318355245,+ },+ {+ x: 1048.906618661254,+ y: 148.2273318355245,+ },+ {+ x: 1048.906618661254,+ y: 214.40370720311216,+ },+ {+ x: 222.7798615058843,+ y: 214.40370720311216,+ },+ ],+ boundingBox: {+ left: 222.7798615058843,+ top: 148.2273318355245,+ right: 1048.906618661254,+ bottom: 214.40370720311216,+ },+ },+ {+ id: "block_6_kibLxu",+ type: "table",+ content:+ "| 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) [ ] |",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Table",+ minOcrConfidence: 0.256,+ avgOcrConfidence: 0.856,+ },+ polygon: [+ {+ x: 246.08119491243013,+ y: 233.8958637983279,+ },+ {+ x: 1028.2713006012632,+ y: 233.8958637983279,+ },+ {+ x: 1028.2713006012632,+ y: 389.94297754674926,+ },+ {+ x: 246.08119491243013,+ y: 389.94297754674926,+ },+ ],+ boundingBox: {+ left: 246.08119491243013,+ top: 233.8958637983279,+ right: 1028.2713006012632,+ bottom: 389.94297754674926,+ },+ },+ {+ id: "block_6_tUIpoY",+ type: "section_heading",+ content: "### 3.5 Positional Encoding",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 224.00651778617916,+ y: 445.9595083078944,+ },+ {+ x: 448.20427163674015,+ y: 445.9595083078944,+ },+ {+ x: 448.20427163674015,+ y: 466.69903696390026,+ },+ {+ x: 224.00651778617916,+ y: 466.69903696390026,+ },+ ],+ boundingBox: {+ left: 224.00651778617916,+ top: 445.9595083078944,+ right: 448.20427163674015,+ bottom: 466.69903696390026,+ },+ },+ {+ id: "block_6_mmxGrc",+ type: "text",+ content:+ '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].',+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.912,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.83698512167825,+ y: 487.3354288832586,+ },+ {+ x: 1050.4121766473256,+ y: 487.3354288832586,+ },+ {+ x: 1050.4121766473256,+ y: 620.7750930786133,+ },+ {+ x: 223.83698512167825,+ y: 620.7750930786133,+ },+ ],+ boundingBox: {+ left: 223.83698512167825,+ top: 487.3354288832586,+ right: 1050.4121766473256,+ bottom: 620.7750930786133,+ },+ },+ {+ id: "block_6_NG2aN8",+ type: "text",+ content:+ "In this work, we use sine and cosine functions of different frequencies:",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 224.39521455416715,+ y: 635.0555533789154,+ },+ {+ x: 810.5588871197108,+ y: 635.0555533789154,+ },+ {+ x: 810.5588871197108,+ y: 655.9754529393705,+ },+ {+ x: 224.39521455416715,+ y: 655.9754529393705,+ },+ ],+ boundingBox: {+ left: 224.39521455416715,+ top: 635.0555533789154,+ right: 810.5588871197108,+ bottom: 655.9754529393705,+ },+ },+ {+ id: "block_6_ktOzAP",+ type: "text",+ content:+ "PE(pos,2i) = sin(pos/100002i/dmodel ) PE(pos,2i+1) = cos(pos/100002i/dmodel) )",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Formula",+ minOcrConfidence: 0.646,+ avgOcrConfidence: 0.856,+ },+ polygon: [+ {+ x: 470.62755222738224,+ y: 700.6432727440855,+ },+ {+ x: 804.2361684089159,+ y: 700.6432727440855,+ },+ {+ x: 804.2361684089159,+ y: 763.5065343469606,+ },+ {+ x: 470.62755222738224,+ y: 763.5065343469606,+ },+ ],+ boundingBox: {+ left: 470.62755222738224,+ top: 700.6432727440855,+ right: 804.2361684089159,+ bottom: 763.5065343469606,+ },+ },+ {+ id: "block_6_L0vHNu",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.291,+ avgOcrConfidence: 0.967,+ },+ polygon: [+ {+ x: 223.63699196028884,+ y: 787.3148307800293,+ },+ {+ x: 1050.8335586881985,+ y: 787.3148307800293,+ },+ {+ x: 1050.8335586881985,+ y: 900.202535012611,+ },+ {+ x: 223.63699196028884,+ y: 900.202535012611,+ },+ ],+ boundingBox: {+ left: 223.63699196028884,+ top: 787.3148307800293,+ right: 1050.8335586881985,+ bottom: 900.202535012611,+ },+ },+ {+ id: "block_6_Sai49H",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.868,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 223.15007369883736,+ y: 912.2991767252298,+ },+ {+ x: 1049.522644933993,+ y: 912.2991767252298,+ },+ {+ x: 1049.522644933993,+ y: 1000.5864015736975,+ },+ {+ x: 223.15007369883736,+ y: 1000.5864015736975,+ },+ ],+ boundingBox: {+ left: 223.15007369883736,+ top: 912.2991767252298,+ right: 1049.522644933993,+ bottom: 1000.5864015736975,+ },+ },+ {+ id: "block_6_545oKE",+ type: "section_heading",+ content: "### 4 Why Self-Attention",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.44270274586924,+ y: 1036.185907234823,+ },+ {+ x: 468.14631162768734,+ y: 1036.185907234823,+ },+ {+ x: 468.14631162768734,+ y: 1059.806398205291,+ },+ {+ x: 223.44270274586924,+ y: 1059.806398205291,+ },+ ],+ boundingBox: {+ left: 223.44270274586924,+ top: 1036.185907234823,+ right: 468.14631162768734,+ bottom: 1059.806398205291,+ },+ },+ {+ id: "block_6_rdkytl",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.298,+ avgOcrConfidence: 0.936,+ },+ polygon: [+ {+ x: 222.55295802206888,+ y: 1087.3066867455505,+ },+ {+ x: 1052.7677884067061,+ y: 1087.3066867455505,+ },+ {+ x: 1052.7677884067061,+ y: 1195.3768446499244,+ },+ {+ x: 222.55295802206888,+ y: 1195.3768446499244,+ },+ ],+ boundingBox: {+ left: 222.55295802206888,+ top: 1087.3066867455505,+ right: 1052.7677884067061,+ bottom: 1195.3768446499244,+ },+ },+ {+ id: "block_6_y2UJTk",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.43593374656064,+ y: 1212.4905345601246,+ },+ {+ x: 1048.7435946499345,+ y: 1212.4905345601246,+ },+ {+ x: 1048.7435946499345,+ y: 1255.7911059730932,+ },+ {+ x: 223.43593374656064,+ y: 1255.7911059730932,+ },+ ],+ boundingBox: {+ left: 223.43593374656064,+ top: 1212.4905345601246,+ right: 1048.7435946499345,+ bottom: 1255.7911059730932,+ },+ },+ {+ id: "block_6_OGHshO",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.983,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 222.87737296445525,+ y: 1268.8657945905413,+ },+ {+ x: 1049.749950770914,+ y: 1268.8657945905413,+ },+ {+ x: 1049.749950770914,+ y: 1426.1352065236945,+ },+ {+ x: 222.87737296445525,+ y: 1426.1352065236945,+ },+ ],+ boundingBox: {+ left: 222.87737296445525,+ top: 1268.8657945905413,+ right: 1049.749950770914,+ bottom: 1426.1352065236945,+ },+ },+ {+ id: "block_6_zgN3wO",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.963,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 223.4352473794979,+ y: 1439.235182109632,+ },+ {+ x: 1051.6017217705719,+ y: 1439.235182109632,+ },+ {+ x: 1051.6017217705719,+ y: 1506.1062388025728,+ },+ {+ x: 223.4352473794979,+ y: 1506.1062388025728,+ },+ ],+ boundingBox: {+ left: 223.4352473794979,+ top: 1439.235182109632,+ right: 1051.6017217705719,+ bottom: 1506.1062388025728,+ },+ },+ {+ id: "block_6_aNgpKT",+ type: "page_number",+ content: "6",+ metadata: {+ page: {+ number: 6,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.993,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 631.7702550957673,+ y: 1548.2886905526757,+ },+ {+ x: 642.7105200551722,+ y: 1548.2886905526757,+ },+ {+ x: 642.7105200551722,+ y: 1563.5418467700931,+ },+ {+ x: 631.7702550957673,+ y: 1563.5418467700931,+ },+ ],+ boundingBox: {+ left: 631.7702550957673,+ top: 1548.2886905526757,+ right: 642.7105200551722,+ bottom: 1563.5418467700931,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_7_u723hy",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.909,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 223.89144479793353,+ y: 155.39061148363845,+ },+ {+ x: 1050.0338700565978,+ y: 155.39061148363845,+ },+ {+ x: 1050.0338700565978,+ y: 290.11272512163436,+ },+ {+ x: 223.89144479793353,+ y: 290.11272512163436,+ },+ ],+ boundingBox: {+ left: 223.89144479793353,+ top: 155.39061148363845,+ right: 1050.0338700565978,+ bottom: 290.11272512163436,+ },+ },+ {+ id: "block_7_SLgoxa",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.525,+ avgOcrConfidence: 0.977,+ },+ polygon: [+ {+ x: 223.84822734080961,+ y: 303.4973448416344,+ },+ {+ x: 1051.7048188369638,+ y: 303.4973448416344,+ },+ {+ x: 1051.7048188369638,+ y: 482.7421505003047,+ },+ {+ x: 223.84822734080961,+ y: 482.7421505003047,+ },+ ],+ boundingBox: {+ left: 223.84822734080961,+ top: 303.4973448416344,+ right: 1051.7048188369638,+ bottom: 482.7421505003047,+ },+ },+ {+ id: "block_7_lGN5L0",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.94,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.7218884656029,+ y: 496.4417208334557,+ },+ {+ x: 1049.5183847246378,+ y: 496.4417208334557,+ },+ {+ x: 1049.5183847246378,+ y: 581.3287481437052,+ },+ {+ x: 223.7218884656029,+ y: 581.3287481437052,+ },+ ],+ boundingBox: {+ left: 223.7218884656029,+ top: 496.4417208334557,+ right: 1049.5183847246378,+ bottom: 581.3287481437052,+ },+ },+ {+ id: "block_7_FOtl5B",+ type: "heading",+ content: "# 5 Training",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Heading",+ minOcrConfidence: 0.989,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 224.4122553915873,+ y: 625.3390120599503,+ },+ {+ x: 354.91415984439146,+ y: 625.3390120599503,+ },+ {+ x: 354.91415984439146,+ y: 649.7166914688913,+ },+ {+ x: 224.4122553915873,+ y: 649.7166914688913,+ },+ ],+ boundingBox: {+ left: 224.4122553915873,+ top: 625.3390120599503,+ right: 354.91415984439146,+ bottom: 649.7166914688913,+ },+ },+ {+ id: "block_7_3jYBCf",+ type: "text",+ content: "This section describes the training regime for our models.",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 222.4527957665659,+ y: 679.1303132709704,+ },+ {+ x: 701.988161741382,+ y: 679.1303132709704,+ },+ {+ x: 701.988161741382,+ y: 699.7081758025894,+ },+ {+ x: 222.4527957665659,+ y: 699.7081758025894,+ },+ ],+ boundingBox: {+ left: 222.4527957665659,+ top: 679.1303132709704,+ right: 701.988161741382,+ bottom: 699.7081758025894,+ },+ },+ {+ id: "block_7_PIafds",+ type: "section_heading",+ content: "### 5.1 Training Data and Batching",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.68002007477475,+ y: 735.0401794318866,+ },+ {+ x: 519.6398407873446,+ y: 735.0401794318866,+ },+ {+ x: 519.6398407873446,+ y: 755.8565634247055,+ },+ {+ x: 223.68002007477475,+ y: 755.8565634247055,+ },+ ],+ boundingBox: {+ left: 223.68002007477475,+ top: 735.0401794318866,+ right: 519.6398407873446,+ bottom: 755.8565634247055,+ },+ },+ {+ id: "block_7_8RhsHH",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.911,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.70165247116648,+ y: 778.8621643467953,+ },+ {+ x: 1052.1871692072737,+ y: 778.8621643467953,+ },+ {+ x: 1052.1871692072737,+ y: 935.23512009929,+ },+ {+ x: 223.70165247116648,+ y: 935.23512009929,+ },+ ],+ boundingBox: {+ left: 223.70165247116648,+ top: 778.8621643467953,+ right: 1052.1871692072737,+ bottom: 935.23512009929,+ },+ },+ {+ id: "block_7_2fOgoW",+ type: "section_heading",+ content: "### 5.2 Hardware and Schedule",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.994,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 223.9209349138023,+ y: 971.4598863071069,+ },+ {+ x: 484.7486314982394,+ y: 971.4598863071069,+ },+ {+ x: 484.7486314982394,+ y: 987.6652342143811,+ },+ {+ x: 223.9209349138023,+ y: 987.6652342143811,+ },+ ],+ boundingBox: {+ left: 223.9209349138023,+ top: 971.4598863071069,+ right: 484.7486314982394,+ bottom: 987.6652342143811,+ },+ },+ {+ id: "block_7_7vykWe",+ type: "text",+ content:+ "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).",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.961,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 223.2459757449853,+ y: 1014.9955223485043,+ },+ {+ x: 1049.3973947789548,+ y: 1014.9955223485043,+ },+ {+ x: 1049.3973947789548,+ y: 1126.7015106660083,+ },+ {+ x: 223.2459757449853,+ y: 1126.7015106660083,+ },+ ],+ boundingBox: {+ left: 223.2459757449853,+ top: 1014.9955223485043,+ right: 1049.3973947789548,+ bottom: 1126.7015106660083,+ },+ },+ {+ id: "block_7_Xjy6qb",+ type: "section_heading",+ content: "### 5.3 Optimizer",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.994,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.84361211400832,+ y: 1161.1210525053784,+ },+ {+ x: 361.9454223744191,+ y: 1161.1210525053784,+ },+ {+ x: 361.9454223744191,+ y: 1181.9203891037102,+ },+ {+ x: 223.84361211400832,+ y: 1181.9203891037102,+ },+ ],+ boundingBox: {+ left: 223.84361211400832,+ top: 1161.1210525053784,+ right: 361.9454223744191,+ bottom: 1181.9203891037102,+ },+ },+ {+ id: "block_7_uZS3FC",+ type: "text",+ content:+ "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:",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.472,+ avgOcrConfidence: 0.947,+ },+ polygon: [+ {+ x: 223.18536243299496,+ y: 1203.7906809068263,+ },+ {+ x: 1049.5936484232436,+ y: 1203.7906809068263,+ },+ {+ x: 1049.5936484232436,+ y: 1249.0720648514596,+ },+ {+ x: 223.18536243299496,+ y: 1249.0720648514596,+ },+ ],+ boundingBox: {+ left: 223.18536243299496,+ top: 1203.7906809068263,+ right: 1049.5936484232436,+ bottom: 1249.0720648514596,+ },+ },+ {+ id: "block_7_qvJczg",+ type: "text",+ content:+ "lrate = dmodel . min(step_num-0.5, step_num . warmup_steps-1.5)",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Formula",+ minOcrConfidence: 0.563,+ avgOcrConfidence: 0.786,+ },+ polygon: [+ {+ x: 338.51696905428474,+ y: 1286.921258338412,+ },+ {+ x: 933.735361586522,+ y: 1286.921258338412,+ },+ {+ x: 933.735361586522,+ y: 1314.0637410099346,+ },+ {+ x: 338.51696905428474,+ y: 1314.0637410099346,+ },+ ],+ boundingBox: {+ left: 338.51696905428474,+ top: 1286.921258338412,+ right: 933.735361586522,+ bottom: 1314.0637410099346,+ },+ },+ {+ id: "block_7_ZRnl1T",+ type: "text",+ content: "(3)",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 1026.6387883764114,+ y: 1291.0368781986094,+ },+ {+ x: 1051.2767151324417,+ y: 1291.0368781986094,+ },+ {+ x: 1051.2767151324417,+ y: 1311.080825805664,+ },+ {+ x: 1026.6387883764114,+ y: 1311.080825805664,+ },+ ],+ boundingBox: {+ left: 1026.6387883764114,+ top: 1291.0368781986094,+ right: 1051.2767151324417,+ bottom: 1311.080825805664,+ },+ },+ {+ id: "block_7_M71nL9",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.916,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 222.72840764400732,+ y: 1340.2761936044335,+ },+ {+ x: 1052.0266066502481,+ y: 1340.2761936044335,+ },+ {+ x: 1052.0266066502481,+ y: 1406.6737115616188,+ },+ {+ x: 222.72840764400732,+ y: 1406.6737115616188,+ },+ ],+ boundingBox: {+ left: 222.72840764400732,+ top: 1340.2761936044335,+ right: 1052.0266066502481,+ bottom: 1406.6737115616188,+ },+ },+ {+ id: "block_7_ACakMa",+ type: "section_heading",+ content: "### 5.4 Regularization",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.993,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 223.81116351942077,+ y: 1441.41800626597,+ },+ {+ x: 402.1996435457773,+ y: 1441.41800626597,+ },+ {+ x: 402.1996435457773,+ y: 1461.9926013803124,+ },+ {+ x: 223.81116351942077,+ y: 1461.9926013803124,+ },+ ],+ boundingBox: {+ left: 223.81116351942077,+ top: 1441.41800626597,+ right: 402.1996435457773,+ bottom: 1461.9926013803124,+ },+ },+ {+ id: "block_7_rR8JeL",+ type: "text",+ content: "We employ three types of regularization during training:",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 222.88627206844134,+ y: 1484.7892296583134,+ },+ {+ x: 690.987449144795,+ y: 1484.7892296583134,+ },+ {+ x: 690.987449144795,+ y: 1505.950728681751,+ },+ {+ x: 222.88627206844134,+ y: 1505.950728681751,+ },+ ],+ boundingBox: {+ left: 222.88627206844134,+ top: 1484.7892296583134,+ right: 690.987449144795,+ bottom: 1505.950728681751,+ },+ },+ {+ id: "block_7_I7j7Uy",+ type: "page_number",+ content: "7",+ metadata: {+ page: {+ number: 7,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.996,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 631.8865114755004,+ y: 1547.4189893105872,+ },+ {+ x: 642.4512153124288,+ y: 1547.4189893105872,+ },+ {+ x: 642.4512153124288,+ y: 1562.541448836936,+ },+ {+ x: 631.8865114755004,+ y: 1562.541448836936,+ },+ ],+ boundingBox: {+ left: 631.8865114755004,+ top: 1547.4189893105872,+ right: 642.4512153124288,+ bottom: 1562.541448836936,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_8_8rtbBp",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.963,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 222.40285664579295,+ y: 148.11078211418666,+ },+ {+ x: 1048.695596291201,+ y: 148.11078211418666,+ },+ {+ x: 1048.695596291201,+ y: 191.8824890538266,+ },+ {+ x: 222.40285664579295,+ y: 191.8824890538266,+ },+ ],+ boundingBox: {+ left: 222.40285664579295,+ top: 148.11078211418666,+ right: 1048.695596291201,+ bottom: 191.8824890538266,+ },+ },+ {+ id: "block_8_M3V7h9",+ type: "table",+ content:+ "| 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 | |",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Table",+ minOcrConfidence: 0.141,+ avgOcrConfidence: 0.893,+ },+ polygon: [+ {+ x: 271.150136516042,+ y: 195.3426247575229,+ },+ {+ x: 1004.1704442379248,+ y: 195.3426247575229,+ },+ {+ x: 1004.1704442379248,+ y: 508.6132290201976,+ },+ {+ x: 271.150136516042,+ y: 508.6132290201976,+ },+ ],+ boundingBox: {+ left: 271.150136516042,+ top: 195.3426247575229,+ right: 1004.1704442379248,+ bottom: 508.6132290201976,+ },+ },+ {+ id: "block_8_Wl0xmI",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.893,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 223.9333605244212,+ y: 569.1121117154458,+ },+ {+ x: 1051.605887308608,+ y: 569.1121117154458,+ },+ {+ x: 1051.605887308608,+ y: 660.0886577520155,+ },+ {+ x: 223.9333605244212,+ y: 660.0886577520155,+ },+ ],+ boundingBox: {+ left: 223.9333605244212,+ top: 569.1121117154458,+ right: 1051.605887308608,+ bottom: 660.0886577520155,+ },+ },+ {+ id: "block_8_CtqTnb",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.518,+ avgOcrConfidence: 0.977,+ },+ polygon: [+ {+ x: 223.52019122047145,+ y: 690.790115499855,+ },+ {+ x: 1049.6801780088103,+ y: 690.790115499855,+ },+ {+ x: 1049.6801780088103,+ y: 734.1354363233523,+ },+ {+ x: 223.52019122047145,+ y: 734.1354363233523,+ },+ ],+ boundingBox: {+ left: 223.52019122047145,+ top: 690.790115499855,+ right: 1049.6801780088103,+ bottom: 734.1354363233523,+ },+ },+ {+ id: "block_8_KA1kZT",+ type: "heading",+ content: "# 6 Results",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Heading",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 224.16400352533717,+ y: 774.585115131579,+ },+ {+ x: 339.42863018843383,+ y: 774.585115131579,+ },+ {+ x: 339.42863018843383,+ y: 793.809935433524,+ },+ {+ x: 224.16400352533717,+ y: 793.809935433524,+ },+ ],+ boundingBox: {+ left: 224.16400352533717,+ top: 774.585115131579,+ right: 339.42863018843383,+ bottom: 793.809935433524,+ },+ },+ {+ id: "block_8_LYkEL8",+ type: "section_heading",+ content: "### 6.1 Machine Translation",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.994,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 224.2968510537252,+ y: 828.3471990026029,+ },+ {+ x: 455.2866330111984,+ y: 828.3471990026029,+ },+ {+ x: 455.2866330111984,+ y: 844.3720339438072,+ },+ {+ x: 224.2968510537252,+ y: 844.3720339438072,+ },+ ],+ boundingBox: {+ left: 224.2968510537252,+ top: 828.3471990026029,+ right: 455.2866330111984,+ bottom: 844.3720339438072,+ },+ },+ {+ id: "block_8_UnI1Ea",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.973,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.56291165317063,+ y: 872.0711140453367,+ },+ {+ x: 1050.5385628581919,+ y: 872.0711140453367,+ },+ {+ x: 1050.5385628581919,+ y: 1006.0390107004266,+ },+ {+ x: 223.56291165317063,+ y: 1006.0390107004266,+ },+ ],+ boundingBox: {+ left: 223.56291165317063,+ top: 872.0711140453367,+ right: 1050.5385628581919,+ bottom: 1006.0390107004266,+ },+ },+ {+ id: "block_8_pkBARc",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.945,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 224.05139199138557,+ y: 1019.1086798072756,+ },+ {+ x: 1052.2523977460653,+ y: 1019.1086798072756,+ },+ {+ x: 1052.2523977460653,+ y: 1109.5784446888401,+ },+ {+ x: 224.05139199138557,+ y: 1109.5784446888401,+ },+ ],+ boundingBox: {+ left: 224.05139199138557,+ top: 1019.1086798072756,+ right: 1052.2523977460653,+ bottom: 1109.5784446888401,+ },+ },+ {+ id: "block_8_vKs7Yg",+ type: "text",+ content:+ "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].",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.099,+ avgOcrConfidence: 0.983,+ },+ polygon: [+ {+ x: 223.50279536560504,+ y: 1122.2645474197273,+ },+ {+ x: 1050.043905216412,+ y: 1122.2645474197273,+ },+ {+ x: 1050.043905216412,+ y: 1233.5787297872673,+ },+ {+ x: 223.50279536560504,+ y: 1233.5787297872673,+ },+ ],+ boundingBox: {+ left: 223.50279536560504,+ top: 1122.2645474197273,+ right: 1050.043905216412,+ bottom: 1233.5787297872673,+ },+ },+ {+ id: "block_8_42PSVl",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.975,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 222.3879459130503,+ y: 1247.2785842436597,+ },+ {+ x: 1049.63284234931,+ y: 1247.2785842436597,+ },+ {+ x: 1049.63284234931,+ y: 1336.1913537620603,+ },+ {+ x: 222.3879459130503,+ y: 1336.1913537620603,+ },+ ],+ boundingBox: {+ left: 222.3879459130503,+ top: 1247.2785842436597,+ right: 1049.63284234931,+ bottom: 1336.1913537620603,+ },+ },+ {+ id: "block_8_pDx0nB",+ type: "section_heading",+ content: "### 6.2 Model Variations",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 224.05955739264942,+ y: 1370.9984397027727,+ },+ {+ x: 424.93188398597886,+ y: 1370.9984397027727,+ },+ {+ x: 424.93188398597886,+ y: 1387.4261614003576,+ },+ {+ x: 224.05955739264942,+ y: 1387.4261614003576,+ },+ ],+ boundingBox: {+ left: 224.05955739264942,+ top: 1370.9984397027727,+ right: 424.93188398597886,+ bottom: 1387.4261614003576,+ },+ },+ {+ id: "block_8_XCLvsN",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 222.6526705888066,+ y: 1413.835037862448,+ },+ {+ x: 1049.9819901737853,+ y: 1413.835037862448,+ },+ {+ x: 1049.9819901737853,+ y: 1458.0598621798638,+ },+ {+ x: 222.6526705888066,+ y: 1458.0598621798638,+ },+ ],+ boundingBox: {+ left: 222.6526705888066,+ top: 1413.835037862448,+ right: 1049.9819901737853,+ bottom: 1458.0598621798638,+ },+ },+ {+ id: "block_8_6e9VRc",+ type: "text",+ content:+ "5We used values of 2.8, 3.7, 6.0 and 9.5 TFLOPS for K80, K40, M40 and P100, respectively.",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.976,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 249.0640041601919,+ y: 1482.8447849015545,+ },+ {+ x: 944.2274051861172,+ y: 1482.8447849015545,+ },+ {+ x: 944.2274051861172,+ y: 1505.4603319670025,+ },+ {+ x: 249.0640041601919,+ y: 1505.4603319670025,+ },+ ],+ boundingBox: {+ left: 249.0640041601919,+ top: 1482.8447849015545,+ right: 944.2274051861172,+ bottom: 1505.4603319670025,+ },+ },+ {+ id: "block_8_HHxEh9",+ type: "page_number",+ content: "8",+ metadata: {+ page: {+ number: 8,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.996,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 631.7743259624843,+ y: 1547.954182789738,+ },+ {+ x: 642.6607229413778,+ y: 1547.954182789738,+ },+ {+ x: 642.6607229413778,+ y: 1563.2957013352473,+ },+ {+ x: 631.7743259624843,+ y: 1563.2957013352473,+ },+ ],+ boundingBox: {+ left: 631.7743259624843,+ top: 1547.954182789738,+ right: 642.6607229413778,+ bottom: 1563.2957013352473,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_9_2CG18E",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.99,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 222.6654748847015,+ y: 147.86792777355453,+ },+ {+ x: 1049.6700481776775,+ y: 147.86792777355453,+ },+ {+ x: 1049.6700481776775,+ y: 237.19010704442076,+ },+ {+ x: 222.6654748847015,+ y: 237.19010704442076,+ },+ ],+ boundingBox: {+ left: 222.6654748847015,+ top: 147.86792777355453,+ right: 1049.6700481776775,+ bottom: 237.19010704442076,+ },+ },+ {+ id: "block_9_0WToWH",+ type: "table",+ content:+ "| | 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 |",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Table",+ minOcrConfidence: 0.612,+ avgOcrConfidence: 0.986,+ },+ polygon: [+ {+ x: 224.84461930546448,+ y: 268.65403318763674,+ },+ {+ x: 1060.6742636130673,+ y: 268.65403318763674,+ },+ {+ x: 1060.6742636130673,+ y: 801.2216690178204,+ },+ {+ x: 224.84461930546448,+ y: 801.2216690178204,+ },+ ],+ boundingBox: {+ left: 224.84461930546448,+ top: 268.65403318763674,+ right: 1060.6742636130673,+ bottom: 801.2216690178204,+ },+ },+ {+ id: "block_9_p8WB9c",+ type: "text",+ content:+ "development set, newstest2013. We used beam search as described in the previous section, but no checkpoint averaging. We present these results in Table 3.",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.989,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 224.42882287241247,+ y: 862.6040329323675,+ },+ {+ x: 1049.5265264580719,+ y: 862.6040329323675,+ },+ {+ x: 1049.5265264580719,+ y: 905.6541023541213,+ },+ {+ x: 224.42882287241247,+ y: 905.6541023541213,+ },+ ],+ boundingBox: {+ left: 224.42882287241247,+ top: 862.6040329323675,+ right: 1049.5265264580719,+ bottom: 905.6541023541213,+ },+ },+ {+ id: "block_9_XvsIA2",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.967,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 224.23600106343736,+ y: 918.8913094656807,+ },+ {+ x: 1052.034559041044,+ y: 918.8913094656807,+ },+ {+ x: 1052.034559041044,+ y: 986.1080494357232,+ },+ {+ x: 224.23600106343736,+ y: 986.1080494357232,+ },+ ],+ boundingBox: {+ left: 224.23600106343736,+ top: 918.8913094656807,+ right: 1052.034559041044,+ bottom: 986.1080494357232,+ },+ },+ {+ id: "block_9_lFHLbG",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.881,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 224.0262804240206,+ y: 998.9746651326803,+ },+ {+ x: 1052.338643317675,+ y: 998.9746651326803,+ },+ {+ x: 1052.338643317675,+ y: 1130.1984048140678,+ },+ {+ x: 224.0262804240206,+ y: 1130.1984048140678,+ },+ ],+ boundingBox: {+ left: 224.0262804240206,+ top: 998.9746651326803,+ right: 1052.338643317675,+ bottom: 1130.1984048140678,+ },+ },+ {+ id: "block_9_nnE2Kn",+ type: "section_heading",+ content: "### 6.3 English Constituency Parsing",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.994,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 224.00199723069687,+ y: 1168.0604785546325,+ },+ {+ x: 533.1579584274849,+ y: 1168.0604785546325,+ },+ {+ x: 533.1579584274849,+ y: 1188.5333575485345,+ },+ {+ x: 224.00199723069687,+ y: 1188.5333575485345,+ },+ ],+ boundingBox: {+ left: 224.00199723069687,+ top: 1168.0604785546325,+ right: 533.1579584274849,+ bottom: 1188.5333575485345,+ },+ },+ {+ id: "block_9_UvLm1J",+ type: "text",+ content:+ "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].",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.963,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.0787388599702,+ y: 1212.099580979885,+ },+ {+ x: 1049.9080518736457,+ y: 1212.099580979885,+ },+ {+ x: 1049.9080518736457,+ y: 1300.6617424183323,+ },+ {+ x: 223.0787388599702,+ y: 1300.6617424183323,+ },+ ],+ boundingBox: {+ left: 223.0787388599702,+ top: 1212.099580979885,+ right: 1049.9080518736457,+ bottom: 1300.6617424183323,+ },+ },+ {+ id: "block_9_nmNLPf",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.913,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 223.08401678600453,+ y: 1314.1105266370273,+ },+ {+ x: 1051.1732393807738,+ y: 1314.1105266370273,+ },+ {+ x: 1051.1732393807738,+ y: 1425.9921031177494,+ },+ {+ x: 223.08401678600453,+ y: 1425.9921031177494,+ },+ ],+ boundingBox: {+ left: 223.08401678600453,+ top: 1314.1105266370273,+ right: 1051.1732393807738,+ bottom: 1425.9921031177494,+ },+ },+ {+ id: "block_9_kQhH3x",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.1762739863709,+ y: 1439.0945411051127,+ },+ {+ x: 1050.7557388639798,+ y: 1439.0945411051127,+ },+ {+ x: 1050.7557388639798,+ y: 1505.8386894168711,+ },+ {+ x: 223.1762739863709,+ y: 1505.8386894168711,+ },+ ],+ boundingBox: {+ left: 223.1762739863709,+ top: 1439.0945411051127,+ right: 1050.7557388639798,+ bottom: 1505.8386894168711,+ },+ },+ {+ id: "block_9_C4QuNg",+ type: "page_number",+ content: "9",+ metadata: {+ page: {+ number: 9,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.993,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 631.6446262554531,+ y: 1547.2787271370566,+ },+ {+ x: 642.3550765879834,+ y: 1547.2787271370566,+ },+ {+ x: 642.3550765879834,+ y: 1562.906831325445,+ },+ {+ x: 631.6446262554531,+ y: 1562.906831325445,+ },+ ],+ boundingBox: {+ left: 631.6446262554531,+ top: 1547.2787271370566,+ right: 642.3550765879834,+ bottom: 1562.906831325445,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_10_Whfo1k",+ type: "text",+ content:+ "Table 4: The Transformer generalizes well to English constituency parsing (Results are on Section 23 of WSJ)",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.988,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 222.60232911492787,+ y: 147.913837353986,+ },+ {+ x: 1049.0453121435903,+ y: 147.913837353986,+ },+ {+ x: 1049.0453121435903,+ y: 190.50408882485297,+ },+ {+ x: 222.60232911492787,+ y: 190.50408882485297,+ },+ ],+ boundingBox: {+ left: 222.60232911492787,+ top: 147.913837353986,+ right: 1049.0453121435903,+ bottom: 190.50408882485297,+ },+ },+ {+ id: "block_10_Oq0boE",+ type: "table",+ content:+ "| 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 |",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Table",+ minOcrConfidence: 0.926,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 300.48226962124346,+ y: 193.81453893417702,+ },+ {+ x: 974.1206315312072,+ y: 193.81453893417702,+ },+ {+ x: 974.1206315312072,+ y: 493.68785631567016,+ },+ {+ x: 300.48226962124346,+ y: 493.68785631567016,+ },+ ],+ boundingBox: {+ left: 300.48226962124346,+ top: 193.81453893417702,+ right: 974.1206315312072,+ bottom: 493.68785631567016,+ },+ },+ {+ id: "block_10_wSUPzw",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.117,+ avgOcrConfidence: 0.964,+ },+ polygon: [+ {+ x: 223.84354111051908,+ y: 546.3992524398001,+ },+ {+ x: 1049.2353174808252,+ y: 546.3992524398001,+ },+ {+ x: 1049.2353174808252,+ y: 589.787902057619,+ },+ {+ x: 223.84354111051908,+ y: 589.787902057619,+ },+ ],+ boundingBox: {+ left: 223.84354111051908,+ top: 546.3992524398001,+ right: 1049.2353174808252,+ bottom: 589.787902057619,+ },+ },+ {+ id: "block_10_KdYXbX",+ type: "text",+ content:+ "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].",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.917,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 224.34470740548016,+ y: 603.5821801379211,+ },+ {+ x: 1052.1757139776746,+ y: 603.5821801379211,+ },+ {+ x: 1052.1757139776746,+ y: 667.7562916691143,+ },+ {+ x: 224.34470740548016,+ y: 667.7562916691143,+ },+ ],+ boundingBox: {+ left: 224.34470740548016,+ top: 603.5821801379211,+ right: 1052.1757139776746,+ bottom: 667.7562916691143,+ },+ },+ {+ id: "block_10_spL6f1",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.907,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 223.93137242672216,+ y: 683.4819921909419,+ },+ {+ x: 1052.021589070341,+ y: 683.4819921909419,+ },+ {+ x: 1052.021589070341,+ y: 725.8283830513632,+ },+ {+ x: 223.93137242672216,+ y: 725.8283830513632,+ },+ ],+ boundingBox: {+ left: 223.93137242672216,+ top: 683.4819921909419,+ right: 1052.021589070341,+ bottom: 725.8283830513632,+ },+ },+ {+ id: "block_10_FpxS4M",+ type: "section_heading",+ content: "### 7 Conclusion",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.993,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.87968188654767,+ y: 760.911873552136,+ },+ {+ x: 380.37754949862074,+ y: 760.911873552136,+ },+ {+ x: 380.37754949862074,+ y: 780.8896204439321,+ },+ {+ x: 223.87968188654767,+ y: 780.8896204439321,+ },+ ],+ boundingBox: {+ left: 223.87968188654767,+ top: 760.911873552136,+ right: 380.37754949862074,+ bottom: 780.8896204439321,+ },+ },+ {+ id: "block_10_06Cxhy",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.989,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.7800876589587,+ y: 811.1846398948727,+ },+ {+ x: 1049.4503160462762,+ y: 811.1846398948727,+ },+ {+ x: 1049.4503160462762,+ y: 872.951422555106,+ },+ {+ x: 223.7800876589587,+ y: 872.951422555106,+ },+ ],+ boundingBox: {+ left: 223.7800876589587,+ top: 811.1846398948727,+ right: 1049.4503160462762,+ bottom: 872.951422555106,+ },+ },+ {+ id: "block_10_4PqBx5",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.989,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 223.91187013500797,+ y: 890.9364237390963,+ },+ {+ x: 1049.8108244290318,+ y: 890.9364237390963,+ },+ {+ x: 1049.8108244290318,+ y: 980.2941302536126,+ },+ {+ x: 223.91187013500797,+ y: 980.2941302536126,+ },+ ],+ boundingBox: {+ left: 223.91187013500797,+ top: 890.9364237390963,+ right: 1049.8108244290318,+ bottom: 980.2941302536126,+ },+ },+ {+ id: "block_10_9Aa2OZ",+ type: "text",+ content:+ "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.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.985,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 223.4691397117002,+ y: 993.4156992059005,+ },+ {+ x: 1051.09778633953,+ y: 993.4156992059005,+ },+ {+ x: 1051.09778633953,+ y: 1081.8706514745727,+ },+ {+ x: 223.4691397117002,+ y: 1081.8706514745727,+ },+ ],+ boundingBox: {+ left: 223.4691397117002,+ top: 993.4156992059005,+ right: 1051.09778633953,+ bottom: 1081.8706514745727,+ },+ },+ {+ id: "block_10_eXUU9v",+ type: "text",+ content:+ "The code we used to train and evaluate our models is available at https://github.com/ tensorflow/tensor2tensor.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.94,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 222.4288912585182,+ y: 1095.2490678371344,+ },+ {+ x: 1050.6089983195284,+ y: 1095.2490678371344,+ },+ {+ x: 1050.6089983195284,+ y: 1136.225321719521,+ },+ {+ x: 222.4288912585182,+ y: 1136.225321719521,+ },+ ],+ boundingBox: {+ left: 222.4288912585182,+ top: 1095.2490678371344,+ right: 1050.6089983195284,+ bottom: 1136.225321719521,+ },+ },+ {+ id: "block_10_HbnFiy",+ type: "text",+ content:+ "Acknowledgements We are grateful to Nal Kalchbrenner and Stephan Gouws for their fruitful comments, corrections and inspiration.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Text",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.996,+ },+ polygon: [+ {+ x: 223.74068072242457,+ y: 1165.530171673997,+ },+ {+ x: 1049.9162882783987,+ y: 1165.530171673997,+ },+ {+ x: 1049.9162882783987,+ y: 1209.6124608319503,+ },+ {+ x: 223.74068072242457,+ y: 1209.6124608319503,+ },+ ],+ boundingBox: {+ left: 223.74068072242457,+ top: 1165.530171673997,+ right: 1049.9162882783987,+ bottom: 1209.6124608319503,+ },+ },+ {+ id: "block_10_FqHFgA",+ type: "section_heading",+ content: "### References",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Subheading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 224.3401158465086,+ y: 1243.4205694557131,+ },+ {+ x: 340.41243086766156,+ y: 1243.4205694557131,+ },+ {+ x: 340.41243086766156,+ y: 1263.1433630921786,+ },+ {+ x: 224.3401158465086,+ y: 1263.1433630921786,+ },+ ],+ boundingBox: {+ left: 224.3401158465086,+ top: 1243.4205694557131,+ right: 340.41243086766156,+ bottom: 1263.1433630921786,+ },+ },+ {+ id: "block_10_PnBCYC",+ type: "text",+ content:+ "[1] Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint arXiv: 1607.06450, 2016.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.913,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 234.62492392881074,+ y: 1281.5349446346884,+ },+ {+ x: 1049.520940850251,+ y: 1281.5349446346884,+ },+ {+ x: 1049.520940850251,+ y: 1323.6168167573169,+ },+ {+ x: 234.62492392881074,+ y: 1323.6168167573169,+ },+ ],+ boundingBox: {+ left: 234.62492392881074,+ top: 1281.5349446346884,+ right: 1049.520940850251,+ bottom: 1323.6168167573169,+ },+ },+ {+ id: "block_10_sUAYRJ",+ type: "text",+ content:+ "[2] Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly learning to align and translate. CoRR, abs/1409.0473, 2014.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.913,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 233.7351792050104,+ y: 1342.1247941210754,+ },+ {+ x: 1048.5688313950586,+ y: 1342.1247941210754,+ },+ {+ x: 1048.5688313950586,+ y: 1385.6842018070079,+ },+ {+ x: 233.7351792050104,+ y: 1385.6842018070079,+ },+ ],+ boundingBox: {+ left: 233.7351792050104,+ top: 1342.1247941210754,+ right: 1048.5688313950586,+ bottom: 1385.6842018070079,+ },+ },+ {+ id: "block_10_cYNyCb",+ type: "text",+ content:+ "[3] Denny Britz, Anna Goldie, Minh-Thang Luong, and Quoc V. Le. Massive exploration of neural machine translation architectures. CoRR, abs/1703.03906, 2017.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.914,+ avgOcrConfidence: 0.989,+ },+ polygon: [+ {+ x: 234.47555625525703,+ y: 1401.96474766552,+ },+ {+ x: 1050.0915248898693,+ y: 1401.96474766552,+ },+ {+ x: 1050.0915248898693,+ y: 1443.4021335687853,+ },+ {+ x: 234.47555625525703,+ y: 1443.4021335687853,+ },+ ],+ boundingBox: {+ left: 234.47555625525703,+ top: 1401.96474766552,+ right: 1050.0915248898693,+ bottom: 1443.4021335687853,+ },+ },+ {+ id: "block_10_akeHB3",+ type: "text",+ content:+ "[4] Jianpeng Cheng, Li Dong, and Mirella Lapata. Long short-term memory-networks for machine reading. arXiv preprint arXiv: 1601.06733, 2016.",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.91,+ avgOcrConfidence: 0.989,+ },+ polygon: [+ {+ x: 235.1935672063897,+ y: 1461.8473196961825,+ },+ {+ x: 1049.3358584216041,+ y: 1461.8473196961825,+ },+ {+ x: 1049.3358584216041,+ y: 1505.7106445427228,+ },+ {+ x: 235.1935672063897,+ y: 1505.7106445427228,+ },+ ],+ boundingBox: {+ left: 235.1935672063897,+ top: 1461.8473196961825,+ right: 1049.3358584216041,+ bottom: 1505.7106445427228,+ },+ },+ {+ id: "block_10_sJYSgt",+ type: "page_number",+ content: "10",+ metadata: {+ page: {+ number: 10,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.999,+ avgOcrConfidence: 0.999,+ },+ polygon: [+ {+ x: 628.4902252420022,+ y: 1547.7831405983832,+ },+ {+ x: 647.7796484954166,+ y: 1547.7831405983832,+ },+ {+ x: 647.7796484954166,+ y: 1563.3856736950409,+ },+ {+ x: 628.4902252420022,+ y: 1563.3856736950409,+ },+ ],+ boundingBox: {+ left: 628.4902252420022,+ top: 1547.7831405983832,+ right: 647.7796484954166,+ bottom: 1563.3856736950409,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_11_VBbBwR",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.932,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 234.95565818174043,+ y: 155.04768656967278,+ },+ {+ x: 1051.617910566121,+ y: 155.04768656967278,+ },+ {+ x: 1051.617910566121,+ y: 219.22101676195186,+ },+ {+ x: 234.95565818174043,+ y: 219.22101676195186,+ },+ ],+ boundingBox: {+ left: 234.95565818174043,+ top: 155.04768656967278,+ right: 1051.617910566121,+ bottom: 219.22101676195186,+ },+ },+ {+ id: "block_11_fZULb0",+ type: "text",+ content:+ "[6] Francois Chollet. Xception: Deep learning with depthwise separable convolutions. arXiv preprint arXiv: 1610.02357, 2016.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.916,+ avgOcrConfidence: 0.987,+ },+ polygon: [+ {+ x: 234.37082610861228,+ y: 242.1581676597882,+ },+ {+ x: 1050.1136779785156,+ y: 242.1581676597882,+ },+ {+ x: 1050.1136779785156,+ y: 284.96119192309845,+ },+ {+ x: 234.37082610861228,+ y: 284.96119192309845,+ },+ ],+ boundingBox: {+ left: 234.37082610861228,+ top: 242.1581676597882,+ right: 1050.1136779785156,+ bottom: 284.96119192309845,+ },+ },+ {+ id: "block_11_KQxaZG",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.937,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 234.59709056102446,+ y: 305.8525607747243,+ },+ {+ x: 1050.252182118214,+ y: 305.8525607747243,+ },+ {+ x: 1050.252182118214,+ y: 348.70033444856347,+ },+ {+ x: 234.59709056102446,+ y: 348.70033444856347,+ },+ ],+ boundingBox: {+ left: 234.59709056102446,+ top: 305.8525607747243,+ right: 1050.252182118214,+ bottom: 348.70033444856347,+ },+ },+ {+ id: "block_11_lSxX1m",+ type: "text",+ content:+ "[8] Chris Dyer, Adhiguna Kuncoro, Miguel Ballesteros, and Noah A. Smith. Recurrent neural network grammars. In Proc. of NAACL, 2016.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.92,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 234.54393261540545,+ y: 369.88837531814,+ },+ {+ x: 1049.7648141679972,+ y: 369.88837531814,+ },+ {+ x: 1049.7648141679972,+ y: 412.63161531606113,+ },+ {+ x: 234.54393261540545,+ y: 412.63161531606113,+ },+ ],+ boundingBox: {+ left: 234.54393261540545,+ top: 369.88837531814,+ right: 1049.7648141679972,+ bottom: 412.63161531606113,+ },+ },+ {+ id: "block_11_3YLXoz",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.927,+ avgOcrConfidence: 0.989,+ },+ polygon: [+ {+ x: 233.81299902922916,+ y: 434.3302966813395,+ },+ {+ x: 1052.8067929901345,+ y: 434.3302966813395,+ },+ {+ x: 1052.8067929901345,+ y: 476.945989020785,+ },+ {+ x: 233.81299902922916,+ y: 476.945989020785,+ },+ ],+ boundingBox: {+ left: 233.81299902922916,+ top: 434.3302966813395,+ right: 1052.8067929901345,+ bottom: 476.945989020785,+ },+ },+ {+ id: "block_11_OkxRaO",+ type: "text",+ content:+ "[10] Alex Graves. Generating sequences with recurrent neural networks. arXiv preprint arXiv: 1308.0850, 2013.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.904,+ avgOcrConfidence: 0.986,+ },+ polygon: [+ {+ x: 224.38643378932983,+ y: 498.1091927836712,+ },+ {+ x: 1050.5877919440723,+ y: 498.1091927836712,+ },+ {+ x: 1050.5877919440723,+ y: 539.0395607625632,+ },+ {+ x: 224.38643378932983,+ y: 539.0395607625632,+ },+ ],+ boundingBox: {+ left: 224.38643378932983,+ top: 498.1091927836712,+ right: 1050.5877919440723,+ bottom: 539.0395607625632,+ },+ },+ {+ id: "block_11_RVnHcs",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.919,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.3475475450502,+ y: 561.9494121522832,+ },+ {+ x: 1053.1976908662893,+ y: 561.9494121522832,+ },+ {+ x: 1053.1976908662893,+ y: 627.2271530610278,+ },+ {+ x: 224.3475475450502,+ y: 627.2271530610278,+ },+ ],+ boundingBox: {+ left: 224.3475475450502,+ top: 561.9494121522832,+ right: 1053.1976908662893,+ bottom: 627.2271530610278,+ },+ },+ {+ id: "block_11_s96TQd",+ type: "text",+ content:+ "[12] Sepp Hochreiter, Yoshua Bengio, Paolo Frasconi, and J\u00fcrgen Schmidhuber. Gradient flow in recurrent nets: the difficulty of learning long-term dependencies, 2001.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.892,+ avgOcrConfidence: 0.989,+ },+ polygon: [+ {+ x: 224.27874516396628,+ y: 647.9830188034173,+ },+ {+ x: 1048.8635432111087,+ y: 647.9830188034173,+ },+ {+ x: 1048.8635432111087,+ y: 692.1669293740639,+ },+ {+ x: 224.27874516396628,+ y: 692.1669293740639,+ },+ ],+ boundingBox: {+ left: 224.27874516396628,+ top: 647.9830188034173,+ right: 1048.8635432111087,+ bottom: 692.1669293740639,+ },+ },+ {+ id: "block_11_bKrlBK",+ type: "text",+ content:+ "[13] Sepp Hochreiter and J\u00fcrgen Schmidhuber. Long short-term memory. Neural computation, 9(8):1735-1780, 1997.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.903,+ avgOcrConfidence: 0.984,+ },+ polygon: [+ {+ x: 224.36335765532334,+ y: 712.3709330738038,+ },+ {+ x: 1051.7104044447851,+ y: 712.3709330738038,+ },+ {+ x: 1051.7104044447851,+ y: 754.2910917181719,+ },+ {+ x: 224.36335765532334,+ y: 754.2910917181719,+ },+ ],+ boundingBox: {+ left: 224.36335765532334,+ top: 712.3709330738038,+ right: 1051.7104044447851,+ bottom: 754.2910917181719,+ },+ },+ {+ id: "block_11_c3sQ7S",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.908,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.70277800177138,+ y: 777.0990849258308,+ },+ {+ x: 1050.1772024335653,+ y: 777.0990849258308,+ },+ {+ x: 1050.1772024335653,+ y: 842.7015786995565,+ },+ {+ x: 224.70277800177138,+ y: 842.7015786995565,+ },+ ],+ boundingBox: {+ left: 224.70277800177138,+ top: 777.0990849258308,+ right: 1050.1772024335653,+ bottom: 842.7015786995565,+ },+ },+ {+ id: "block_11_HmSxMA",+ type: "text",+ content:+ "[15] Rafal Jozefowicz, Oriol Vinyals, Mike Schuster, Noam Shazeer, and Yonghui Wu. Exploring the limits of language modeling. arXiv preprint arXiv: 1602.02410, 2016.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.906,+ avgOcrConfidence: 0.989,+ },+ polygon: [+ {+ x: 223.96287430811972,+ y: 863.015632801486,+ },+ {+ x: 1049.822942357864,+ y: 863.015632801486,+ },+ {+ x: 1049.822942357864,+ y: 907.0369301702743,+ },+ {+ x: 223.96287430811972,+ y: 907.0369301702743,+ },+ ],+ boundingBox: {+ left: 223.96287430811972,+ top: 863.015632801486,+ right: 1049.822942357864,+ bottom: 907.0369301702743,+ },+ },+ {+ id: "block_11_XlCObz",+ type: "text",+ content:+ "[16] \u0141ukasz Kaiser and Samy Bengio. Can active memory replace attention? In Advances in Neural Information Processing Systems, (NIPS), 2016.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.902,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 224.17545875493627,+ y: 927.1137413655905,+ },+ {+ x: 1050.2528448174469,+ y: 927.1137413655905,+ },+ {+ x: 1050.2528448174469,+ y: 970.5487977795134,+ },+ {+ x: 224.17545875493627,+ y: 970.5487977795134,+ },+ ],+ boundingBox: {+ left: 224.17545875493627,+ top: 927.1137413655905,+ right: 1050.2528448174469,+ bottom: 970.5487977795134,+ },+ },+ {+ id: "block_11_48mMcn",+ type: "text",+ content:+ "[17] \u0141ukasz Kaiser and Ilya Sutskever. Neural GPUs learn algorithms. In International Conference on Learning Representations (ICLR), 2016.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.903,+ avgOcrConfidence: 0.987,+ },+ polygon: [+ {+ x: 224.42198286961465,+ y: 991.1752927392946,+ },+ {+ x: 1049.7810976348653,+ y: 991.1752927392946,+ },+ {+ x: 1049.7810976348653,+ y: 1034.8329123590227,+ },+ {+ x: 224.42198286961465,+ y: 1034.8329123590227,+ },+ ],+ boundingBox: {+ left: 224.42198286961465,+ top: 991.1752927392946,+ right: 1049.7810976348653,+ bottom: 1034.8329123590227,+ },+ },+ {+ id: "block_11_lBImir",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.934,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 224.23202486803933,+ y: 1055.1385374714557,+ },+ {+ x: 1052.4190192675069,+ y: 1055.1385374714557,+ },+ {+ x: 1052.4190192675069,+ y: 1117.975328259002,+ },+ {+ x: 224.23202486803933,+ y: 1117.975328259002,+ },+ ],+ boundingBox: {+ left: 224.23202486803933,+ top: 1055.1385374714557,+ right: 1052.4190192675069,+ bottom: 1117.975328259002,+ },+ },+ {+ id: "block_11_Y0ddKF",+ type: "text",+ content:+ "[19] Yoon Kim, Carl Denton, Luong Hoang, and Alexander M. Rush. Structured attention networks. In International Conference on Learning Representations, 2017.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.974,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 224.29036606837366,+ y: 1142.1438929622334,+ },+ {+ x: 1052.7023705252766,+ y: 1142.1438929622334,+ },+ {+ x: 1052.7023705252766,+ y: 1185.793178300212,+ },+ {+ x: 224.29036606837366,+ y: 1185.793178300212,+ },+ ],+ boundingBox: {+ left: 224.29036606837366,+ top: 1142.1438929622334,+ right: 1052.7023705252766,+ bottom: 1185.793178300212,+ },+ },+ {+ id: "block_11_nehypx",+ type: "text",+ content:+ "[20] Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In ICLR, 2015.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.912,+ avgOcrConfidence: 0.989,+ },+ polygon: [+ {+ x: 223.92950266817192,+ y: 1205.8213097134928,+ },+ {+ x: 1052.7550077786411,+ y: 1205.8213097134928,+ },+ {+ x: 1052.7550077786411,+ y: 1227.2851158658366,+ },+ {+ x: 223.92950266817192,+ y: 1227.2851158658366,+ },+ ],+ boundingBox: {+ left: 223.92950266817192,+ top: 1205.8213097134928,+ right: 1052.7550077786411,+ bottom: 1227.2851158658366,+ },+ },+ {+ id: "block_11_af7MVz",+ type: "text",+ content:+ "[21] Oleksii Kuchaiev and Boris Ginsburg. Factorization tricks for LSTM networks. arXiv preprint arXiv: 1703.10722, 2017.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.925,+ avgOcrConfidence: 0.989,+ },+ polygon: [+ {+ x: 223.78512890669552,+ y: 1247.11833873548,+ },+ {+ x: 1050.4177622551465,+ y: 1247.11833873548,+ },+ {+ x: 1050.4177622551465,+ y: 1289.109575544085,+ },+ {+ x: 223.78512890669552,+ y: 1289.109575544085,+ },+ ],+ boundingBox: {+ left: 223.78512890669552,+ top: 1247.11833873548,+ right: 1050.4177622551465,+ bottom: 1289.109575544085,+ },+ },+ {+ id: "block_11_vnPlfZ",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.913,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 223.74063338676507,+ y: 1311.0246641116034,+ },+ {+ x: 1050.2205618976677,+ y: 1311.0246641116034,+ },+ {+ x: 1050.2205618976677,+ y: 1375.8748468958345,+ },+ {+ x: 223.74063338676507,+ y: 1375.8748468958345,+ },+ ],+ boundingBox: {+ left: 223.74063338676507,+ top: 1311.0246641116034,+ right: 1050.2205618976677,+ bottom: 1375.8748468958345,+ },+ },+ {+ id: "block_11_g0SHxO",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.908,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 224.355428932357,+ y: 1397.7982697451025,+ },+ {+ x: 1050.4997476174015,+ y: 1397.7982697451025,+ },+ {+ x: 1050.4997476174015,+ y: 1441.9434448471643,+ },+ {+ x: 224.355428932357,+ y: 1441.9434448471643,+ },+ ],+ boundingBox: {+ left: 224.355428932357,+ top: 1397.7982697451025,+ right: 1050.4997476174015,+ bottom: 1441.9434448471643,+ },+ },+ {+ id: "block_11_gDtqYI",+ type: "text",+ content:+ "[24] Minh-Thang Luong, Hieu Pham, and Christopher D Manning. Effective approaches to attention- based neural machine translation. arXiv preprint arXiv: 1508.04025, 2015.",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.927,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 224.7064228475529,+ y: 1461.612349775501,+ },+ {+ x: 1052.9802308465444,+ y: 1461.612349775501,+ },+ {+ x: 1052.9802308465444,+ y: 1506.2439438669305,+ },+ {+ x: 224.7064228475529,+ y: 1506.2439438669305,+ },+ ],+ boundingBox: {+ left: 224.7064228475529,+ top: 1461.612349775501,+ right: 1052.9802308465444,+ bottom: 1506.2439438669305,+ },+ },+ {+ id: "block_11_JWTkzE",+ type: "page_number",+ content: "11",+ metadata: {+ page: {+ number: 11,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.995,+ avgOcrConfidence: 0.995,+ },+ polygon: [+ {+ x: 629.039650241824,+ y: 1547.854550239735,+ },+ {+ x: 645.38100862155,+ y: 1547.854550239735,+ },+ {+ x: 645.38100862155,+ y: 1563.4467601919532,+ },+ {+ x: 629.039650241824,+ y: 1563.4467601919532,+ },+ ],+ boundingBox: {+ left: 629.039650241824,+ top: 1547.854550239735,+ right: 645.38100862155,+ bottom: 1563.4467601919532,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_12_TQ4Lbe",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.913,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 223.94512343580706,+ y: 154.85743054411464,+ },+ {+ x: 1050.2930801280222,+ y: 154.85743054411464,+ },+ {+ x: 1050.2930801280222,+ y: 198.76930494953817,+ },+ {+ x: 223.94512343580706,+ y: 198.76930494953817,+ },+ ],+ boundingBox: {+ left: 223.94512343580706,+ top: 154.85743054411464,+ right: 1050.2930801280222,+ bottom: 198.76930494953817,+ },+ },+ {+ id: "block_12_LvCkff",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.907,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.21323261121762,+ y: 226.782506971431,+ },+ {+ x: 1051.9384676522582,+ y: 226.782506971431,+ },+ {+ x: 1051.9384676522582,+ y: 292.8687442406676,+ },+ {+ x: 224.21323261121762,+ y: 292.8687442406676,+ },+ ],+ boundingBox: {+ left: 224.21323261121762,+ top: 226.782506971431,+ right: 1051.9384676522582,+ bottom: 292.8687442406676,+ },+ },+ {+ id: "block_12_Rm8AFL",+ type: "text",+ content:+ "[27] Ankur Parikh, Oscar T\u00e4ckstr\u00f6m, Dipanjan Das, and Jakob Uszkoreit. A decomposable attention model. In Empirical Methods in Natural Language Processing, 2016.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.916,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.08847948060418,+ y: 321.2656073462694,+ },+ {+ x: 1048.8436622341185,+ y: 321.2656073462694,+ },+ {+ x: 1048.8436622341185,+ y: 364.85913349811295,+ },+ {+ x: 224.08847948060418,+ y: 364.85913349811295,+ },+ ],+ boundingBox: {+ left: 224.08847948060418,+ top: 321.2656073462694,+ right: 1048.8436622341185,+ bottom: 364.85913349811295,+ },+ },+ {+ id: "block_12_cqas9e",+ type: "text",+ content:+ "[28] Romain Paulus, Caiming Xiong, and Richard Socher. A deep reinforced model for abstractive summarization. arXiv preprint arXiv: 1705.04304, 2017.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.912,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 224.67392691730583,+ y: 392.7383714116606,+ },+ {+ x: 1049.3349117084142,+ y: 392.7383714116606,+ },+ {+ x: 1049.3349117084142,+ y: 435.42904860991285,+ },+ {+ x: 224.67392691730583,+ y: 435.42904860991285,+ },+ ],+ boundingBox: {+ left: 224.67392691730583,+ top: 392.7383714116606,+ right: 1049.3349117084142,+ bottom: 435.42904860991285,+ },+ },+ {+ id: "block_12_hfa5dB",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.899,+ avgOcrConfidence: 0.99,+ },+ polygon: [+ {+ x: 223.91392923619625,+ y: 463.67279296530813,+ },+ {+ x: 1051.5214404920591,+ y: 463.67279296530813,+ },+ {+ x: 1051.5214404920591,+ y: 549.7230681799408,+ },+ {+ x: 223.91392923619625,+ y: 549.7230681799408,+ },+ ],+ boundingBox: {+ left: 223.91392923619625,+ top: 463.67279296530813,+ right: 1051.5214404920591,+ bottom: 549.7230681799408,+ },+ },+ {+ id: "block_12_H2k7w4",+ type: "text",+ content:+ "[30] Ofir Press and Lior Wolf. Using the output embedding to improve language models. arXiv preprint arXiv: 1608.05859, 2016.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.898,+ avgOcrConfidence: 0.987,+ },+ polygon: [+ {+ x: 224.29183347381814,+ y: 581.8894180068396,+ },+ {+ x: 1049.7876299558764,+ y: 581.8894180068396,+ },+ {+ x: 1049.7876299558764,+ y: 624.918793785841,+ },+ {+ x: 224.29183347381814,+ y: 624.918793785841,+ },+ ],+ boundingBox: {+ left: 224.29183347381814,+ top: 581.8894180068396,+ right: 1049.7876299558764,+ bottom: 624.918793785841,+ },+ },+ {+ id: "block_12_UrZIEK",+ type: "text",+ content:+ "[31] Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words with subword units. arXiv preprint arXiv: 1508.07909, 2015.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.925,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 224.35140540129947,+ y: 653.3260510666926,+ },+ {+ x: 1049.4855337769445,+ y: 653.3260510666926,+ },+ {+ x: 1049.4855337769445,+ y: 696.2955715494944,+ },+ {+ x: 224.35140540129947,+ y: 696.2955715494944,+ },+ ],+ boundingBox: {+ left: 224.35140540129947,+ top: 653.3260510666926,+ right: 1049.4855337769445,+ bottom: 696.2955715494944,+ },+ },+ {+ id: "block_12_IIwlxZ",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.88,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 224.15238262092979,+ y: 724.7319041087216,+ },+ {+ x: 1051.274348349467,+ y: 724.7319041087216,+ },+ {+ x: 1051.274348349467,+ y: 791.0497254966793,+ },+ {+ x: 224.15238262092979,+ y: 791.0497254966793,+ },+ ],+ boundingBox: {+ left: 224.15238262092979,+ top: 724.7319041087216,+ right: 1051.274348349467,+ bottom: 791.0497254966793,+ },+ },+ {+ id: "block_12_pGLzhM",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.938,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 224.4417928431156,+ y: 819.0001126052741,+ },+ {+ x: 1053.3042907714844,+ y: 819.0001126052741,+ },+ {+ x: 1053.3042907714844,+ y: 885.2761205228649,+ },+ {+ x: 224.4417928431156,+ y: 885.2761205228649,+ },+ ],+ boundingBox: {+ left: 224.4417928431156,+ top: 819.0001126052741,+ right: 1053.3042907714844,+ bottom: 885.2761205228649,+ },+ },+ {+ id: "block_12_Bz8MfK",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.897,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.0948934624665,+ y: 913.8373252467105,+ },+ {+ x: 1051.823347328353,+ y: 913.8373252467105,+ },+ {+ x: 1051.823347328353,+ y: 1000.8878563328793,+ },+ {+ x: 224.0948934624665,+ y: 1000.8878563328793,+ },+ ],+ boundingBox: {+ left: 224.0948934624665,+ top: 913.8373252467105,+ right: 1051.823347328353,+ bottom: 1000.8878563328793,+ },+ },+ {+ id: "block_12_m0nnSr",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.899,+ avgOcrConfidence: 0.988,+ },+ polygon: [+ {+ x: 224.52872478178818,+ y: 1030.965426796361,+ },+ {+ x: 1050.1110271815835,+ y: 1030.965426796361,+ },+ {+ x: 1050.1110271815835,+ y: 1074.9609636579241,+ },+ {+ x: 224.52872478178818,+ y: 1074.9609636579241,+ },+ ],+ boundingBox: {+ left: 224.52872478178818,+ top: 1030.965426796361,+ right: 1050.1110271815835,+ bottom: 1074.9609636579241,+ },+ },+ {+ id: "block_12_C1nzdD",+ type: "text",+ content:+ "[36] Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, and Zbigniew Wojna. Rethinking the inception architecture for computer vision. CoRR, abs/1512.00567, 2015.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.939,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.60145602261062,+ y: 1102.9526906981505,+ },+ {+ x: 1051.9790816481095,+ y: 1102.9526906981505,+ },+ {+ x: 1051.9790816481095,+ y: 1146.15116715969,+ },+ {+ x: 224.60145602261062,+ y: 1146.15116715969,+ },+ ],+ boundingBox: {+ left: 224.60145602261062,+ top: 1102.9526906981505,+ right: 1051.9790816481095,+ bottom: 1146.15116715969,+ },+ },+ {+ id: "block_12_smJ629",+ type: "text",+ content:+ "[37] Vinyals & Kaiser, Koo, Petrov, Sutskever, and Hinton. Grammar as a foreign language. In Advances in Neural Information Processing Systems, 2015.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.912,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.70363004364236,+ y: 1173.716330506748,+ },+ {+ x: 1049.93891472364,+ y: 1173.716330506748,+ },+ {+ x: 1049.93891472364,+ y: 1218.0808487512115,+ },+ {+ x: 224.70363004364236,+ y: 1218.0808487512115,+ },+ ],+ boundingBox: {+ left: 224.70363004364236,+ top: 1173.716330506748,+ right: 1049.93891472364,+ bottom: 1218.0808487512115,+ },+ },+ {+ id: "block_12_oKrqzS",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.935,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 224.222865417926,+ y: 1246.0137622804568,+ },+ {+ x: 1050.4285547855127,+ y: 1246.0137622804568,+ },+ {+ x: 1050.4285547855127,+ y: 1332.3901636224045,+ },+ {+ x: 224.222865417926,+ y: 1332.3901636224045,+ },+ ],+ boundingBox: {+ left: 224.222865417926,+ top: 1246.0137622804568,+ right: 1050.4285547855127,+ bottom: 1332.3901636224045,+ },+ },+ {+ id: "block_12_5hQUgX",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.977,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 224.40534438530025,+ y: 1362.7727877394598,+ },+ {+ x: 1049.6643678985372,+ y: 1362.7727877394598,+ },+ {+ x: 1049.6643678985372,+ y: 1404.796982844073,+ },+ {+ x: 224.40534438530025,+ y: 1404.796982844073,+ },+ ],+ boundingBox: {+ left: 224.40534438530025,+ top: 1362.7727877394598,+ right: 1049.6643678985372,+ bottom: 1404.796982844073,+ },+ },+ {+ id: "block_12_7qyMnf",+ type: "text",+ content:+ "[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.",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "List Item",+ minOcrConfidence: 0.905,+ avgOcrConfidence: 0.991,+ },+ polygon: [+ {+ x: 224.04902520841057,+ y: 1434.5126750056904,+ },+ {+ x: 1049.9945814592124,+ y: 1434.5126750056904,+ },+ {+ x: 1049.9945814592124,+ y: 1501.148572362455,+ },+ {+ x: 224.04902520841057,+ y: 1501.148572362455,+ },+ ],+ boundingBox: {+ left: 224.04902520841057,+ top: 1434.5126750056904,+ right: 1049.9945814592124,+ bottom: 1501.148572362455,+ },+ },+ {+ id: "block_12_6o6JUd",+ type: "page_number",+ content: "12",+ metadata: {+ page: {+ number: 12,+ width: 1275,+ height: 1651,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.998,+ avgOcrConfidence: 0.998,+ },+ polygon: [+ {+ x: 628.997000812614,+ y: 1547.789391309695,+ },+ {+ x: 647.0427269483133,+ y: 1547.789391309695,+ },+ {+ x: 647.0427269483133,+ y: 1563.398364533159,+ },+ {+ x: 628.997000812614,+ y: 1563.398364533159,+ },+ ],+ boundingBox: {+ left: 628.997000812614,+ top: 1547.789391309695,+ right: 647.0427269483133,+ bottom: 1563.398364533159,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_13_KlKk5h",+ type: "page_number",+ content: "13",+ metadata: {+ page: {+ number: 13,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.999,+ avgOcrConfidence: 0.999,+ },+ polygon: [+ {+ x: 103.29433033878627,+ y: 628.7723457726248,+ },+ {+ x: 103.29433033878627,+ y: 646.9001519418981,+ },+ {+ x: 87.59273293860883,+ y: 646.9001519418981,+ },+ {+ x: 87.59273293860883,+ y: 628.7723457726248,+ },+ ],+ boundingBox: {+ left: 87.59273293860883,+ top: 628.7723457726248,+ right: 103.29433033878627,+ bottom: 646.9001519418981,+ },+ },+ {+ id: "block_13_PkaOm5",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 13,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.937,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 999.8870322148603,+ y: 224.33585563715354,+ },+ {+ x: 999.8870322148603,+ y: 1052.0067256732577,+ },+ {+ x: 911.037953656419,+ y: 1052.0067256732577,+ },+ {+ x: 911.037953656419,+ y: 224.33585563715354,+ },+ ],+ boundingBox: {+ left: 911.037953656419,+ top: 224.33585563715354,+ right: 999.8870322148603,+ bottom: 1052.0067256732577,+ },+ },+ {+ id: "block_13_xamkHQ",+ type: "figure",+ content:+ "<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>",+ metadata: {+ page: {+ number: 13,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Picture/Figure/Image/Chart",+ minOcrConfidence: 0.717,+ avgOcrConfidence: 0.98,+ },+ polygon: [+ {+ x: 1444.0009233001479,+ y: 252.8656019781628,+ },+ {+ x: 1444.0009233001479,+ y: 1047.5539548553688,+ },+ {+ x: 1022.9538143416097,+ y: 1047.5539548553688,+ },+ {+ x: 1022.9538143416097,+ y: 252.8656019781628,+ },+ ],+ boundingBox: {+ left: 1022.9538143416097,+ top: 252.8656019781628,+ right: 1444.0009233001479,+ bottom: 1047.5539548553688,+ },+ },+ {+ id: "block_13_5eYqPZ",+ type: "heading",+ content: "# Attention Visualizations",+ metadata: {+ page: {+ number: 13,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Heading",+ minOcrConfidence: 0.992,+ avgOcrConfidence: 0.992,+ },+ polygon: [+ {+ x: 1498.6412794643775,+ y: 224.94428453654268,+ },+ {+ x: 1498.6412794643775,+ y: 480.8453803514912,+ },+ {+ x: 1479.199057528847,+ y: 480.8453803514912,+ },+ {+ x: 1479.199057528847,+ y: 224.94428453654268,+ },+ ],+ boundingBox: {+ left: 1479.199057528847,+ top: 224.94428453654268,+ right: 1498.6412794643775,+ bottom: 480.8453803514912,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_14_DaAuYi",+ type: "page_number",+ content: "14",+ metadata: {+ page: {+ number: 14,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.998,+ avgOcrConfidence: 0.998,+ },+ polygon: [+ {+ x: 103.12243577770732,+ y: 628.7327731612825,+ },+ {+ x: 103.12243577770732,+ y: 647.0026336447166,+ },+ {+ x: 87.74237117910752,+ y: 647.0026336447166,+ },+ {+ x: 87.74237117910752,+ y: 628.7327731612825,+ },+ ],+ boundingBox: {+ left: 87.74237117910752,+ top: 628.7327731612825,+ right: 103.12243577770732,+ bottom: 647.0026336447166,+ },+ },+ {+ id: "block_14_VDKMys",+ type: "text",+ content:+ "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:",+ metadata: {+ page: {+ number: 14,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.972,+ avgOcrConfidence: 0.993,+ },+ polygon: [+ {+ x: 370.4634644357782,+ y: 224.1528559775248,+ },+ {+ x: 370.4634644357782,+ y: 1051.3102287793681,+ },+ {+ x: 303.81733864232115,+ y: 1051.3102287793681,+ },+ {+ x: 303.81733864232115,+ y: 224.1528559775248,+ },+ ],+ boundingBox: {+ left: 303.81733864232115,+ top: 224.1528559775248,+ right: 370.4634644357782,+ bottom: 1051.3102287793681,+ },+ },+ {+ id: "block_14_QRz2LE",+ type: "figure",+ content:+ "<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>",+ metadata: {+ page: {+ number: 14,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Picture/Figure/Image/Chart",+ minOcrConfidence: 0.379,+ avgOcrConfidence: 0.963,+ },+ polygon: [+ {+ x: 1294.7974623916741,+ y: 255.12043611846704,+ },+ {+ x: 1294.7974623916741,+ y: 1044.444475382784,+ },+ {+ x: 388.9633916410289,+ y: 1044.444475382784,+ },+ {+ x: 388.9633916410289,+ y: 255.12043611846704,+ },+ ],+ boundingBox: {+ left: 388.9633916410289,+ top: 255.12043611846704,+ right: 1294.7974623916741,+ bottom: 1044.444475382784,+ },+ },+ ],+ },+ {+ blocks: [+ {+ id: "block_15_pV91a2",+ type: "page_number",+ content: "15",+ metadata: {+ page: {+ number: 15,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Page Number",+ minOcrConfidence: 0.998,+ avgOcrConfidence: 0.998,+ },+ polygon: [+ {+ x: 103.26014084206486,+ y: 628.7008215911197,+ },+ {+ x: 103.26014084206486,+ y: 647.1549124613296,+ },+ {+ x: 87.58487219559515,+ y: 647.1549124613296,+ },+ {+ x: 87.58487219559515,+ y: 628.7008215911197,+ },+ ],+ boundingBox: {+ left: 87.58487219559515,+ top: 628.7008215911197,+ right: 103.26014084206486,+ bottom: 647.1549124613296,+ },+ },+ {+ id: "block_15_2igWoi",+ type: "text",+ content:+ "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",+ metadata: {+ page: {+ number: 15,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Caption",+ minOcrConfidence: 0.976,+ avgOcrConfidence: 0.994,+ },+ polygon: [+ {+ x: 394.6980404387739,+ y: 223.74716570777616,+ },+ {+ x: 394.6980404387739,+ y: 1049.736980800211,+ },+ {+ x: 328.87227315113955,+ y: 1049.736980800211,+ },+ {+ x: 328.87227315113955,+ y: 223.74716570777616,+ },+ ],+ boundingBox: {+ left: 328.87227315113955,+ top: 223.74716570777616,+ right: 394.6980404387739,+ bottom: 1049.736980800211,+ },+ },+ {+ id: "block_15_OqCqJD",+ type: "figure",+ content:+ "<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>",+ metadata: {+ page: {+ number: 15,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Picture/Figure/Image/Chart",+ minOcrConfidence: 0.651,+ avgOcrConfidence: 0.969,+ },+ polygon: [+ {+ x: 810.314180990807,+ y: 253.4944325467966,+ },+ {+ x: 810.314180990807,+ y: 1035.3522419059364,+ },+ {+ x: 421.96601087527165,+ y: 1035.3522419059364,+ },+ {+ x: 421.96601087527165,+ y: 253.4944325467966,+ },+ ],+ boundingBox: {+ left: 421.96601087527165,+ top: 253.4944325467966,+ right: 810.314180990807,+ bottom: 1035.3522419059364,+ },+ },+ {+ id: "block_15_sK8Nre",+ type: "figure",+ content:+ "<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>",+ metadata: {+ page: {+ number: 15,+ width: 1651,+ height: 1275,+ },+ layoutClass: "Picture/Figure/Image/Chart",+ minOcrConfidence: 0.6,+ avgOcrConfidence: 0.968,+ },+ polygon: [+ {+ x: 1255.9501913113702,+ y: 254.50874105857238,+ },+ {+ x: 1255.9501913113702,+ y: 1034.3072598868043,+ },+ {+ x: 882.2701913360366,+ y: 1034.3072598868043,+ },+ {+ x: 882.2701913360366,+ y: 254.50874105857238,+ },+ ],+ boundingBox: {+ left: 882.2701913360366,+ top: 254.50874105857238,+ right: 1255.9501913113702,+ bottom: 1034.3072598868043,+ },+ },+ ],+ },+ ],+} satisfies ParsedOcrOutput-const PAGE_WIDTH = 792-const PAGE_HEIGHT = 612-const OCR_BLOCKS: OcrBlock[] = [+const BLOCK_STYLES: Record<+ OcrBlockType,{- id: "title",- kind: "Heading",- text: "# Attention Is All You Need",- page: 1,- confidence: 0.99,+ label: string+ icon: React.ComponentProps<typeof HugeiconsIcon>["icon"]+ overlay: string+ mutedOverlay: string+ ring: string+ text: string+ }+> = {+ heading: {+ label: "Heading",icon: Heading01Icon,- accentClassName: "border-violet-500/60 bg-violet-500/5 text-violet-600",- polygon: [- { x: 246, y: 188 },- { x: 566, y: 188 },- { x: 566, y: 222 },- { x: 246, y: 222 },- ],+ overlay: "border-violet-500/70 bg-violet-500/10",+ mutedOverlay: "border-violet-500/35 bg-violet-500/5",+ ring: "border-violet-500/60 bg-violet-500/5 text-violet-600",+ text: "text-violet-600 dark:text-violet-300",},- {- id: "abstract",- kind: "Paragraph",- text: "The model relies **only on attention**, avoiding recurrence and convolutions.",- page: 1,- confidence: 0.94,+ paragraph: {+ label: "Paragraph",icon: ParagraphIcon,- accentClassName: "border-blue-500/60 bg-blue-500/5 text-blue-600",- polygon: [- { x: 108, y: 346 },- { x: 692, y: 346 },- { x: 692, y: 458 },- { x: 108, y: 458 },- ],+ overlay: "border-blue-500/70 bg-blue-500/10",+ mutedOverlay: "border-blue-500/35 bg-blue-500/5",+ ring: "border-blue-500/60 bg-blue-500/5 text-blue-600",+ text: "text-blue-600 dark:text-blue-300",},- {- id: "table",- kind: "Table",- text: "- **Layer type**\n- Path length\n- Sequential operations",- page: 6,- confidence: 0.91,+ list: {+ label: "List",+ icon: LeftToRightListBulletIcon,+ overlay: "border-emerald-500/70 bg-emerald-500/10",+ mutedOverlay: "border-emerald-500/35 bg-emerald-500/5",+ ring: "border-emerald-500/60 bg-emerald-500/5 text-emerald-600",+ text: "text-emerald-600 dark:text-emerald-300",+ },+ table: {+ label: "Table",icon: Table01Icon,- accentClassName: "border-amber-500/60 bg-amber-500/5 text-amber-700",- polygon: [- { x: 52, y: 58 },- { x: 740, y: 58 },- { x: 740, y: 190 },- { x: 52, y: 190 },- ],+ overlay: "border-amber-500/70 bg-amber-500/10",+ mutedOverlay: "border-amber-500/35 bg-amber-500/5",+ ring: "border-amber-500/60 bg-amber-500/5 text-amber-700",+ text: "text-amber-700 dark:text-amber-300",+ },+ figure: {+ label: "Figure",+ icon: ImageCompositionIcon,+ overlay: "border-rose-500/70 bg-rose-500/10",+ mutedOverlay: "border-rose-500/35 bg-rose-500/5",+ ring: "border-rose-500/60 bg-rose-500/5 text-rose-600",+ text: "text-rose-600 dark:text-rose-300",+ },+ header: {+ label: "Header",+ icon: TextCenterlineCenterTopIcon,+ overlay: "border-cyan-500/70 bg-cyan-500/10",+ mutedOverlay: "border-cyan-500/35 bg-cyan-500/5",+ ring: "border-cyan-500/60 bg-cyan-500/5 text-cyan-700",+ text: "text-cyan-700 dark:text-cyan-300",},-]+ footer: {+ label: "Footer",+ icon: AlignBoxBottomCenterIcon,+ overlay: "border-slate-500/70 bg-slate-500/10",+ mutedOverlay: "border-slate-500/35 bg-slate-500/5",+ ring: "border-slate-500/60 bg-slate-500/5 text-slate-700",+ text: "text-slate-700 dark:text-slate-300",+ },+ page_number: {+ label: "Page number",+ icon: TextNumberSignIcon,+ overlay: "border-zinc-500/70 bg-zinc-500/10",+ mutedOverlay: "border-zinc-500/35 bg-zinc-500/5",+ ring: "border-zinc-500/60 bg-zinc-500/5 text-zinc-700",+ text: "text-zinc-700 dark:text-zinc-300",+ },+}++function getBlockType(block: ParsedOcrBlock): OcrBlockType | undefined {+ if (block.type === "heading" || block.type === "section_heading") {+ return "heading"+ }++ if (block.type === "header") {+ return "header"+ }++ if (block.type === "footer") {+ return "footer"+ }++ if (block.type === "page_number") {+ return "page_number"+ }++ if (block.type === "figure" || block.type === "image") {+ return "figure"+ }++ if (block.type === "table") {+ return "table"+ }++ if (block.metadata.layoutClass === "List Item") {+ return "list"+ }++ if (block.type === "text") {+ return "paragraph"+ }+}++function getOcrBlocks(output: ParsedOcrOutput): OcrBlock[] {+ return output.chunks.flatMap((chunk) =>+ chunk.blocks.flatMap((block) => {+ const type = getBlockType(block)+ const { page } = block.metadata++ if (!type || page.width <= 0 || page.height <= 0) {+ return []+ }++ return {+ id: block.id,+ type,+ text: block.content,+ page: page.number,+ pageWidth: page.width,+ pageHeight: page.height,+ confidence:+ block.metadata.avgOcrConfidence ??+ block.metadata.minOcrConfidence ??+ 1,+ polygon: block.polygon,+ boundingBox: block.boundingBox,+ }+ })+ )+}++function getBoundingBox(block: OcrBlock): BoundingBox {+ if (block.boundingBox) {+ return block.boundingBox+ }-function polygonToArea(polygon: OcrBlock["polygon"]) {+ const polygon = block.polygon ?? []const xValues = polygon.map((point) => point.x)const yValues = polygon.map((point) => point.y)const left = Math.min(...xValues)@@ -83,18 +8062,30 @@ function polygonToArea(polygon: OcrBlock["polygon"]) {const top = Math.min(...yValues)const bottom = Math.max(...yValues)+ return { left, top, right, bottom }+}++function blockToArea(block: OcrBlock): React.CSSProperties {+ const { left, top, right, bottom } = getBoundingBox(block)+return {- left: `${(left / PAGE_WIDTH) * 100}%`,- top: `${(top / PAGE_HEIGHT) * 100}%`,- width: `${((right - left) / PAGE_WIDTH) * 100}%`,- height: `${((bottom - top) / PAGE_HEIGHT) * 100}%`,+ left: `${(left / block.pageWidth) * 100}%`,+ top: `${(top / block.pageHeight) * 100}%`,+ width: `${((right - left) / block.pageWidth) * 100}%`,+ height: `${((bottom - top) / block.pageHeight) * 100}%`,}}function OcrBlockMarkdown({ text }: { text: string }) {+ const markdown = text.replace(OCR_MARKDOWN_FIGURE_CAPTION_PATTERN, (tag) =>+ tag.startsWith("</") ? "</figcaption>" : "<figcaption>"+ )+return (<div className="space-y-1 text-sm leading-5 text-foreground/90"><ReactMarkdown+ rehypePlugins={OCR_MARKDOWN_REHYPE_PLUGINS}+ remarkPlugins={OCR_MARKDOWN_REMARK_PLUGINS}components={{h1: ({ node: _node, ...props }) => (<h1@@ -102,68 +8093,129 @@ function OcrBlockMarkdown({ text }: { text: string }) {{...props}/>),- h2: ({ node: _node, ...props }) => (- <h2- className="my-0 text-[15px] leading-5 font-semibold text-foreground"- {...props}- />- ),- h3: ({ node: _node, ...props }) => (- <h3- className="my-0 text-sm leading-5 font-semibold text-foreground"- {...props}- />- ),p: ({ node: _node, ...props }) => (<p className="my-0 text-[13px] leading-5" {...props} />),- strong: ({ node: _node, ...props }) => (- <strong className="font-semibold text-foreground" {...props} />- ),- em: ({ node: _node, ...props }) => (- <em className="text-foreground" {...props} />- ),- ul: ({ node: _node, ...props }) => (- <ul className="my-0 list-disc space-y-0.5 pl-4" {...props} />- ),- li: ({ node: _node, ...props }) => (- <li className="pl-0.5 text-[13px] leading-5" {...props} />+ ol: ({ node: _node, ...props }) => (+ <ol className="my-0 list-decimal space-y-0.5 pl-4" {...props} />),table: ({ node: _node, ...props }) => (<div className="overflow-hidden rounded-md border bg-background"><table className="w-full border-collapse text-xs" {...props} /></div>),- th: ({ node: _node, ...props }) => (- <th- className="border-b bg-muted px-2 py-1 text-left font-medium"+ figure: ({ node: _node, ...props }) => (+ <figure+ className="my-0 space-y-2 rounded-md border bg-muted/20 p-2 text-[13px]"+ {...props}+ />+ ),+ figcaption: ({ node: _node, ...props }) => (+ <figcaption+ className="border-t pt-2 text-xs leading-5 text-muted-foreground"+ {...props}+ />+ ),+ caption: ({ node: _node, ...props }) => (+ <figcaption+ className="block border-t pt-2 text-xs leading-5 text-muted-foreground"{...props}/>),+ th: ({ node: _node, ...props }) => (+ <th className="border-b bg-muted px-2 py-1 text-left" {...props} />+ ),td: ({ node: _node, ...props }) => (<td className="border-t px-2 py-1" {...props} />),}}>- {text}+ {markdown}</ReactMarkdown></div>)}-export function OcrBlocksBlock({ file }: { file?: string }) {- const [activeBlockId, setActiveBlockId] = React.useState(OCR_BLOCKS[0].id)+function OcrBlockButton({+ block,+ isActive,+ onFocusBlock,+}: {+ block: OcrBlock+ isActive: boolean+ onFocusBlock: (block: OcrBlock) => void+}) {+ const style = BLOCK_STYLES[block.type]++ return (+ <button+ type="button"+ onClick={() => onFocusBlock(block)}+ onFocus={() => onFocusBlock(block)}+ className={cn(+ "mb-2 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",+ isActive && style.ring+ )}+ >+ <div className="flex items-start gap-3">+ <div className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-md bg-muted">+ <HugeiconsIcon icon={style.icon} className="size-4" />+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex items-center justify-between gap-2">+ <div className={cn("text-xs font-medium", style.text)}>+ {style.label} - {Math.round(block.confidence * 100)}%+ </div>+ <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">+ p. {block.page}+ </div>+ </div>+ <div className="mt-2 text-sm text-foreground/90">+ <OcrBlockMarkdown text={block.text} />+ </div>+ </div>+ </div>+ </button>+ )+}++export function OcrBlocksBlock({+ file = PDF_URL,+ output = ATTENTION_OCR_OUTPUT,+}: {+ file?: string+ output?: ParsedOcrOutput+}) {+ const blocks = React.useMemo(() => getOcrBlocks(output), [output])+ const scrollViewportRef = React.useRef<HTMLDivElement | null>(null)+ const [activeBlockId, setActiveBlockId] = React.useState(blocks[0]?.id)const viewerRef = React.useRef<PDFViewerHandle>(null)- const activeBlock =- OCR_BLOCKS.find((block) => block.id === activeBlockId) ?? OCR_BLOCKS[0]+ const activeBlock = blocks.find((block) => block.id === activeBlockId)+ const virtualizer = useVirtualizer({+ count: blocks.length,+ estimateSize: () => OCR_BLOCK_ROW_ESTIMATE,+ getItemKey: (index) => blocks[index]?.id ?? index,+ getScrollElement: () => scrollViewportRef.current,+ overscan: 8,+ })++ React.useEffect(() => {+ if (!blocks.length || blocks.some((block) => block.id === activeBlockId)) {+ return+ }++ setActiveBlockId(blocks[0].id)+ }, [activeBlockId, blocks])const focusBlock = React.useCallback((block: OcrBlock) => {+ const area = blockToArea(block)+setActiveBlockId(block.id)viewerRef.current?.scrollToPageArea(block.page, {- left: Number.parseFloat(polygonToArea(block.polygon).left),- top: Number.parseFloat(polygonToArea(block.polygon).top),- width: Number.parseFloat(polygonToArea(block.polygon).width),- height: Number.parseFloat(polygonToArea(block.polygon).height),+ left: Number.parseFloat(String(area.left)),+ top: Number.parseFloat(String(area.top)),+ width: Number.parseFloat(String(area.width)),+ height: Number.parseFloat(String(area.height)),})}, [])@@ -176,64 +8228,74 @@ export function OcrBlocksBlock({ file }: { file?: string }) {file={file}defaultZoom={0.75}renderPageOverlay={({ pageNumber }) =>- OCR_BLOCKS.filter((block) => block.page === pageNumber).map(- (block) => (- <div- key={block.id}- className={cn(- "pointer-events-none absolute z-10 rounded-[3px] border",- block.id === activeBlock.id- ? block.accentClassName- : "border-muted-foreground/30 bg-muted/20"- )}- style={polygonToArea(block.polygon)}- />- )- )+ blocks+ .filter((block) => block.page === pageNumber)+ .map((block) => {+ const style = BLOCK_STYLES[block.type]++ return (+ <div+ key={block.id}+ className={cn(+ "pointer-events-none absolute z-10 border",+ block.id === activeBlock?.id+ ? style.overlay+ : style.mutedOverlay+ )}+ style={blockToArea(block)}+ />+ )+ })}/>}right={<aside className="min-h-0 bg-background">- <ScrollArea className="h-full" scrollFade>- <div className="space-y-2 p-3">- {OCR_BLOCKS.map((block) => {- const isActive = block.id === activeBlock.id+ <ScrollArea+ className="h-full"+ scrollFade+ viewportRef={scrollViewportRef}+ >+ {blocks.length ? (+ <div+ className="relative"+ style={{+ height:+ virtualizer.getTotalSize() + OCR_BLOCK_LIST_PADDING * 2,+ }}+ >+ {virtualizer.getVirtualItems().map((virtualRow) => {+ const block = blocks[virtualRow.index]+ if (!block) return null- return (- <button- key={block.id}- type="button"- onClick={() => focusBlock(block)}- onFocus={() => focusBlock(block)}- onMouseEnter={() => focusBlock(block)}- className={cn(- "w-full rounded-lg border bg-background p-3 text-left transition-colors hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",- isActive && block.accentClassName- )}- >- <div className="flex items-start gap-3">- <div className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-md bg-muted">- <HugeiconsIcon icon={block.icon} className="size-4" />- </div>- <div className="min-w-0 flex-1">- <div className="flex items-center justify-between gap-2">- <div className="text-xs font-medium text-muted-foreground">- {block.kind} - {Math.round(block.confidence * 100)}%- </div>- <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">- p. {block.page}- </div>- </div>- <div className="mt-2 text-sm text-foreground/90">- <OcrBlockMarkdown text={block.text} />- </div>- </div>+ return (+ <div+ key={virtualRow.key}+ ref={virtualizer.measureElement}+ data-index={virtualRow.index}+ className="absolute top-0 right-3 left-3"+ style={{+ transform: `translateY(${+ virtualRow.start + OCR_BLOCK_LIST_PADDING+ }px)`,+ }}+ >+ <OcrBlockButton+ block={block}+ isActive={block.id === activeBlock?.id}+ onFocusBlock={focusBlock}+ /></div>- </button>- )- })}- </div>+ )+ })}+ </div>+ ) : (+ <div className="p-3">+ <div className="rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground">+ No OCR blocks found.+ </div>+ </div>+ )}</ScrollArea></aside>}diff --git a/apps/v4/registry/new-york-v4/blocks/pdf-dropzone.tsx b/apps/v4/registry/new-york-v4/blocks/pdf-dropzone.tsxindex e6bcd88..e078824 100644--- a/apps/v4/registry/new-york-v4/blocks/pdf-dropzone.tsx+++ b/apps/v4/registry/new-york-v4/blocks/pdf-dropzone.tsx@@ -65,6 +65,7 @@ export function PdfDropzoneBlock() {key={pdfFile.url}file={pdfFile.url}defaultZoom={0.75}+ downloadFileName={pdfFile.name}onPdfUpload={(file) => loadPdf([file])}toolbarActions={<div className="hidden max-w-40 truncate text-xs text-muted-foreground sm:block">diff --git a/apps/v4/registry/new-york-v4/ui/file-upload.tsx b/apps/v4/registry/new-york-v4/ui/file-upload.tsxindex fac25e8..0521abb 100644--- a/apps/v4/registry/new-york-v4/ui/file-upload.tsx+++ b/apps/v4/registry/new-york-v4/ui/file-upload.tsx@@ -121,7 +121,8 @@ function UploadIconCluster({"absolute top-1/2 left-1/2 grid size-12 place-items-center rounded-xl bg-background text-muted-foreground transition-[transform,color,background-color] duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] before:rounded-[calc(var(--radius-xl)-1px)]","motion-reduce:transition-none",index === 1 && "z-10",- isDragging && "bg-accent text-foreground"+ isDragging &&+ "bg-popover text-foreground shadow-md shadow-black/10 not-dark:bg-clip-border dark:shadow-black/25")}style={{transform: singleIcon@@ -197,7 +198,7 @@ export function FileUpload({"motion-reduce:transition-none",isDragging? "border-foreground/40 bg-accent/35"- : "border-border hover:border-foreground/30 hover:bg-muted/35"+ : "border-foreground/20 hover:border-foreground/35 hover:bg-muted/35 dark:border-foreground/25 dark:hover:border-foreground/40")}onDragEnter={(event) => {event.preventDefault()diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 760d10a..2026351 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -57,6 +57,9 @@ importers:'@tabler/icons-react':specifier: ^3.31.0version: 3.34.1([email protected])+ '@tanstack/react-virtual':+ specifier: 3.13.26border-beam:specifier: ^1.0.1@@ -126,6 +129,15 @@ importers:rehype-pretty-code:specifier: ^0.14.1version: 0.14.1([email protected])+ rehype-raw:+ specifier: ^7.0.0+ version: 7.0.0+ rehype-sanitize:+ specifier: ^6.0.0+ version: 6.0.0+ remark-gfm:+ specifier: 4.0.1+ version: 4.0.1shadcn:specifier: ^4.8.2version: 4.8.2(@types/[email protected])([email protected])@@ -3137,6 +3149,12 @@ packages:resolution: {integrity: sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A==}+ resolution: {integrity: sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw==}++ resolution: {integrity: sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg==}+resolution: {integrity: sha512-48+B/rJWAp0jamNbAAf9M7Uf//UVqAoMmgXhBdxTDJLGKY+LRnZ99qcG+Qjl5HfMpYNzS5v4EAwVEF34LeAj7w==}@@ -3146,6 +3164,9 @@ packages:resolution: {integrity: sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==}+ resolution: {integrity: sha512-MlWT6Pjt4CG9lFCjiz4BH7l9wmrMkfkJYCxFwKQic8+RTZgWPuWxwAfjJElsXkex7DJjfSJsQIt931ilUgmwdA==}+resolution: {integrity: sha512-XelQVTDWvqcl3axRfI0xSeoVKzyIFPwsAGSLIsKdJKQMXDYJS4WYrBNF/8J7RdhIcFI2BOHgAifggsvsxp/3+A==}@@ -4412,9 +4433,15 @@ packages:peerDependencies:shiki: ^1.0.0 || ^2.0.0 || ^3.0.0+ resolution: {integrity: sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww==}+resolution: {integrity: sha512-lqA4rGUf1JmacCNWWZx0Wv1dHqMwxzsDWYMTowuplHF3xH0N/MmrZ/G3BDZnzAkRmxDadujCjaKM2hqYdCBOGw==}+ resolution: {integrity: sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg==}+resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}@@ -8173,6 +8200,28 @@ snapshots:dependencies:'@types/hast': 3.0.4+ dependencies:+ '@types/hast': 3.0.4+ '@types/unist': 3.0.3+ '@ungap/structured-clone': 1.3.0+ hast-util-from-parse5: 8.0.3+ hast-util-to-parse5: 8.0.1+ html-void-elements: 3.0.0+ mdast-util-to-hast: 13.2.0+ parse5: 7.3.0+ unist-util-position: 5.0.0+ unist-util-visit: 5.0.0+ vfile: 6.0.3+ web-namespaces: 2.0.1+ zwitch: 2.0.4++ dependencies:+ '@types/hast': 3.0.4+ '@ungap/structured-clone': 1.3.0+ unist-util-position: 5.0.0+dependencies:'@types/estree': 1.0.8@@ -8228,6 +8277,16 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@types/hast': 3.0.4+ comma-separated-tokens: 2.0.3+ devlop: 1.1.0+ property-information: 7.1.0+ space-separated-tokens: 2.0.2+ web-namespaces: 2.0.1+ zwitch: 2.0.4+dependencies:'@types/hast': 3.0.4@@ -9676,6 +9735,12 @@ snapshots:unified: 11.0.5unist-util-visit: 5.0.0+ dependencies:+ '@types/hast': 3.0.4+ hast-util-raw: 9.1.0+ vfile: 6.0.3+dependencies:'@types/estree': 1.0.8@@ -9684,6 +9749,11 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@types/hast': 3.0.4+ hast-util-sanitize: 5.0.2+dependencies:'@types/mdast': 4.0.4