Skip to content

armgit / ui

Public Imported from GitHub
0
TypeScript

Harden registry previews and resizable block layouts

Andrew Luo7391673573c8
diff --git a/apps/v4/components/file-thumbnail-docs.tsx b/apps/v4/components/file-thumbnail-docs.tsx
index 70417e8..a6d6c83 100644
--- a/apps/v4/components/file-thumbnail-docs.tsx
+++ b/apps/v4/components/file-thumbnail-docs.tsx
@@ -98,6 +98,7 @@ function getThumbnailFile(file: DemoFile): ThumbnailFile {
name: file.name,
size: file.size,
type: file.type,
+ url: file.url,
}
}
@@ -178,58 +179,12 @@ export function DocumentAwareFileThumbnail({
generationDelayMs?: number
showMetadata?: boolean
}) {
- const isActive = useThumbnailActivation(generationDelayMs)
-
- if (isImageFile(file)) {
- return (
- <FileThumbnail
- file={getThumbnailFile(file)}
- previewImageUrl={file.url}
- className={className}
- showMetadata={showMetadata}
- />
- )
- }
-
- if (isPdfFile(file)) {
- return (
- <PdfFileThumbnail
- file={file}
- isActive={isActive}
- className={className}
- showMetadata={showMetadata}
- thumbnailWidth={520}
- />
- )
- }
-
- if (isDocxFile(file)) {
- return (
- <DocxFileThumbnail
- file={file}
- isActive={isActive}
- className={className}
- showMetadata={showMetadata}
- thumbnailWidth={520}
- />
- )
- }
-
- if (isXlsxFile(file)) {
- return (
- <XlsxFileThumbnail
- file={file}
- isActive={isActive}
- className={className}
- showMetadata={showMetadata}
- thumbnailWidth={680}
- />
- )
- }
-
return (
<FileThumbnail
file={getThumbnailFile(file)}
+ source={file.url}
+ generationDelayMs={generationDelayMs}
+ thumbnailWidth={isXlsxFile(file) ? 680 : 520}
className={className}
showMetadata={showMetadata}
/>
diff --git a/apps/v4/components/file-upload-docs.tsx b/apps/v4/components/file-upload-docs.tsx
index 02bee23..c5f5fa0 100644
--- a/apps/v4/components/file-upload-docs.tsx
+++ b/apps/v4/components/file-upload-docs.tsx
@@ -9,7 +9,6 @@ import {
} from "@hugeicons/core-free-icons"
import { HugeiconsIcon } from "@hugeicons/react"
import { BorderBeam } from "border-beam"
-import { useTheme } from "next-themes"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
@@ -33,6 +32,7 @@ type AcceptedFileType = {
type FileUploadProps = {
accept?: string
acceptedFileTypes?: AcceptedFileType[]
+ borderBeamTheme?: React.ComponentProps<typeof BorderBeam>["theme"]
browseLabel?: string
className?: string
description?: string
@@ -145,6 +145,7 @@ function UploadIconCluster({
export function FileUpload({
accept,
acceptedFileTypes = ACCEPTED_FILE_TYPES,
+ borderBeamTheme = "light",
browseLabel = "Browse files",
className,
description = "PDF, DOCX, XLSX, CSV, PNG, or JPG",
@@ -157,21 +158,11 @@ export function FileUpload({
onFilesChange,
}: FileUploadProps) {
const dragDepthRef = React.useRef(0)
- const { resolvedTheme } = useTheme()
- const [mounted, setMounted] = React.useState(false)
const [isDragging, setIsDragging] = React.useState(false)
const [files, setFiles] = React.useState<FileUploadItem[]>([])
const [rejectionMessage, setRejectionMessage] = React.useState<string | null>(
null
)
- const borderBeamTheme: React.ComponentProps<typeof BorderBeam>["theme"] =
- !mounted
- ? "auto"
- : resolvedTheme === "dark"
- ? "dark"
- : resolvedTheme === "light"
- ? "light"
- : "auto"
const commitFiles = React.useCallback(
(nextFiles: FileList | File[]) => {
@@ -197,10 +188,6 @@ export function FileUpload({
[accept, multiple, onFilesAccepted, onFilesChange]
)
- React.useEffect(() => {
- setMounted(true)
- }, [])
-
React.useEffect(() => {
return () => {
files.forEach((file) => URL.revokeObjectURL(file.url))
@@ -394,7 +381,6 @@ export function FileUploadExample() {
const fileUploadUsageCode = `"use client";
import * as React from "react";
-import { useTheme } from "next-themes";
import { BorderBeam } from "border-beam";
import {
FileImageIcon,
@@ -417,6 +403,7 @@ type FileUploadItem = {
};
type FileUploadProps = {
+ borderBeamTheme?: React.ComponentProps<typeof BorderBeam>["theme"];
className?: string;
onFilesChange?: (files: FileUploadItem[]) => void;
};
@@ -488,17 +475,14 @@ function UploadIconCluster({ isDragging }: { isDragging: boolean }) {
);
}
-export function FileUpload({ className, onFilesChange }: FileUploadProps) {
+export function FileUpload({
+ borderBeamTheme = "light",
+ className,
+ onFilesChange,
+}: FileUploadProps) {
const dragDepthRef = React.useRef(0);
- const { resolvedTheme } = useTheme();
const [isDragging, setIsDragging] = React.useState(false);
const [files, setFiles] = React.useState<FileUploadItem[]>([]);
- const borderBeamTheme: React.ComponentProps<typeof BorderBeam>["theme"] =
- resolvedTheme === "dark"
- ? "dark"
- : resolvedTheme === "light"
- ? "light"
- : "auto";
const commitFiles = React.useCallback(
(nextFiles: FileList | File[]) => {
diff --git a/apps/v4/components/pdf-block-resizable-shell.tsx b/apps/v4/components/pdf-block-resizable-shell.tsx
index 215f860..08ee613 100644
--- a/apps/v4/components/pdf-block-resizable-shell.tsx
+++ b/apps/v4/components/pdf-block-resizable-shell.tsx
@@ -46,7 +46,7 @@ export function PdfBlockResizableShell({
autoSaveId={`${autoSaveId}-${direction}`}
className={cn(
heightClassName,
- "max-h-[calc(100vh-8rem)] min-h-[420px] overflow-hidden bg-background",
+ "relative max-h-[calc(100vh-8rem)] min-h-[420px] overflow-hidden bg-background",
className
)}
>
@@ -57,7 +57,7 @@ export function PdfBlockResizableShell({
>
{left}
</ResizablePanel>
- <ResizableHandle className="group z-10" withHandle />
+ <ResizableHandle className="group z-[1000]" withHandle />
<ResizablePanel
defaultSize={isDesktop ? rightDefaultSize : 38}
minSize={isDesktop ? rightMinSize : 24}
diff --git a/apps/v4/components/pdf-viewer-blocks.tsx b/apps/v4/components/pdf-viewer-blocks.tsx
index 60c7338..dbcb6ba 100644
--- a/apps/v4/components/pdf-viewer-blocks.tsx
+++ b/apps/v4/components/pdf-viewer-blocks.tsx
@@ -1,62 +1,21 @@
"use client"
import * as React from "react"
-import dynamic from "next/dynamic"
import Link from "next/link"
import { ArrowUpRight01Icon, Refresh01Icon } from "@hugeicons/core-free-icons"
import { HugeiconsIcon } from "@hugeicons/react"
import { siteConfig } from "@/lib/config"
import { Button } from "@/components/ui/button"
-
-const PreviewLoading = () => (
- <div className="grid h-[420px] place-items-center bg-muted/20 text-sm text-muted-foreground">
- Loading preview...
- </div>
-)
-
-const PdfDropzoneBlock = dynamic(
- () =>
- import("@/components/pdf-dropzone-block").then(
- (mod) => mod.PdfDropzoneBlock
- ),
- { loading: PreviewLoading, ssr: false }
-)
-const CitationsBlock = dynamic(
- () => import("@/components/citations-docs").then((mod) => mod.CitationsBlock),
- { loading: PreviewLoading, ssr: false }
-)
-const OcrBlocksBlock = dynamic(
- () =>
- import("@/components/ocr-blocks-docs").then((mod) => mod.OcrBlocksBlock),
- { loading: PreviewLoading, ssr: false }
-)
-const ESignatureBlock = dynamic(
- () =>
- import("@/components/e-signature-docs").then((mod) => mod.ESignatureBlock),
- { loading: PreviewLoading, ssr: false }
-)
-const HumanReviewBlock = dynamic(
- () =>
- import("@/components/human-review-docs").then(
- (mod) => mod.HumanReviewBlock
- ),
- { loading: PreviewLoading, ssr: false }
-)
-const DocumentSplitsBlock = dynamic(
- () =>
- import("@/components/document-splitter-docs").then(
- (mod) => mod.DocumentSplitsBlock
- ),
- { loading: PreviewLoading, ssr: false }
-)
-const XlsxDocumentSplitsBlock = dynamic(
- () =>
- import("@/components/document-splitter-docs").then(
- (mod) => mod.XlsxDocumentSplitsBlock
- ),
- { loading: PreviewLoading, ssr: false }
-)
+import { CitationsBlock } from "@/components/citations-docs"
+import {
+ DocumentSplitsBlock,
+ XlsxDocumentSplitsBlock,
+} from "@/components/document-splitter-docs"
+import { ESignatureBlock } from "@/components/e-signature-docs"
+import { HumanReviewBlock } from "@/components/human-review-docs"
+import { OcrBlocksBlock } from "@/components/ocr-blocks-docs"
+import { PdfDropzoneBlock } from "@/components/pdf-dropzone-block"
function getRegistryAddCommand(name: string) {
return `npx shadcn@latest add ${siteConfig.url}/r/${name}.json`
@@ -145,37 +104,11 @@ function PdfViewerBlockPreview({
}: {
block: (typeof pdfViewerBlocks)[number]
}) {
- const rootRef = React.useRef<HTMLElement | null>(null)
- const [isPreviewVisible, setIsPreviewVisible] = React.useState(false)
const [previewKey, setPreviewKey] = React.useState(0)
const Preview = block.component
- React.useEffect(() => {
- const root = rootRef.current
- if (!root || isPreviewVisible) return
-
- if (!("IntersectionObserver" in window)) {
- setIsPreviewVisible(true)
- return
- }
-
- const observer = new IntersectionObserver(
- ([entry]) => {
- if (entry?.isIntersecting) {
- setIsPreviewVisible(true)
- observer.disconnect()
- }
- },
- { rootMargin: "700px" }
- )
-
- observer.observe(root)
-
- return () => observer.disconnect()
- }, [isPreviewVisible])
-
return (
- <article ref={rootRef} id={block.id} className="space-y-3">
+ <article id={block.id} className="space-y-3">
<div
className={[
"flex flex-col gap-3 sm:flex-row sm:items-end",
@@ -223,7 +156,7 @@ function PdfViewerBlockPreview({
</div>
</div>
<div className="bg-background">
- {isPreviewVisible ? <Preview key={previewKey} /> : <PreviewLoading />}
+ <Preview key={previewKey} />
</div>
</div>
</article>
diff --git a/apps/v4/components/ui/csv-viewer.tsx b/apps/v4/components/ui/csv-viewer.tsx
index 0d80a05..5ea5f80 100644
--- a/apps/v4/components/ui/csv-viewer.tsx
+++ b/apps/v4/components/ui/csv-viewer.tsx
@@ -36,12 +36,29 @@ import {
} from "@/registry/new-york-v4/ui/tooltip"
const ZOOM_OPTIONS = [0.75, 1, 1.25, 1.5, 2] as const
+const GLIDE_DATA_GRID_CRITICAL_CSS = `
+.gdg-wmyidgi{position:relative;min-width:10px;min-height:10px;max-width:100%;max-height:100%;width:var(--wmyidgi-0);height:var(--wmyidgi-1);overflow:hidden;overflow:clip;direction:ltr;}
+.gdg-wmyidgi>:first-child{position:absolute;left:0;top:0;width:100%;height:100%;}
+.gdg-s1dgczr6 .dvn-scroller{overflow:var(--s1dgczr6-0);transform:translate3d(0,0,0);}
+.gdg-s1dgczr6 .dvn-hidden{visibility:hidden;}
+.gdg-s1dgczr6 .dvn-scroll-inner{display:flex;pointer-events:none;}
+.gdg-s1dgczr6 .dvn-scroll-inner>*{flex-shrink:0;}
+.gdg-s1dgczr6 .dvn-scroll-inner .dvn-spacer{flex-grow:1;}
+.gdg-s1dgczr6 .dvn-scroll-inner .dvn-stack{display:flex;flex-direction:column;}
+.gdg-s1dgczr6 .dvn-underlay>*{position:absolute;left:0;top:0;}
+.gdg-s1dgczr6 canvas{outline:none;}
+`
+
type GlideDataGridModule = typeof GlideDataGrid
type CsvViewerProps = {
className?: string
data?: string
}
+function GlideDataGridCriticalStyles() {
+ return <style>{GLIDE_DATA_GRID_CRITICAL_CSS}</style>
+}
+
function toDisplayString(value: unknown): string {
return value === null || value === undefined ? "" : String(value)
}
@@ -290,6 +307,7 @@ export function CsvViewer({ className, data }: CsvViewerProps) {
className
)}
>
+ <GlideDataGridCriticalStyles />
<div className="flex min-h-12 items-center justify-end gap-3 border-b px-3">
<TooltipProvider>
<div className="ml-auto flex shrink-0 items-center gap-1">
diff --git a/apps/v4/components/ui/file-thumbnail.tsx b/apps/v4/components/ui/file-thumbnail.tsx
index 93c9e1c..8db5ea1 100644
--- a/apps/v4/components/ui/file-thumbnail.tsx
+++ b/apps/v4/components/ui/file-thumbnail.tsx
@@ -1,38 +1,256 @@
"use client"
import * as React from "react"
+import {
+ DocxEditorViewer,
+ useDocxEditor,
+ useDocxViewerThumbnails,
+} from "@extend-ai/react-docx"
+import {
+ useXlsxViewer,
+ useXlsxViewerController,
+ useXlsxViewerThumbnails,
+ XlsxViewerProvider,
+} from "@extend-ai/react-xlsx"
import { File01Icon, FileImageIcon } from "@hugeicons/core-free-icons"
import { HugeiconsIcon } from "@hugeicons/react"
+import type * as ReactPdf from "react-pdf"
import { cn } from "@/lib/utils"
+export type ThumbnailSource = string | File | Blob
+
export type ThumbnailFile = {
name: string
type: string
- size?: string
+ size?: string | number
+ source?: ThumbnailSource
+ url?: string
}
export type FileThumbnailProps = {
- file: ThumbnailFile
+ file: ThumbnailFile | File
className?: string
previewClassName?: string
previewContent?: React.ReactNode
previewImageUrl?: string | null
+ source?: ThumbnailSource
+ thumbnailWidth?: number
+ generationDelayMs?: number
+ renderDocumentPreview?: boolean
isLoading?: boolean
hasError?: boolean
showMetadata?: boolean
}
-function isImageFile(file: ThumbnailFile) {
+type NormalizedThumbnailFile = {
+ name: string
+ type: string
+ size?: string | number
+ source?: ThumbnailSource
+ url?: string
+}
+
+type ReactPdfModule = typeof ReactPdf
+
+function isBlobLike(value: unknown): value is Blob {
+ return typeof Blob !== "undefined" && value instanceof Blob
+}
+
+function isFileLike(value: unknown): value is File {
+ return typeof File !== "undefined" && value instanceof File
+}
+
+function normalizeFile(file: ThumbnailFile | File): NormalizedThumbnailFile {
+ return {
+ name: file.name,
+ size:
+ typeof file.size === "number"
+ ? formatBytes(file.size)
+ : (file.size as string | undefined),
+ source: isFileLike(file) ? file : (file as ThumbnailFile).source,
+ type: file.type,
+ url: (file as ThumbnailFile).url,
+ }
+}
+
+function getThumbnailSource(
+ file: NormalizedThumbnailFile,
+ source?: ThumbnailSource
+): ThumbnailSource | undefined {
+ return source ?? file.source ?? file.url
+}
+
+function formatBytes(bytes: number) {
+ if (!Number.isFinite(bytes) || bytes <= 0) return undefined
+
+ const units = ["B", "KB", "MB", "GB"]
+ let value = bytes
+ let unitIndex = 0
+
+ while (value >= 1024 && unitIndex < units.length - 1) {
+ value /= 1024
+ unitIndex += 1
+ }
+
+ const formatted =
+ value >= 10 || unitIndex === 0 ? Math.round(value) : value.toFixed(1)
+ return `${formatted} ${units[unitIndex]}`
+}
+
+function isImageFile(file: NormalizedThumbnailFile) {
return file.type.startsWith("image/")
}
-function FileKindIcon({ file }: { file: ThumbnailFile }) {
+function isPdfFile(file: NormalizedThumbnailFile) {
+ return (
+ file.type === "application/pdf" || file.name.toLowerCase().endsWith(".pdf")
+ )
+}
+
+function isDocxFile(file: NormalizedThumbnailFile) {
+ return (
+ file.type ===
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
+ file.name.toLowerCase().endsWith(".docx")
+ )
+}
+
+function isXlsxFile(file: NormalizedThumbnailFile) {
+ const fileName = file.name.toLowerCase()
+
+ return (
+ file.type ===
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
+ file.type === "application/vnd.ms-excel" ||
+ fileName.endsWith(".xlsx") ||
+ fileName.endsWith(".xls")
+ )
+}
+
+function FileKindIcon({ file }: { file: NormalizedThumbnailFile }) {
const icon = isImageFile(file) ? FileImageIcon : File01Icon
return <HugeiconsIcon icon={icon} className="size-4" />
}
+function useThumbnailActivation(delayMs: number) {
+ const [isActive, setIsActive] = React.useState(delayMs <= 0)
+
+ React.useEffect(() => {
+ if (delayMs <= 0) {
+ setIsActive(true)
+ return
+ }
+
+ setIsActive(false)
+ const timeout = window.setTimeout(() => {
+ setIsActive(true)
+ }, delayMs)
+
+ return () => window.clearTimeout(timeout)
+ }, [delayMs])
+
+ return isActive
+}
+
+function useObjectUrl() {
+ const [objectUrl, setObjectUrl] = React.useState<string | null>(null)
+
+ const updateObjectUrl = React.useCallback((blob: Blob) => {
+ const nextUrl = URL.createObjectURL(blob)
+ setObjectUrl((currentUrl) => {
+ if (currentUrl) URL.revokeObjectURL(currentUrl)
+ return nextUrl
+ })
+ }, [])
+
+ React.useEffect(() => {
+ return () => {
+ if (objectUrl) URL.revokeObjectURL(objectUrl)
+ }
+ }, [objectUrl])
+
+ return { objectUrl, updateObjectUrl }
+}
+
+function useSourceObjectUrl(source: ThumbnailSource | undefined) {
+ const [objectUrl, setObjectUrl] = React.useState<string | null>(null)
+
+ React.useEffect(() => {
+ if (!source || typeof source === "string") {
+ setObjectUrl(null)
+ return
+ }
+
+ const nextUrl = URL.createObjectURL(source)
+ setObjectUrl(nextUrl)
+
+ return () => URL.revokeObjectURL(nextUrl)
+ }, [source])
+
+ if (!source) return undefined
+ return typeof source === "string" ? source : (objectUrl ?? undefined)
+}
+
+async function sourceToFile(
+ source: ThumbnailSource,
+ file: NormalizedThumbnailFile
+) {
+ if (isFileLike(source)) return source
+
+ if (isBlobLike(source)) {
+ return new File([source], file.name, {
+ type: source.type || file.type,
+ })
+ }
+
+ const response = await fetch(source)
+ if (!response.ok) {
+ throw new Error(`Failed to fetch ${file.name} (${response.status})`)
+ }
+
+ const blob = await response.blob()
+
+ return new File([blob], file.name, {
+ type: blob.type || file.type,
+ })
+}
+
+function canvasToBlob(canvas: HTMLCanvasElement | null) {
+ if (!canvas) return Promise.resolve<Blob | null>(null)
+
+ return new Promise<Blob | null>((resolve) => {
+ const blobFromDataUrl = async () => {
+ try {
+ const dataUrl = canvas.toDataURL("image/png")
+ const response = await fetch(dataUrl)
+ return await response.blob()
+ } catch {
+ return null
+ }
+ }
+
+ try {
+ if (typeof canvas.toBlob === "function") {
+ canvas.toBlob((blob) => {
+ if (blob) {
+ resolve(blob)
+ return
+ }
+
+ void blobFromDataUrl().then(resolve)
+ }, "image/png")
+ return
+ }
+
+ void blobFromDataUrl().then(resolve)
+ } catch {
+ resolve(null)
+ }
+ })
+}
+
export function FileThumbnailLoadingOverlay() {
return (
<div className="absolute inset-0 z-10 overflow-hidden bg-muted">
@@ -61,7 +279,7 @@ export function FileThumbnailLoadingOverlay() {
)
}
-export function FileThumbnail({
+function FileThumbnailShell({
file,
className,
previewClassName,
@@ -70,7 +288,16 @@ export function FileThumbnail({
isLoading = false,
hasError = false,
showMetadata = true,
-}: FileThumbnailProps) {
+}: {
+ file: NormalizedThumbnailFile
+ className?: string
+ previewClassName?: string
+ previewContent?: React.ReactNode
+ previewImageUrl?: string | null
+ isLoading?: boolean
+ hasError?: boolean
+ showMetadata?: boolean
+}) {
const imageRef = React.useRef<HTMLImageElement | null>(null)
const [isImageLoading, setIsImageLoading] = React.useState(
Boolean(previewImageUrl)
@@ -120,6 +347,7 @@ export function FileThumbnail({
ref={imageRef}
src={previewImageUrl}
alt=""
+ draggable={false}
loading="lazy"
decoding="async"
className={cn(
@@ -172,3 +400,544 @@ export function FileThumbnail({
</div>
)
}
+
+function ImageFileThumbnail({
+ className,
+ file,
+ hasError,
+ isLoading,
+ previewClassName,
+ showMetadata,
+ source,
+}: {
+ className?: string
+ file: NormalizedThumbnailFile
+ hasError?: boolean
+ isLoading?: boolean
+ previewClassName?: string
+ showMetadata?: boolean
+ source: ThumbnailSource
+}) {
+ const imageUrl = useSourceObjectUrl(source)
+
+ return (
+ <FileThumbnailShell
+ file={file}
+ previewImageUrl={imageUrl}
+ isLoading={isLoading || !imageUrl}
+ hasError={hasError}
+ className={className}
+ previewClassName={previewClassName}
+ showMetadata={showMetadata}
+ />
+ )
+}
+
+function PdfFileThumbnail({
+ file,
+ className,
+ hasError: externalHasError,
+ isActive,
+ isLoading: externalIsLoading,
+ previewClassName,
+ showMetadata,
+ source,
+ thumbnailWidth,
+}: {
+ file: NormalizedThumbnailFile
+ className?: string
+ hasError?: boolean
+ isActive: boolean
+ isLoading?: boolean
+ previewClassName?: string
+ showMetadata: boolean
+ source: ThumbnailSource
+ thumbnailWidth: number
+}) {
+ const sourceUrl = useSourceObjectUrl(source)
+ const [reactPdf, setReactPdf] = React.useState<ReactPdfModule | null>(null)
+ const [isLoading, setIsLoading] = React.useState(true)
+ const [hasError, setHasError] = React.useState(false)
+ const rootRef = React.useRef<HTMLDivElement | null>(null)
+ const { objectUrl, updateObjectUrl } = useObjectUrl()
+ const shouldRenderPdf =
+ isActive && sourceUrl && reactPdf && !objectUrl && !hasError
+ const capturePdfCanvas = React.useCallback(() => {
+ const canvas = rootRef.current?.querySelector("canvas") ?? null
+
+ void canvasToBlob(canvas).then((blob) => {
+ if (!blob) {
+ setHasError(true)
+ setIsLoading(false)
+ return
+ }
+
+ updateObjectUrl(blob)
+ setHasError(false)
+ setIsLoading(false)
+ })
+ }, [updateObjectUrl])
+
+ React.useEffect(() => {
+ setIsLoading(true)
+ setHasError(false)
+ }, [sourceUrl])
+
+ React.useEffect(() => {
+ if (!isActive || reactPdf || objectUrl) return
+
+ let isMounted = true
+ setIsLoading(true)
+ setHasError(false)
+
+ void import("react-pdf")
+ .then((module) => {
+ module.pdfjs.GlobalWorkerOptions.workerSrc = `https://unpkg.com/pdfjs-dist@${module.pdfjs.version}/legacy/build/pdf.worker.min.mjs`
+ if (isMounted) setReactPdf(module)
+ })
+ .catch(() => {
+ if (isMounted) {
+ setHasError(true)
+ setIsLoading(false)
+ }
+ })
+
+ return () => {
+ isMounted = false
+ }
+ }, [isActive, objectUrl, reactPdf])
+
+ return (
+ <>
+ <FileThumbnailShell
+ file={file}
+ previewImageUrl={objectUrl}
+ isLoading={Boolean(externalIsLoading || (isLoading && !objectUrl))}
+ hasError={Boolean(externalHasError || hasError)}
+ className={className}
+ previewClassName={previewClassName}
+ showMetadata={showMetadata}
+ />
+ {shouldRenderPdf ? (
+ <div
+ ref={rootRef}
+ aria-hidden="true"
+ className="pointer-events-none fixed top-0 left-[-10000px] w-[560px] overflow-hidden bg-white"
+ >
+ <reactPdf.Document
+ file={sourceUrl}
+ loading={null}
+ error={null}
+ noData={null}
+ onLoadError={() => {
+ setHasError(true)
+ setIsLoading(false)
+ }}
+ >
+ <reactPdf.Thumbnail
+ pageNumber={1}
+ width={thumbnailWidth}
+ loading={null}
+ error={null}
+ onRenderSuccess={() => {
+ window.requestAnimationFrame(() => {
+ capturePdfCanvas()
+ })
+ }}
+ onRenderError={() => {
+ setHasError(true)
+ setIsLoading(false)
+ }}
+ />
+ </reactPdf.Document>
+ </div>
+ ) : null}
+ </>
+ )
+}
+
+function DocxFileThumbnail({
+ file,
+ className,
+ hasError: externalHasError,
+ isActive,
+ isLoading: externalIsLoading,
+ previewClassName,
+ showMetadata,
+ source,
+ thumbnailWidth,
+}: {
+ file: NormalizedThumbnailFile
+ className?: string
+ hasError?: boolean
+ isActive: boolean
+ isLoading?: boolean
+ previewClassName?: string
+ showMetadata: boolean
+ source: ThumbnailSource
+ thumbnailWidth: number
+}) {
+ const editor = useDocxEditor({
+ initialDocumentTheme: "light",
+ initialFileName: file.name,
+ })
+ const { thumbnails } = useDocxViewerThumbnails(editor, {
+ pixelRatio: 2,
+ resolution: {
+ maxHeight: thumbnailWidth,
+ maxWidth: thumbnailWidth,
+ },
+ })
+ const firstThumbnail = thumbnails[0]
+ const [hasError, setHasError] = React.useState(false)
+ const [isReady, setIsReady] = React.useState(false)
+ const [thumbnailCanvasRef, setThumbnailCanvasRef] = React.useState<
+ ((canvas: HTMLCanvasElement | null) => void) | null
+ >(null)
+ const [thumbnailSize, setThumbnailSize] = React.useState<{
+ height: number
+ width: number
+ } | null>(null)
+ const editorRef = React.useRef(editor)
+ const importedDocxKeyRef = React.useRef<string | null>(null)
+
+ React.useEffect(() => {
+ editorRef.current = editor
+ }, [editor])
+
+ React.useEffect(() => {
+ if (!isActive) return
+
+ const docxKey =
+ typeof source === "string"
+ ? `${file.name}:${source}`
+ : `${file.name}:${source.size}:${source.type}`
+
+ if (importedDocxKeyRef.current === docxKey) return
+
+ let isCurrent = true
+ importedDocxKeyRef.current = docxKey
+ setHasError(false)
+ setIsReady(false)
+
+ async function loadDocx() {
+ try {
+ const docxFile = await sourceToFile(source, file)
+ await editorRef.current.importDocxFile(docxFile)
+ } catch {
+ if (isCurrent && importedDocxKeyRef.current === docxKey) {
+ setHasError(true)
+ }
+ }
+ }
+
+ void loadDocx()
+
+ return () => {
+ isCurrent = false
+ }
+ }, [file, isActive, source])
+
+ React.useEffect(() => {
+ if (firstThumbnail?.status === "ready") {
+ setThumbnailCanvasRef(() => firstThumbnail.canvasRef)
+ setThumbnailSize({
+ height: firstThumbnail.pixelHeightPx,
+ width: firstThumbnail.pixelWidthPx,
+ })
+ setIsReady(true)
+ } else if (firstThumbnail?.status === "error") {
+ setHasError(true)
+ } else if (!firstThumbnail) {
+ setThumbnailCanvasRef(null)
+ setThumbnailSize(null)
+ }
+ }, [firstThumbnail])
+
+ const attachThumbnailCanvas = React.useCallback(
+ (canvas: HTMLCanvasElement | null) => {
+ thumbnailCanvasRef?.(canvas)
+ },
+ [thumbnailCanvasRef]
+ )
+
+ const previewContent = thumbnailSize ? (
+ <canvas
+ ref={attachThumbnailCanvas}
+ width={thumbnailSize.width}
+ height={thumbnailSize.height}
+ className="!size-full bg-white object-cover object-top"
+ />
+ ) : null
+
+ return (
+ <>
+ <FileThumbnailShell
+ file={file}
+ previewContent={previewContent}
+ isLoading={Boolean(externalIsLoading || (!isReady && !hasError))}
+ hasError={Boolean(externalHasError || hasError)}
+ className={className}
+ previewClassName={cn("bg-white", previewClassName)}
+ showMetadata={showMetadata}
+ />
+ {isActive && !hasError && !isReady ? (
+ <div
+ aria-hidden="true"
+ className="pointer-events-none fixed top-0 left-[-10000px] w-[816px] overflow-hidden bg-white"
+ >
+ <div className="w-[816px]">
+ <DocxEditorViewer
+ editor={editor}
+ mode="read-only"
+ pageBackgroundColor="#ffffff"
+ pageGapBackgroundColor="transparent"
+ visiblePageRange={{ endPageIndex: 0, startPageIndex: 0 }}
+ pageVirtualization={{ enabled: false }}
+ deferInitialPaginationPaint={false}
+ />
+ </div>
+ </div>
+ ) : null}
+ </>
+ )
+}
+
+function XlsxFileThumbnail({
+ file,
+ className,
+ hasError: externalHasError,
+ isActive,
+ isLoading: externalIsLoading,
+ previewClassName,
+ showMetadata,
+ source,
+ thumbnailWidth,
+}: {
+ file: NormalizedThumbnailFile
+ className?: string
+ hasError?: boolean
+ isActive: boolean
+ isLoading?: boolean
+ previewClassName?: string
+ showMetadata: boolean
+ source: ThumbnailSource
+ thumbnailWidth: number
+}) {
+ const sourceUrl = useSourceObjectUrl(source)
+ const [imageUrl, setImageUrl] = React.useState<string | null>(null)
+ const [hasError, setHasError] = React.useState(false)
+
+ React.useEffect(() => {
+ setImageUrl(null)
+ setHasError(false)
+ }, [sourceUrl])
+
+ return (
+ <>
+ <FileThumbnailShell
+ file={file}
+ previewImageUrl={imageUrl}
+ isLoading={Boolean(
+ externalIsLoading || (isActive && !imageUrl && !hasError)
+ )}
+ hasError={Boolean(externalHasError || hasError)}
+ className={className}
+ previewClassName={cn(
+ "bg-white [&>img]:object-left-top",
+ previewClassName
+ )}
+ showMetadata={showMetadata}
+ />
+ {isActive && sourceUrl && !imageUrl && !hasError ? (
+ <XlsxThumbnailGenerator
+ file={file}
+ sourceUrl={sourceUrl}
+ thumbnailWidth={thumbnailWidth}
+ onError={() => setHasError(true)}
+ onImageUrl={setImageUrl}
+ />
+ ) : null}
+ </>
+ )
+}
+
+function XlsxThumbnailGenerator({
+ file,
+ onError,
+ onImageUrl,
+ sourceUrl,
+ thumbnailWidth,
+}: {
+ file: NormalizedThumbnailFile
+ onError: () => void
+ onImageUrl: (url: string) => void
+ sourceUrl: string
+ thumbnailWidth: number
+}) {
+ const controller = useXlsxViewerController(
+ React.useMemo(
+ () => ({
+ fileName: file.name,
+ readOnly: true,
+ src: sourceUrl,
+ useWorker: true,
+ }),
+ [file.name, sourceUrl]
+ )
+ )
+
+ return (
+ <XlsxViewerProvider controller={controller}>
+ <XlsxThumbnailGeneratorContent
+ thumbnailWidth={thumbnailWidth}
+ onError={onError}
+ onImageUrl={onImageUrl}
+ />
+ </XlsxViewerProvider>
+ )
+}
+
+function XlsxThumbnailGeneratorContent({
+ onError,
+ onImageUrl,
+ thumbnailWidth,
+}: {
+ onError: () => void
+ onImageUrl: (url: string) => void
+ thumbnailWidth: number
+}) {
+ const controller = useXlsxViewer()
+ const { thumbnails } = useXlsxViewerThumbnails({
+ includeHeaders: true,
+ resolution: {
+ maxHeight: thumbnailWidth,
+ maxWidth: thumbnailWidth,
+ },
+ })
+ const firstThumbnail = thumbnails[0]
+
+ React.useEffect(() => {
+ if (controller.error) {
+ onError()
+ return
+ }
+
+ if (!firstThumbnail) return
+
+ const canvas = document.createElement("canvas")
+
+ if (!firstThumbnail.paint(canvas)) return
+
+ onImageUrl(canvas.toDataURL("image/png"))
+ }, [controller.error, firstThumbnail, onError, onImageUrl])
+
+ return null
+}
+
+export function FileThumbnail({
+ file: rawFile,
+ className,
+ previewClassName,
+ previewContent,
+ previewImageUrl,
+ source: explicitSource,
+ thumbnailWidth,
+ generationDelayMs = 0,
+ renderDocumentPreview = true,
+ isLoading = false,
+ hasError = false,
+ showMetadata = true,
+}: FileThumbnailProps) {
+ const file = React.useMemo(() => normalizeFile(rawFile), [rawFile])
+ const source = getThumbnailSource(file, explicitSource)
+ const isActive = useThumbnailActivation(generationDelayMs)
+
+ if (previewImageUrl || previewContent || !renderDocumentPreview || !source) {
+ return (
+ <FileThumbnailShell
+ file={file}
+ previewImageUrl={previewImageUrl}
+ previewContent={previewContent}
+ isLoading={isLoading}
+ hasError={hasError}
+ className={className}
+ previewClassName={previewClassName}
+ showMetadata={showMetadata}
+ />
+ )
+ }
+
+ if (isImageFile(file)) {
+ return (
+ <ImageFileThumbnail
+ file={file}
+ source={source}
+ isLoading={isLoading}
+ hasError={hasError}
+ className={className}
+ previewClassName={previewClassName}
+ showMetadata={showMetadata}
+ />
+ )
+ }
+
+ if (isPdfFile(file)) {
+ return (
+ <PdfFileThumbnail
+ file={file}
+ source={source}
+ isActive={isActive}
+ isLoading={isLoading}
+ hasError={hasError}
+ className={className}
+ previewClassName={previewClassName}
+ showMetadata={showMetadata}
+ thumbnailWidth={thumbnailWidth ?? 520}
+ />
+ )
+ }
+
+ if (isDocxFile(file)) {
+ return (
+ <DocxFileThumbnail
+ file={file}
+ source={source}
+ isActive={isActive}
+ isLoading={isLoading}
+ hasError={hasError}
+ className={className}
+ previewClassName={previewClassName}
+ showMetadata={showMetadata}
+ thumbnailWidth={thumbnailWidth ?? 520}
+ />
+ )
+ }
+
+ if (isXlsxFile(file)) {
+ return (
+ <XlsxFileThumbnail
+ file={file}
+ source={source}
+ isActive={isActive}
+ isLoading={isLoading}
+ hasError={hasError}
+ className={className}
+ previewClassName={previewClassName}
+ showMetadata={showMetadata}
+ thumbnailWidth={thumbnailWidth ?? 680}
+ />
+ )
+ }
+
+ return (
+ <FileThumbnailShell
+ file={file}
+ isLoading={isLoading}
+ hasError={hasError}
+ className={className}
+ previewClassName={previewClassName}
+ showMetadata={showMetadata}
+ />
+ )
+}
diff --git a/apps/v4/components/ui/pdf-viewer.tsx b/apps/v4/components/ui/pdf-viewer.tsx
index 53546cb..cfd115a 100644
--- a/apps/v4/components/ui/pdf-viewer.tsx
+++ b/apps/v4/components/ui/pdf-viewer.tsx
@@ -98,11 +98,6 @@ const ZOOM_OPTIONS = [0.5, 0.75, 1, 1.25, 1.5, 2]
const MAX_DEVICE_PIXEL_RATIO = 2
const DEFAULT_PAGE_RENDER_BUFFER = 2
const THUMBNAIL_WIDTH = 92
-const PDF_WORKER_URL = new URL(
- "pdfjs-dist/legacy/build/pdf.worker.min.mjs",
- import.meta.url
-).toString()
-
type SearchHighlight = {
id: string
left: number
@@ -111,6 +106,36 @@ type SearchHighlight = {
height: number
}
+function getPdfWorkerUrl(pdfjsVersion: string) {
+ return `//unpkg.com/pdfjs-dist@${pdfjsVersion}/legacy/build/pdf.worker.min.mjs`
+}
+
+function PDFViewerLoadingSkeleton() {
+ return (
+ <div className="absolute inset-0 z-20 flex bg-muted/30">
+ <div className="hidden w-40 shrink-0 border-r bg-sidebar p-4 md:block">
+ <div className="mx-auto h-28 w-20 rounded-sm border 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" />
+ </div>
+ <div className="relative grid min-w-0 flex-1 place-items-center p-6">
+ <div className="w-full max-w-[360px] overflow-hidden rounded-sm border bg-background shadow-xs">
+ <div className="aspect-[8.5/11] animate-pulse bg-muted" />
+ </div>
+ <div className="absolute inset-0 grid place-items-center">
+ <div className="grid size-10 place-items-center rounded-full border bg-background/90 shadow-sm">
+ <HugeiconsIcon
+ icon={Loading03Icon}
+ className="size-4 animate-spin"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+}
+
function ToolbarTooltip({
label,
children,
@@ -409,7 +434,9 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(
void import("react-pdf")
.then((module) => {
- module.pdfjs.GlobalWorkerOptions.workerSrc = PDF_WORKER_URL
+ module.pdfjs.GlobalWorkerOptions.workerSrc = getPdfWorkerUrl(
+ module.pdfjs.version
+ )
if (mounted) {
setReactPdf(module)
@@ -876,14 +903,7 @@ export const PDFViewer = React.forwardRef<PDFViewerHandle, PDFViewerProps>(
</div>
</div>
) : null}
- {isLoading && !loadError ? (
- <div className="absolute inset-0 z-20 grid place-items-center bg-background">
- <HugeiconsIcon
- icon={Loading03Icon}
- className="size-4 animate-spin"
- />
- </div>
- ) : null}
+ {isLoading && !loadError ? <PDFViewerLoadingSkeleton /> : null}
{loadError ? (
<div className="absolute inset-0 z-20 grid place-items-center bg-background p-6 text-sm text-muted-foreground">
Unable to load the PDF preview.
diff --git a/apps/v4/components/ui/resizable.tsx b/apps/v4/components/ui/resizable.tsx
index 91ade68..e8d6f82 100644
--- a/apps/v4/components/ui/resizable.tsx
+++ b/apps/v4/components/ui/resizable.tsx
@@ -39,18 +39,18 @@ function ResizableHandle({
data-slot="resizable-handle"
className={cn(
"flex items-center justify-center",
- "relative w-px bg-border",
- "after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2",
+ "relative isolate w-px bg-border",
+ "after:absolute after:inset-y-0 after:left-1/2 after:z-20 after:w-3 after:-translate-x-1/2",
"focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:outline-hidden",
"data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full [&[data-panel-group-direction=vertical]>div]:rotate-90",
- "data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2",
+ "data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-3 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2",
className
)}
{...props}
>
{withHandle &&
(typeof withHandle === "boolean" ? (
- <div className="z-10 flex h-4 w-3 items-center justify-center rounded-xs border bg-muted dark:bg-neutral-800">
+ <div className="relative z-30 flex h-4 w-3 items-center justify-center rounded-xs border bg-muted shadow-sm dark:bg-neutral-800">
<HugeiconsIcon icon={DragDropVerticalIcon} className="size-2.5" />
</div>
) : (
diff --git a/apps/v4/content/docs/components/file-thumbnail.mdx b/apps/v4/content/docs/components/file-thumbnail.mdx
index bbf3cec..a69b888 100644
--- a/apps/v4/content/docs/components/file-thumbnail.mdx
+++ b/apps/v4/content/docs/components/file-thumbnail.mdx
@@ -4,7 +4,7 @@ description: Render compact file preview images with a skeleton, fade transition
component: true
---
-File Thumbnail gives document lists, upload queues, and attachment trays a consistent preview shell. The core component only renders an image URL, loading state, metadata, and fallback icon; generate PDF, DOCX, or XLSX preview images outside the component with the viewer libraries you already use.
+File Thumbnail gives document lists, upload queues, and attachment trays a consistent preview shell. It can render plain image previews and generate first-page thumbnails for PDF, DOCX, and XLSX files when you pass a `source`, `file.source`, or `file.url`.
<FileThumbnailDemo />
@@ -28,9 +28,16 @@ npx shadcn@latest add http://localhost:4000/r/file-thumbnail.json
<Steps className="mb-0 pt-2">
-<Step>Copy and paste the following code into your project.</Step>
+<Step>Install the package dependencies used by the thumbnail renderers.</Step>
-<FileThumbnailSource />
+```bash
+npm install @extend-ai/react-docx @extend-ai/react-xlsx @hugeicons/core-free-icons @hugeicons/react pdfjs-dist react-pdf
+```
+
+<Step>
+ Copy `components/ui/file-thumbnail.tsx` from the registry item into your
+ project.
+</Step>
<Step>Update the import paths to match your project setup.</Step>
@@ -42,19 +49,18 @@ npx shadcn@latest add http://localhost:4000/r/file-thumbnail.json
## Document Previews
-The preview can come from an image URL or a rendered preview node. For document thumbnails, the code example above shows:
+The registry install includes the renderer dependencies used by the component:
-```bash
-npm install react-pdf @extend-ai/react-docx @extend-ai/react-xlsx
-```
+- `react-pdf` and `pdfjs-dist` for first-page PDF thumbnails.
+- `@extend-ai/react-docx` for first-page DOCX thumbnails.
+- `@extend-ai/react-xlsx` for first-sheet XLSX thumbnails.
-- Use `react-pdf` to render a first-page PDF thumbnail to a hidden canvas, then pass the resulting object URL to `previewImageUrl`.
-- Use `@extend-ai/react-docx` `useDocxViewerThumbnails` to attach a first-page DOCX thumbnail canvas outside the core component.
-- Use `@extend-ai/react-xlsx` `useXlsxViewerThumbnails` to paint a sheet thumbnail to a canvas, then pass the data URL to `previewImageUrl`.
+Pass a `File`, `Blob`, or URL string through `source`, `file.source`, or `file.url`. You can still override the generated preview with `previewImageUrl` or `previewContent`.
## Useful Behaviors
-- Keeps the reusable component free of PDF, DOCX, and XLSX renderer dependencies.
+- Installs the PDF, DOCX, and XLSX renderer packages through the registry item.
+- Generates first-page thumbnails for image, PDF, DOCX, and XLSX sources.
- Shows a shimmering file-preview state while an external preview is being generated or loaded.
- Fades the preview in after it loads.
- Falls back to a compact file icon when no preview image is available or image loading fails.
@@ -64,23 +70,29 @@ npm install react-pdf @extend-ai/react-docx @extend-ai/react-xlsx
### FileThumbnail
-The FileThumbnail component renders the reusable thumbnail shell. It accepts externally generated image URLs or preview content without depending on PDF, DOCX, or XLSX renderers.
-
-| Prop | Type | Default | Required |
-| ------------------ | ----------------- | ------- | -------- |
-| `file` | `ThumbnailFile` | `-` | Yes |
-| `className` | `string` | `-` | No |
-| `previewClassName` | `string` | `-` | No |
-| `previewContent` | `React.ReactNode` | `-` | No |
-| `previewImageUrl` | `string \| null` | `-` | No |
-| `isLoading` | `boolean` | `false` | No |
-| `hasError` | `boolean` | `false` | No |
-| `showMetadata` | `boolean` | `true` | No |
+The FileThumbnail component renders the reusable thumbnail shell. It accepts externally generated previews and can generate image, PDF, DOCX, and XLSX thumbnails from a source.
+
+| Prop | Type | Default | Required |
+| ----------------------- | ------------------------ | ------- | -------- |
+| `file` | `ThumbnailFile \| File` | `-` | Yes |
+| `className` | `string` | `-` | No |
+| `previewClassName` | `string` | `-` | No |
+| `previewContent` | `React.ReactNode` | `-` | No |
+| `previewImageUrl` | `string \| null` | `-` | No |
+| `source` | `string \| File \| Blob` | `-` | No |
+| `thumbnailWidth` | `number` | `-` | No |
+| `generationDelayMs` | `number` | `0` | No |
+| `renderDocumentPreview` | `boolean` | `true` | No |
+| `isLoading` | `boolean` | `false` | No |
+| `hasError` | `boolean` | `false` | No |
+| `showMetadata` | `boolean` | `true` | No |
### ThumbnailFile
-| Prop | Type | Default | Required |
-| ------ | -------- | ------- | -------- |
-| `name` | `string` | `-` | Yes |
-| `type` | `string` | `-` | Yes |
-| `size` | `string` | `-` | No |
+| Prop | Type | Default | Required |
+| -------- | ------------------------ | ------- | -------- |
+| `name` | `string` | `-` | Yes |
+| `type` | `string` | `-` | Yes |
+| `size` | `string \| number` | `-` | No |
+| `source` | `string \| File \| Blob` | `-` | No |
+| `url` | `string` | `-` | No |
diff --git a/apps/v4/registry.json b/apps/v4/registry.json
index cfe1f18..5f60e38 100644
--- a/apps/v4/registry.json
+++ b/apps/v4/registry.json
@@ -8,7 +8,7 @@
"type": "registry:lib",
"title": "Utils",
"description": "Shared class name helper used by Extend UI registry components.",
- "dependencies": ["clsx", "tailwind-merge"],
+ "dependencies": ["clsx@^2.1.1", "tailwind-merge@^3.3.1"],
"files": [
{
"path": "registry/new-york-v4/lib/utils.ts",
@@ -36,9 +36,9 @@
"title": "Accordion",
"description": "A vertically stacked set of expandable content panels.",
"dependencies": [
- "@base-ui/react",
- "@hugeicons/core-free-icons",
- "@hugeicons/react"
+ "@base-ui/react@^1.4.1",
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6"
],
"registryDependencies": ["utils"],
"files": [
@@ -54,7 +54,7 @@
"type": "registry:ui",
"title": "Alert",
"description": "A callout for displaying contextual messages.",
- "dependencies": ["class-variance-authority"],
+ "dependencies": ["class-variance-authority@^0.7.1"],
"registryDependencies": ["utils"],
"files": [
{
@@ -83,9 +83,9 @@
"title": "Autocomplete",
"description": "An autocomplete input built on Base UI primitives.",
"dependencies": [
- "@base-ui/react",
- "@hugeicons/core-free-icons",
- "@hugeicons/react"
+ "@base-ui/react@^1.4.1",
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6"
],
"registryDependencies": ["input", "scroll-area", "utils"],
"files": [
@@ -101,7 +101,10 @@
"type": "registry:ui",
"title": "Badge",
"description": "A compact label for status, metadata, and categorization.",
- "dependencies": ["@base-ui/react", "class-variance-authority"],
+ "dependencies": [
+ "@base-ui/react@^1.4.1",
+ "class-variance-authority@^0.7.1"
+ ],
"registryDependencies": ["utils"],
"files": [
{
@@ -117,9 +120,9 @@
"title": "Breadcrumb",
"description": "Navigation breadcrumbs for page hierarchy.",
"dependencies": [
- "@base-ui/react",
- "@hugeicons/core-free-icons",
- "@hugeicons/react"
+ "@base-ui/react@^1.4.1",
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6"
],
"registryDependencies": ["utils"],
"files": [
@@ -135,7 +138,10 @@
"type": "registry:ui",
"title": "Button",
"description": "A polymorphic button primitive with variants, sizes, and loading state.",
- "dependencies": ["@base-ui/react", "class-variance-authority"],
+ "dependencies": [
+ "@base-ui/react@^1.4.1",
+ "class-variance-authority@^0.7.1"
+ ],
"registryDependencies": ["spinner", "utils"],
"files": [
{
@@ -150,7 +156,7 @@
"type": "registry:ui",
"title": "Card",
"description": "A flexible container primitive for grouped content.",
- "dependencies": ["@base-ui/react"],
+ "dependencies": ["@base-ui/react@^1.4.1"],
"registryDependencies": ["utils"],
"files": [
{
@@ -165,7 +171,7 @@
"type": "registry:ui",
"title": "Collapsible",
"description": "A disclosure primitive for expandable content.",
- "dependencies": ["@base-ui/react"],
+ "dependencies": ["@base-ui/react@^1.4.1"],
"registryDependencies": ["utils"],
"files": [
{
@@ -181,9 +187,9 @@
"title": "Command",
"description": "A command menu surface powered by cmdk.",
"dependencies": [
- "@hugeicons/core-free-icons",
- "@hugeicons/react",
- "cmdk"
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6",
+ "cmdk@^1.1.1"
],
"registryDependencies": ["dialog", "utils"],
"files": [
@@ -200,9 +206,9 @@
"title": "Dialog",
"description": "An accessible modal dialog built on Base UI.",
"dependencies": [
- "@base-ui/react",
- "@hugeicons/core-free-icons",
- "@hugeicons/react"
+ "@base-ui/react@^1.4.1",
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6"
],
"registryDependencies": ["button", "scroll-area", "utils"],
"files": [
@@ -219,9 +225,9 @@
"title": "Dropdown Menu",
"description": "A dropdown menu built on Base UI menu primitives.",
"dependencies": [
- "@base-ui/react",
- "@hugeicons/core-free-icons",
- "@hugeicons/react"
+ "@base-ui/react@^1.4.1",
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6"
],
"registryDependencies": ["utils"],
"files": [
@@ -237,7 +243,7 @@
"type": "registry:ui",
"title": "Input",
"description": "A styled text input built on Base UI.",
- "dependencies": ["@base-ui/react"],
+ "dependencies": ["@base-ui/react@^1.4.1"],
"registryDependencies": ["utils"],
"files": [
{
@@ -266,7 +272,7 @@
"type": "registry:ui",
"title": "Popover",
"description": "A floating popover built on Base UI.",
- "dependencies": ["@base-ui/react"],
+ "dependencies": ["@base-ui/react@^1.4.1"],
"registryDependencies": ["utils"],
"files": [
{
@@ -281,7 +287,7 @@
"type": "registry:ui",
"title": "Scroll Area",
"description": "A custom scroll area built on Base UI.",
- "dependencies": ["@base-ui/react"],
+ "dependencies": ["@base-ui/react@^1.4.1"],
"registryDependencies": ["utils"],
"files": [
{
@@ -297,10 +303,10 @@
"title": "Select",
"description": "A select control built on Base UI.",
"dependencies": [
- "@base-ui/react",
- "@hugeicons/core-free-icons",
- "@hugeicons/react",
- "class-variance-authority"
+ "@base-ui/react@^1.4.1",
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6",
+ "class-variance-authority@^0.7.1"
],
"registryDependencies": ["utils"],
"files": [
@@ -316,7 +322,7 @@
"type": "registry:ui",
"title": "Separator",
"description": "A visual separator built on Base UI.",
- "dependencies": ["@base-ui/react"],
+ "dependencies": ["@base-ui/react@^1.4.1"],
"registryDependencies": ["utils"],
"files": [
{
@@ -332,9 +338,9 @@
"title": "Sheet",
"description": "A side sheet built on Base UI dialog primitives.",
"dependencies": [
- "@base-ui/react",
- "@hugeicons/core-free-icons",
- "@hugeicons/react"
+ "@base-ui/react@^1.4.1",
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6"
],
"registryDependencies": ["button", "scroll-area", "utils"],
"files": [
@@ -351,10 +357,10 @@
"title": "Sidebar",
"description": "A responsive application sidebar with menu, rail, and provider primitives.",
"dependencies": [
- "@base-ui/react",
- "@hugeicons/core-free-icons",
- "@hugeicons/react",
- "class-variance-authority"
+ "@base-ui/react@^1.4.1",
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6",
+ "class-variance-authority@^0.7.1"
],
"registryDependencies": [
"button",
@@ -393,10 +399,10 @@
"title": "Sonner",
"description": "A themed toast provider for Sonner.",
"dependencies": [
- "@hugeicons/core-free-icons",
- "@hugeicons/react",
- "next-themes",
- "sonner"
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6",
+ "sonner@^2.0.0"
],
"files": [
{
@@ -411,7 +417,10 @@
"type": "registry:ui",
"title": "Spinner",
"description": "A compact loading spinner using Hugeicons.",
- "dependencies": ["@hugeicons/core-free-icons", "@hugeicons/react"],
+ "dependencies": [
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6"
+ ],
"registryDependencies": ["utils"],
"files": [
{
@@ -426,7 +435,7 @@
"type": "registry:ui",
"title": "Tabs",
"description": "A tabs primitive built on Base UI.",
- "dependencies": ["@base-ui/react"],
+ "dependencies": ["@base-ui/react@^1.4.1"],
"registryDependencies": ["utils"],
"files": [
{
@@ -441,7 +450,7 @@
"type": "registry:ui",
"title": "Tooltip",
"description": "A tooltip primitive built on Base UI.",
- "dependencies": ["@base-ui/react"],
+ "dependencies": ["@base-ui/react@^1.4.1"],
"registryDependencies": ["utils"],
"files": [
{
@@ -457,9 +466,9 @@
"title": "Resizable",
"description": "Resizable panel primitives using react-resizable-panels.",
"dependencies": [
- "@hugeicons/core-free-icons",
- "@hugeicons/react",
- "react-resizable-panels"
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6",
+ "react-resizable-panels@^3.0.5"
],
"registryDependencies": ["utils"],
"files": [
@@ -470,13 +479,37 @@
}
]
},
+ {
+ "name": "pdf-block-resizable-shell",
+ "type": "registry:component",
+ "title": "PDF Block Resizable Shell",
+ "description": "A reusable resizable left document viewer and right review panel shell for PDF-style blocks.",
+ "registryDependencies": ["resizable", "utils"],
+ "categories": ["documents", "blocks"],
+ "files": [
+ {
+ "path": "components/pdf-block-resizable-shell.tsx",
+ "type": "registry:component",
+ "target": "@components/pdf-block-resizable-shell.tsx"
+ },
+ {
+ "path": "hooks/use-media-query.ts",
+ "type": "registry:hook",
+ "target": "@hooks/use-media-query.ts"
+ }
+ ]
+ },
{
"name": "file-upload",
"type": "registry:ui",
"title": "File Upload",
"description": "A drag-and-drop file upload surface with accepted file type icons and a compact file list.",
- "dependencies": ["@hugeicons/core-free-icons", "@hugeicons/react"],
- "registryDependencies": ["file-thumbnail", "utils"],
+ "dependencies": [
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6",
+ "border-beam@^1.0.1"
+ ],
+ "registryDependencies": ["card", "file-thumbnail", "utils"],
"categories": ["documents"],
"files": [
{
@@ -490,8 +523,15 @@
"name": "file-thumbnail",
"type": "registry:ui",
"title": "File Thumbnail",
- "description": "A compact file preview thumbnail with loading, image preview, metadata, and fallback states.",
- "dependencies": ["@hugeicons/core-free-icons", "@hugeicons/react"],
+ "description": "A compact file preview thumbnail with built-in image, PDF, DOCX, and XLSX first-page thumbnail generation.",
+ "dependencies": [
+ "@extend-ai/react-docx@^0.6.5",
+ "@extend-ai/react-xlsx@^0.8.7",
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6",
+ "react-pdf@^10.4.1"
+ ],
"registryDependencies": ["utils"],
"categories": ["documents"],
"files": [
@@ -508,10 +548,10 @@
"title": "PDF Viewer",
"description": "A PDF viewer with page virtualization, thumbnails, search, zoom, rotation, upload, and page overlay hooks.",
"dependencies": [
- "@hugeicons/core-free-icons",
- "@hugeicons/react",
- "pdfjs-dist",
- "react-pdf"
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6",
+ "react-pdf@^10.4.1"
],
"registryDependencies": [
"button",
@@ -538,12 +578,18 @@
"title": "DOCX Viewer",
"description": "A DOCX viewer with upload, zoom, theme controls, cached source loading, and read-only rendering.",
"dependencies": [
- "@extend-ai/react-docx",
- "@hugeicons/core-free-icons",
- "@hugeicons/react",
- "next-themes"
+ "@extend-ai/react-docx@^0.6.5",
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6",
+ ],
+ "registryDependencies": [
+ "button",
+ "select",
+ "separator",
+ "tooltip",
+ "utils"
],
- "registryDependencies": ["button", "select", "separator", "tooltip", "utils"],
"categories": ["documents"],
"files": [
{
@@ -559,10 +605,10 @@
"title": "Excel Viewer",
"description": "An XLSX viewer with workbook loading, thumbnails, sheet tabs, upload, zoom, and theme controls.",
"dependencies": [
- "@extend-ai/react-xlsx",
- "@hugeicons/core-free-icons",
- "@hugeicons/react",
- "next-themes"
+ "@extend-ai/react-xlsx@^0.8.7",
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6",
],
"registryDependencies": [
"button",
@@ -590,13 +636,14 @@
"description": "A CSV and TSV viewer with parsing, upload, zoom, theme-aware grid rendering, and Glide Data Grid.",
"dependencies": [
"@glideapps/[email protected]",
- "@hugeicons/core-free-icons",
- "@hugeicons/react",
- "papaparse"
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6",
+ "papaparse@^5.5.3"
],
+ "devDependencies": ["@types/papaparse@^5.5.2"],
"registryDependencies": ["button", "select", "separator", "tooltip"],
"categories": ["documents"],
- "docs": "Import @glideapps/glide-data-grid/dist/index.css from your app's global stylesheet or root layout so the grid renders correctly.",
+ "docs": "The component includes the critical Glide Data Grid layout CSS. For full editor/search overlay styling, also import @glideapps/glide-data-grid/dist/index.css from your app's global stylesheet or root layout.",
"files": [
{
"path": "components/ui/csv-viewer.tsx",
@@ -610,6 +657,7 @@
"type": "registry:block",
"title": "PDF Dropzone",
"description": "A PDF-only upload dropzone that opens the dropped file in the shared PDF viewer.",
+ "dependencies": ["@hugeicons/core-free-icons@^4.1.1"],
"registryDependencies": ["file-upload", "pdf-viewer"],
"categories": ["documents", "blocks"],
"files": [
@@ -625,7 +673,12 @@
"type": "registry:block",
"title": "Citations",
"description": "A PDF evidence review block with citation cards that focus page regions.",
- "registryDependencies": ["pdf-viewer", "scroll-area", "utils"],
+ "registryDependencies": [
+ "pdf-block-resizable-shell",
+ "pdf-viewer",
+ "scroll-area",
+ "utils"
+ ],
"categories": ["documents", "blocks"],
"files": [
{
@@ -640,8 +693,16 @@
"type": "registry:block",
"title": "OCR Blocks",
"description": "A structured OCR review block with confidence cards and PDF region overlays.",
- "dependencies": ["@hugeicons/core-free-icons", "@hugeicons/react"],
- "registryDependencies": ["pdf-viewer", "scroll-area", "utils"],
+ "dependencies": [
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6"
+ ],
+ "registryDependencies": [
+ "pdf-block-resizable-shell",
+ "pdf-viewer",
+ "scroll-area",
+ "utils"
+ ],
"categories": ["documents", "blocks"],
"files": [
{
@@ -656,8 +717,20 @@
"type": "registry:block",
"title": "E-Signature",
"description": "A PDF signature review block with field overlays and signing actions.",
- "dependencies": ["@hugeicons/core-free-icons", "@hugeicons/react"],
- "registryDependencies": ["button", "pdf-viewer", "scroll-area", "utils"],
+ "dependencies": [
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6",
+ "pdf-lib@^1.17.1",
+ "signature_pad@^5.1.3"
+ ],
+ "registryDependencies": [
+ "button",
+ "dialog",
+ "pdf-block-resizable-shell",
+ "pdf-viewer",
+ "scroll-area",
+ "utils"
+ ],
"categories": ["documents", "blocks"],
"files": [
{
@@ -672,12 +745,19 @@
"type": "registry:block",
"title": "Human Review",
"description": "A human-in-the-loop extraction review block linked to source PDF evidence.",
- "dependencies": ["@hugeicons/core-free-icons", "@hugeicons/react"],
+ "dependencies": [
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6",
+ "@pierre/diffs@^1.1.22"
+ ],
"registryDependencies": [
- "badge",
"button",
+ "input",
+ "pdf-block-resizable-shell",
"pdf-viewer",
"scroll-area",
+ "tabs",
+ "tooltip",
"utils"
],
"categories": ["documents", "blocks"],
@@ -694,10 +774,18 @@
"type": "registry:block",
"title": "Document Splits",
"description": "A split-group review block for organizing pages into output documents.",
- "dependencies": ["@hugeicons/core-free-icons", "@hugeicons/react"],
+ "dependencies": [
+ "@dnd-kit/core@^6.3.1",
+ "@dnd-kit/sortable@^10.0.0",
+ "@dnd-kit/utilities@^3.2.2",
+ "@hugeicons/core-free-icons@^4.1.1",
+ "@hugeicons/react@^1.1.6"
+ ],
"registryDependencies": [
"button",
"file-thumbnail",
+ "pdf-block-resizable-shell",
+ "pdf-viewer",
"scroll-area",
"utils"
],
@@ -717,6 +805,7 @@
"description": "A workbook review block with sheet groups and the shared XLSX viewer.",
"registryDependencies": [
"file-thumbnail",
+ "pdf-block-resizable-shell",
"scroll-area",
"utils",
"xlsx-viewer"
diff --git a/apps/v4/registry/new-york-v4/blocks/citations.tsx b/apps/v4/registry/new-york-v4/blocks/citations.tsx
index 9483f5f..6b02427 100644
--- a/apps/v4/registry/new-york-v4/blocks/citations.tsx
+++ b/apps/v4/registry/new-york-v4/blocks/citations.tsx
@@ -4,6 +4,7 @@ import * as React from "react"
import { cn } from "@/lib/utils"
import { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"
+import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"
import { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"
type Point = { x: number; y: number }
@@ -117,53 +118,60 @@ export function CitationsBlock({ file }: { file?: string }) {
}, [])
return (
- <div className="grid h-[620px] min-h-[420px] overflow-hidden bg-background lg:grid-cols-[minmax(0,1fr)_360px]">
- <PDFViewer
- ref={viewerRef}
- file={file}
- defaultZoom={0.75}
- renderPageOverlay={({ pageNumber }) =>
- activeCitation.page === pageNumber ? (
- <CitationHighlight citation={activeCitation} />
- ) : null
- }
- />
- <aside className="min-h-0 border-t bg-background lg:border-t-0 lg:border-l">
- <ScrollArea className="h-full" scrollFade>
- <div className="space-y-2 p-3">
- {CITATIONS.map((citation) => {
- const isActive = citation.id === activeCitation.id
+ <PdfBlockResizableShell
+ autoSaveId="pdf-block-citations"
+ left={
+ <PDFViewer
+ ref={viewerRef}
+ file={file}
+ defaultZoom={0.75}
+ renderPageOverlay={({ pageNumber }) =>
+ activeCitation.page === pageNumber ? (
+ <CitationHighlight citation={activeCitation} />
+ ) : null
+ }
+ />
+ }
+ right={
+ <aside className="min-h-0 bg-background">
+ <ScrollArea className="h-full" scrollFade>
+ <div className="space-y-2 p-3">
+ {CITATIONS.map((citation) => {
+ const isActive = citation.id === activeCitation.id
- return (
- <button
- key={citation.id}
- type="button"
- onClick={() => focusCitation(citation)}
- onFocus={() => focusCitation(citation)}
- onMouseEnter={() => focusCitation(citation)}
- className={cn(
- "w-full rounded-lg border bg-background p-3 text-left transition-colors hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",
- isActive && "border-blue-500/60 bg-blue-500/5"
- )}
- >
- <div className="flex items-center justify-between gap-3">
- <div className="text-sm font-medium">{citation.label}</div>
- <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">
- p. {citation.page}
+ return (
+ <button
+ key={citation.id}
+ type="button"
+ onClick={() => focusCitation(citation)}
+ onFocus={() => focusCitation(citation)}
+ onMouseEnter={() => focusCitation(citation)}
+ className={cn(
+ "w-full rounded-lg border bg-background p-3 text-left transition-colors hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",
+ isActive && "border-blue-500/60 bg-blue-500/5"
+ )}
+ >
+ <div className="flex items-center justify-between gap-3">
+ <div className="text-sm font-medium">
+ {citation.label}
+ </div>
+ <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">
+ p. {citation.page}
+ </div>
</div>
- </div>
- <div className="mt-1 text-sm text-foreground/90">
- {citation.value}
- </div>
- <div className="mt-2 line-clamp-2 text-xs text-muted-foreground">
- {citation.referenceText}
- </div>
- </button>
- )
- })}
- </div>
- </ScrollArea>
- </aside>
- </div>
+ <div className="mt-1 text-sm text-foreground/90">
+ {citation.value}
+ </div>
+ <div className="mt-2 line-clamp-2 text-xs text-muted-foreground">
+ {citation.referenceText}
+ </div>
+ </button>
+ )
+ })}
+ </div>
+ </ScrollArea>
+ </aside>
+ }
+ />
)
}
diff --git a/apps/v4/registry/new-york-v4/blocks/document-splits.tsx b/apps/v4/registry/new-york-v4/blocks/document-splits.tsx
index 079ab6a..67c933f 100644
--- a/apps/v4/registry/new-york-v4/blocks/document-splits.tsx
+++ b/apps/v4/registry/new-york-v4/blocks/document-splits.tsx
@@ -1,102 +1,705 @@
"use client"
import * as React from "react"
-import { Add01Icon, Delete02Icon } from "@hugeicons/core-free-icons"
+import {
+ closestCenter,
+ DndContext,
+ DragOverlay,
+ PointerSensor,
+ useDroppable,
+ useSensor,
+ useSensors,
+ type DragEndEvent,
+ type DragOverEvent,
+ type DragStartEvent,
+} from "@dnd-kit/core"
+import {
+ arrayMove,
+ horizontalListSortingStrategy,
+ SortableContext,
+ useSortable,
+ verticalListSortingStrategy,
+} from "@dnd-kit/sortable"
+import { CSS } from "@dnd-kit/utilities"
+import {
+ Add01Icon,
+ Delete02Icon,
+ DragDropVerticalIcon,
+} from "@hugeicons/core-free-icons"
import { HugeiconsIcon } from "@hugeicons/react"
+import { cn } from "@/lib/utils"
import { FileThumbnail } from "@/components/ui/file-thumbnail"
+import { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"
+import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"
import { Button } from "@/registry/new-york-v4/ui/button"
import { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"
-type SplitGroup = {
+export type DocumentSplitPageId = `page-${number}`
+export type DocumentSplit = {
id: string
title: string
- pages: number[]
+ pages: DocumentSplitPageId[]
}
-const INITIAL_SPLITS: SplitGroup[] = [
- { id: "split-1", title: "Abstract and intro", pages: [1, 2, 3] },
- { id: "split-2", title: "Model architecture", pages: [4, 5, 6, 7] },
- { id: "split-3", title: "Training and results", pages: [8, 9, 10] },
+type PageId = DocumentSplitPageId
+type SplitGroup = DocumentSplit
+
+const THUMBNAIL_WIDTH = 72
+const THUMBNAIL_HEIGHT = 92
+
+const INITIAL_SPLITS: DocumentSplit[] = [
+ {
+ id: "split-1",
+ title: "Abstract and intro",
+ pages: ["page-1", "page-2", "page-3"],
+ },
+ {
+ id: "split-2",
+ title: "Model architecture",
+ pages: ["page-4", "page-5", "page-6", "page-7"],
+ },
+ {
+ id: "split-3",
+ title: "Training and results",
+ pages: ["page-8", "page-9", "page-10"],
+ },
]
-export function DocumentSplitsBlock() {
- const [splits, setSplits] = React.useState(INITIAL_SPLITS)
-
- const addSplit = React.useCallback(() => {
- setSplits((currentSplits) => [
- ...currentSplits,
- {
- id: `split-${currentSplits.length + 1}`,
- title: `New document ${currentSplits.length + 1}`,
- pages: [],
- },
- ])
- }, [])
+function createInitialSplits(pageCount: number) {
+ if (pageCount <= 0) return INITIAL_SPLITS
+
+ const pages = Array.from(
+ { length: pageCount },
+ (_, index) => `page-${index + 1}` as PageId
+ )
+ const chunkSize = Math.max(1, Math.ceil(pageCount / 3))
+
+ return Array.from(
+ { length: Math.ceil(pageCount / chunkSize) },
+ (_, index) => {
+ const startIndex = index * chunkSize
+ const groupPages = pages.slice(startIndex, startIndex + chunkSize)
+ const firstPage = getPageNumber(groupPages[0])
+ const lastPage = getPageNumber(groupPages[groupPages.length - 1])
+
+ return {
+ id: `split-${index + 1}`,
+ title:
+ firstPage === lastPage
+ ? `Page ${firstPage}`
+ : `Pages ${firstPage}-${lastPage}`,
+ pages: groupPages,
+ }
+ }
+ )
+}
+
+function getPageNumber(pageId: PageId) {
+ return Number(pageId.replace("page-", ""))
+}
+
+function getSplitSortableId(groupId: string) {
+ return `split-sortable-${groupId}`
+}
- const removeSplit = React.useCallback((splitId: string) => {
- setSplits((currentSplits) =>
- currentSplits.length === 1
- ? currentSplits
- : currentSplits.filter((split) => split.id !== splitId)
+function findGroupId(groups: SplitGroup[], id: string) {
+ if (groups.some((group) => group.id === id)) return id
+
+ return groups.find((group) => group.pages.includes(id as PageId))?.id ?? null
+}
+
+function getGroupPages(groups: SplitGroup[], groupId: string | null) {
+ return groups.find((group) => group.id === groupId)?.pages ?? []
+}
+
+function movePageToGroup({
+ activePageId,
+ groups,
+ insertIndex,
+ targetGroupId,
+}: {
+ activePageId: PageId
+ groups: SplitGroup[]
+ insertIndex: number
+ targetGroupId: string
+}) {
+ return groups.map((group) => {
+ const pagesWithoutActive = group.pages.filter(
+ (pageId) => pageId !== activePageId
)
- }, [])
+
+ if (group.id !== targetGroupId) {
+ return { ...group, pages: pagesWithoutActive }
+ }
+
+ const nextPages = [...pagesWithoutActive]
+ nextPages.splice(insertIndex, 0, activePageId)
+
+ return { ...group, pages: nextPages }
+ })
+}
+
+function reorderPageInGroup({
+ activePageId,
+ groups,
+ overPageId,
+}: {
+ activePageId: PageId
+ groups: SplitGroup[]
+ overPageId: PageId
+}) {
+ const groupId = findGroupId(groups, activePageId)
+ const pages = getGroupPages(groups, groupId)
+ const activeIndex = pages.indexOf(activePageId)
+ const overIndex = pages.indexOf(overPageId)
+
+ if (!groupId || activeIndex === -1 || overIndex === -1) return groups
+
+ return groups.map((group) =>
+ group.id === groupId
+ ? {
+ ...group,
+ pages: arrayMove(group.pages, activeIndex, overIndex),
+ }
+ : group
+ )
+}
+
+function createPageRangeLabel(pageIds: PageId[]) {
+ if (pageIds.length === 0) return "No pages"
+
+ return `Pages ${pageIds.map(getPageNumber).join(", ")}`
+}
+
+function SplitGroupDropzone({
+ children,
+ group,
+}: {
+ children: React.ReactNode
+ group: SplitGroup
+}) {
+ const { isOver, setNodeRef } = useDroppable({
+ id: group.id,
+ data: { type: "page-dropzone", isEmpty: group.pages.length === 0 },
+ })
return (
- <div className="flex h-[620px] min-h-[420px] flex-col overflow-hidden bg-background">
- <div className="flex items-center justify-between gap-3 border-b px-4 py-3">
- <div>
- <h3 className="text-sm font-medium">Document splits</h3>
- <p className="text-xs text-muted-foreground">
- Group extracted pages into output documents.
- </p>
+ <div
+ ref={setNodeRef}
+ className={cn(
+ "min-h-[116px] rounded-lg p-2 transition-[background-color,box-shadow]",
+ isOver && "bg-accent/30 shadow-[inset_0_0_0_1px_var(--border)]"
+ )}
+ >
+ {children}
+ </div>
+ )
+}
+
+function PageThumbnail({
+ imageUrl,
+ isActive,
+ onSelect,
+ pageId,
+}: {
+ imageUrl?: string
+ isActive: boolean
+ onSelect: (pageNumber: number) => void
+ pageId: PageId
+}) {
+ const pageNumber = getPageNumber(pageId)
+ const {
+ attributes,
+ isDragging,
+ listeners,
+ setNodeRef,
+ transform,
+ transition,
+ } = useSortable({
+ id: pageId,
+ data: { type: "page" },
+ })
+
+ return (
+ <button
+ 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",
+ isDragging && "opacity-0"
+ )}
+ style={{
+ width: THUMBNAIL_WIDTH,
+ height: THUMBNAIL_HEIGHT,
+ transform: CSS.Transform.toString(transform),
+ transition,
+ }}
+ onClick={() => onSelect(pageNumber)}
+ {...attributes}
+ {...listeners}
+ >
+ <FileThumbnail
+ file={{
+ name: `page-${pageNumber}.pdf`,
+ type: "application/pdf",
+ size: `Page ${pageNumber}`,
+ }}
+ showMetadata={false}
+ previewImageUrl={imageUrl}
+ isLoading={!imageUrl}
+ 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">
+ {pageNumber}
+ </span>
+ </button>
+ )
+}
+
+function SplitGroupCard({
+ activePage,
+ canRemove,
+ group,
+ dragHandleProps,
+ thumbnailImages,
+ onRemove,
+ onSelectPage,
+}: {
+ activePage: number
+ canRemove: boolean
+ group: SplitGroup
+ dragHandleProps?: React.ComponentPropsWithoutRef<"button">
+ thumbnailImages: Record<PageId, string>
+ onRemove: () => void
+ onSelectPage: (pageNumber: number) => void
+}) {
+ return (
+ <section className="rounded-lg border bg-background">
+ <div className="flex items-center justify-between gap-3 border-b p-3">
+ <div className="flex min-w-0 items-center gap-2">
+ <button
+ type="button"
+ aria-label={`Reorder ${group.title}`}
+ className="inline-flex size-7 shrink-0 cursor-grab items-center justify-center rounded-md text-muted-foreground hover:bg-muted active:cursor-grabbing"
+ {...dragHandleProps}
+ >
+ <HugeiconsIcon icon={DragDropVerticalIcon} className="size-4" />
+ </button>
+ <div className="min-w-0">
+ <div className="truncate text-sm font-medium">{group.title}</div>
+ <div className="mt-1 text-xs text-muted-foreground">
+ {createPageRangeLabel(group.pages)}
+ </div>
+ </div>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ <div className="rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">
+ {group.pages.length}
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={`Remove ${group.title}`}
+ disabled={!canRemove}
+ onClick={onRemove}
+ >
+ <HugeiconsIcon icon={Delete02Icon} className="size-4" />
+ </Button>
</div>
- <Button type="button" size="sm" variant="outline" onClick={addSplit}>
- <HugeiconsIcon icon={Add01Icon} className="size-4" />
- Add split
- </Button>
</div>
- <ScrollArea className="min-h-0 flex-1" scrollFade>
- <div className="space-y-3 p-4">
- {splits.map((split) => (
- <section key={split.id} className="rounded-lg border bg-background">
- <div className="flex items-center justify-between gap-3 border-b px-3 py-2">
- <div>
- <div className="text-sm font-medium">{split.title}</div>
- <div className="text-xs text-muted-foreground">
- {split.pages.length === 0
- ? "No pages"
- : `${split.pages.length} pages`}
- </div>
- </div>
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- aria-label={`Remove ${split.title}`}
- onClick={() => removeSplit(split.id)}
- >
- <HugeiconsIcon icon={Delete02Icon} className="size-4" />
- </Button>
- </div>
- <div className="flex gap-2 overflow-x-auto p-3">
- {split.pages.map((page) => (
- <FileThumbnail
- key={page}
- file={{
- name: `Page ${page}`,
- type: "application/pdf",
- size: "PDF page",
- }}
- className="h-28 w-20 shrink-0"
- showMetadata={false}
+ <SplitGroupDropzone group={group}>
+ {group.pages.length ? (
+ <SortableContext
+ items={group.pages}
+ strategy={horizontalListSortingStrategy}
+ >
+ <ScrollArea
+ className="h-[110px] w-full overflow-hidden"
+ orientation="horizontal"
+ scrollbarGutter
+ scrollbarOverflowOnly
+ viewportClassName="overflow-y-hidden"
+ >
+ <div className="flex w-max gap-2 overflow-y-hidden py-1 pr-6">
+ {group.pages.map((pageId) => (
+ <PageThumbnail
+ key={pageId}
+ pageId={pageId}
+ imageUrl={thumbnailImages[pageId]}
+ isActive={activePage === getPageNumber(pageId)}
+ onSelect={onSelectPage}
/>
))}
</div>
- </section>
- ))}
- </div>
- </ScrollArea>
+ </ScrollArea>
+ </SortableContext>
+ ) : (
+ <div className="grid h-[104px] place-items-center rounded-lg bg-muted/35 text-xs text-muted-foreground">
+ Drop pages here
+ </div>
+ )}
+ </SplitGroupDropzone>
+ </section>
+ )
+}
+
+function SortableSplitGroupCard({
+ activePage,
+ canRemove,
+ group,
+ thumbnailImages,
+ onRemove,
+ onSelectPage,
+}: {
+ activePage: number
+ canRemove: boolean
+ group: SplitGroup
+ thumbnailImages: Record<PageId, string>
+ onRemove: () => void
+ onSelectPage: (pageNumber: number) => void
+}) {
+ const {
+ attributes,
+ isDragging,
+ listeners,
+ setNodeRef,
+ transform,
+ transition,
+ } = useSortable({
+ id: getSplitSortableId(group.id),
+ data: { type: "split", groupId: group.id },
+ })
+
+ return (
+ <div
+ ref={setNodeRef}
+ className={cn(isDragging && "opacity-0")}
+ style={{
+ transform: CSS.Transform.toString(transform),
+ transition,
+ }}
+ >
+ <SplitGroupCard
+ activePage={activePage}
+ canRemove={canRemove}
+ group={group}
+ thumbnailImages={thumbnailImages}
+ dragHandleProps={{ ...attributes, ...listeners }}
+ onRemove={onRemove}
+ onSelectPage={onSelectPage}
+ />
</div>
)
}
+
+export function DocumentSplits({
+ activePage,
+ className,
+ splits,
+ thumbnailImages = {},
+ withFrameDivider = true,
+ onSelectPage,
+ onSplitsChange,
+}: {
+ activePage: number
+ className?: string
+ splits: SplitGroup[]
+ thumbnailImages?: Record<PageId, string>
+ withFrameDivider?: boolean
+ onSelectPage: (pageNumber: number) => void
+ onSplitsChange: (splits: SplitGroup[]) => void
+}) {
+ const [activePageId, setActivePageId] = React.useState<PageId | null>(null)
+ const dragStartGroupIdRef = React.useRef<string | null>(null)
+ const dragStartSplitsRef = React.useRef<SplitGroup[] | null>(null)
+ const sensors = useSensors(
+ useSensor(PointerSensor, { activationConstraint: { distance: 6 } })
+ )
+
+ const handleDragStart = React.useCallback(
+ (event: DragStartEvent) => {
+ if (event.active.data.current?.type !== "page") {
+ dragStartGroupIdRef.current = null
+ dragStartSplitsRef.current = null
+ setActivePageId(null)
+ return
+ }
+
+ const pageId = String(event.active.id) as PageId
+ dragStartGroupIdRef.current = findGroupId(splits, pageId)
+ dragStartSplitsRef.current = splits
+ setActivePageId(pageId)
+ },
+ [splits]
+ )
+
+ const handleDragOver = React.useCallback(
+ (event: DragOverEvent) => {
+ if (event.active.data.current?.type !== "page" || !event.over) return
+
+ const pageId = String(event.active.id) as PageId
+ const overId = String(event.over.id)
+
+ const sourceGroupId = findGroupId(splits, pageId)
+ const targetGroupId = findGroupId(splits, overId)
+
+ if (!sourceGroupId || !targetGroupId || sourceGroupId === targetGroupId) {
+ return
+ }
+
+ const targetPages = getGroupPages(splits, targetGroupId)
+ const overIndex = targetPages.indexOf(overId as PageId)
+ const insertIndex = overIndex === -1 ? targetPages.length : overIndex
+
+ onSplitsChange(
+ movePageToGroup({
+ activePageId: pageId,
+ groups: splits,
+ insertIndex,
+ targetGroupId,
+ })
+ )
+ },
+ [onSplitsChange, splits]
+ )
+
+ const handleDragEnd = React.useCallback(
+ (event: DragEndEvent) => {
+ if (event.active.data.current?.type === "split" && event.over) {
+ const activeGroupId = event.active.data.current.groupId
+ const overGroupId = event.over.data.current?.groupId
+
+ const activeIndex = splits.findIndex(
+ (group) => group.id === activeGroupId
+ )
+ const overIndex = splits.findIndex((group) => group.id === overGroupId)
+
+ if (activeIndex !== -1 && overIndex !== -1) {
+ onSplitsChange(arrayMove(splits, activeIndex, overIndex))
+ }
+
+ dragStartGroupIdRef.current = null
+ dragStartSplitsRef.current = null
+ setActivePageId(null)
+ return
+ }
+
+ if (event.active.data.current?.type !== "page" || !event.over) {
+ dragStartGroupIdRef.current = null
+ dragStartSplitsRef.current = null
+ setActivePageId(null)
+ return
+ }
+
+ const pageId = String(event.active.id) as PageId
+ const overId = String(event.over.id) as PageId
+ const overGroupId = findGroupId(splits, overId)
+
+ if (dragStartGroupIdRef.current === overGroupId) {
+ onSplitsChange(
+ reorderPageInGroup({
+ activePageId: pageId,
+ groups: splits,
+ overPageId: overId,
+ })
+ )
+ }
+
+ dragStartGroupIdRef.current = null
+ dragStartSplitsRef.current = null
+ setActivePageId(null)
+ },
+ [onSplitsChange, splits]
+ )
+
+ const handleDragCancel = React.useCallback(() => {
+ if (dragStartSplitsRef.current) {
+ onSplitsChange(dragStartSplitsRef.current)
+ }
+
+ dragStartSplitsRef.current = null
+ dragStartGroupIdRef.current = null
+ setActivePageId(null)
+ }, [onSplitsChange])
+
+ return (
+ <aside
+ className={cn(
+ "flex h-full min-h-0 flex-col bg-muted/20",
+ withFrameDivider && "border-t md:border-t-0 md:border-l",
+ className
+ )}
+ >
+ <div className="flex min-h-12 items-center justify-end gap-3 border-b bg-background px-3">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ onSplitsChange([
+ ...splits,
+ {
+ id: `split-${Date.now()}`,
+ title: `Split ${splits.length + 1}`,
+ pages: [],
+ },
+ ])
+ }
+ >
+ <HugeiconsIcon icon={Add01Icon} className="size-4" />
+ Add split
+ </Button>
+ </div>
+ <DndContext
+ id="document-splits-dnd"
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragStart={handleDragStart}
+ onDragOver={handleDragOver}
+ onDragEnd={handleDragEnd}
+ onDragCancel={handleDragCancel}
+ >
+ <ScrollArea className="min-h-0 flex-1" scrollFade>
+ <SortableContext
+ items={splits.map((group) => getSplitSortableId(group.id))}
+ strategy={verticalListSortingStrategy}
+ >
+ <div className="space-y-3 p-3">
+ {splits.map((group) => (
+ <SortableSplitGroupCard
+ key={group.id}
+ activePage={
+ activePageId ? getPageNumber(activePageId) : activePage
+ }
+ canRemove={splits.length > 1}
+ group={group}
+ thumbnailImages={thumbnailImages}
+ onRemove={() => {
+ if (splits.length <= 1) return
+ onSplitsChange(
+ splits.filter((split) => split.id !== group.id)
+ )
+ }}
+ onSelectPage={onSelectPage}
+ />
+ ))}
+ </div>
+ </SortableContext>
+ </ScrollArea>
+ <DragOverlay>
+ {activePageId ? (
+ <div
+ className="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" }}
+ showMetadata={false}
+ previewImageUrl={thumbnailImages[activePageId]}
+ isLoading={!thumbnailImages[activePageId]}
+ previewClassName="h-full aspect-auto"
+ className="size-full rounded-[inherit] border-0"
+ />
+ </div>
+ ) : null}
+ </DragOverlay>
+ </DndContext>
+ </aside>
+ )
+}
+
+export function DocumentSplitsBlock({
+ file,
+ thumbnailImages,
+}: {
+ file?: string
+ thumbnailImages?: 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)
+ const uploadedPdfUrlRef = React.useRef<string | null>(null)
+
+ React.useEffect(() => {
+ setPdfFile(file)
+ setActivePage(1)
+ }, [file])
+
+ React.useEffect(() => {
+ return () => {
+ if (uploadedPdfUrlRef.current) {
+ URL.revokeObjectURL(uploadedPdfUrlRef.current)
+ }
+ }
+ }, [])
+
+ const handlePdfUpload = React.useCallback((uploadedFile: File) => {
+ const nextUrl = URL.createObjectURL(uploadedFile)
+
+ if (uploadedPdfUrlRef.current) {
+ URL.revokeObjectURL(uploadedPdfUrlRef.current)
+ }
+
+ uploadedPdfUrlRef.current = nextUrl
+ setPdfFile(nextUrl)
+ setActivePage(1)
+ }, [])
+
+ const handleDocumentLoadSuccess = React.useCallback((pageCount: number) => {
+ setSplits(createInitialSplits(pageCount))
+ }, [])
+
+ const handleSelectPage = React.useCallback((pageNumber: number) => {
+ setActivePage(pageNumber)
+ viewerRef.current?.scrollToPage(pageNumber, {
+ block: "start",
+ behavior: "auto",
+ })
+ }, [])
+
+ return (
+ <PdfBlockResizableShell
+ autoSaveId="pdf-block-document-splits"
+ heightClassName="h-[720px]"
+ rightDefaultSize={50}
+ rightMaxSize={66}
+ rightMinSize={30}
+ left={
+ <PDFViewer
+ ref={viewerRef}
+ file={pdfFile}
+ defaultZoom={0.75}
+ onActivePageChange={setActivePage}
+ onDocumentLoadSuccess={handleDocumentLoadSuccess}
+ onPdfUpload={handlePdfUpload}
+ />
+ }
+ right={
+ <div className="flex min-h-0 flex-col bg-background">
+ <div className="border-b px-4 py-3">
+ <h3 className="text-sm font-medium">Document splits</h3>
+ <p className="text-xs text-muted-foreground">
+ Drag pages between split groups and reorder output documents.
+ </p>
+ </div>
+ <DocumentSplits
+ activePage={activePage}
+ className="min-h-0 flex-1"
+ splits={splits}
+ thumbnailImages={thumbnailImages}
+ withFrameDivider={false}
+ onSelectPage={handleSelectPage}
+ onSplitsChange={setSplits}
+ />
+ </div>
+ }
+ />
+ )
+}
diff --git a/apps/v4/registry/new-york-v4/blocks/e-signature.tsx b/apps/v4/registry/new-york-v4/blocks/e-signature.tsx
index 5fb1cbf..15ec163 100644
--- a/apps/v4/registry/new-york-v4/blocks/e-signature.tsx
+++ b/apps/v4/registry/new-york-v4/blocks/e-signature.tsx
@@ -7,128 +7,663 @@ import {
Pen01Icon,
} from "@hugeicons/core-free-icons"
import { HugeiconsIcon } from "@hugeicons/react"
+import type SignaturePad from "signature_pad"
import { cn } from "@/lib/utils"
import { PDFViewer } from "@/components/ui/pdf-viewer"
+import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"
import { Button } from "@/registry/new-york-v4/ui/button"
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogPanel,
+ DialogTitle,
+} from "@/registry/new-york-v4/ui/dialog"
import { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"
+type BoundingBox = {
+ x: number
+ y: number
+ width: number
+ height: number
+}
+
type SignatureField = {
id: string
label: string
page: number
- bbox: { x: number; y: number; width: number; height: number }
- signed?: boolean
+ bbox: BoundingBox
+ imageDataUrl?: string
}
const PAGE_WIDTH = 612
const PAGE_HEIGHT = 792
-const INITIAL_FIELDS: SignatureField[] = [
- {
- id: "signature-1",
- label: "Signature",
- page: 1,
- bbox: { x: 300, y: 504, width: 250, height: 58 },
- },
-]
-
-function bboxToStyle(field: SignatureField) {
+const DEFAULT_ZOOM = 0.75
+const SIGNATURE_PAD_PADDING = 8
+const DEFAULT_SIGNATURE_ASPECT_RATIO = 3
+
+const INITIAL_FIELD: SignatureField = {
+ id: "signature-1",
+ label: "Signature",
+ page: 1,
+ bbox: { x: 300, y: 504, width: 250, height: 58 },
+}
+
+function bboxToStyle(bbox: BoundingBox): React.CSSProperties {
return {
- left: `${(field.bbox.x / PAGE_WIDTH) * 100}%`,
- top: `${(field.bbox.y / PAGE_HEIGHT) * 100}%`,
- width: `${(field.bbox.width / PAGE_WIDTH) * 100}%`,
- height: `${(field.bbox.height / PAGE_HEIGHT) * 100}%`,
+ left: `${(bbox.x / PAGE_WIDTH) * 100}%`,
+ top: `${(bbox.y / PAGE_HEIGHT) * 100}%`,
+ width: `${(bbox.width / PAGE_WIDTH) * 100}%`,
+ height: `${(bbox.height / PAGE_HEIGHT) * 100}%`,
}
}
-export function ESignatureBlock({ file }: { file?: string }) {
- const [fields, setFields] = React.useState(INITIAL_FIELDS)
- const activeField = fields[0]
+function getSignatureAspectRatio(bbox?: BoundingBox): number {
+ if (!bbox || bbox.width <= 0 || bbox.height <= 0) {
+ return DEFAULT_SIGNATURE_ASPECT_RATIO
+ }
+
+ return bbox.width / bbox.height
+}
+
+function getSignatureGuideSize({
+ containerWidth,
+ containerHeight,
+ aspectRatio,
+}: {
+ containerWidth: number
+ containerHeight: number
+ aspectRatio: number
+}): { width: number; height: number } {
+ const maxWidth = Math.max(containerWidth - SIGNATURE_PAD_PADDING * 2, 1)
+ const maxHeight = Math.max(containerHeight - SIGNATURE_PAD_PADDING * 2, 1)
+
+ if (maxWidth / maxHeight > aspectRatio) {
+ const height = maxHeight
+ return {
+ width: height * aspectRatio,
+ height,
+ }
+ }
+
+ const width = maxWidth
+ return {
+ width,
+ height: width / aspectRatio,
+ }
+}
+
+function getCroppedSignatureDataUrl(canvas: HTMLCanvasElement): string {
+ const context = canvas.getContext("2d")
+ if (!context) {
+ return canvas.toDataURL("image/png")
+ }
+
+ const { width, height } = canvas
+ const imageData = context.getImageData(0, 0, width, height)
+ const { data } = imageData
+ let minX = width
+ let minY = height
+ let maxX = -1
+ let maxY = -1
+
+ for (let y = 0; y < height; y += 1) {
+ for (let x = 0; x < width; x += 1) {
+ const alpha = data[(y * width + x) * 4 + 3]
+ if (alpha === 0) continue
+
+ minX = Math.min(minX, x)
+ minY = Math.min(minY, y)
+ maxX = Math.max(maxX, x)
+ maxY = Math.max(maxY, y)
+ }
+ }
+
+ if (maxX < minX || maxY < minY) {
+ return canvas.toDataURL("image/png")
+ }
+
+ const croppedWidth = maxX - minX + 1
+ const croppedHeight = maxY - minY + 1
+ const croppedCanvas = document.createElement("canvas")
+ croppedCanvas.width = croppedWidth
+ croppedCanvas.height = croppedHeight
+
+ const croppedContext = croppedCanvas.getContext("2d")
+ if (!croppedContext) {
+ return canvas.toDataURL("image/png")
+ }
+
+ croppedContext.drawImage(
+ canvas,
+ minX,
+ minY,
+ croppedWidth,
+ croppedHeight,
+ 0,
+ 0,
+ croppedWidth,
+ croppedHeight
+ )
+
+ return croppedCanvas.toDataURL("image/png")
+}
+
+function SignatureDialog({
+ open,
+ fieldBbox,
+ initialValue,
+ onOpenChange,
+ onConfirm,
+}: {
+ open: boolean
+ fieldBbox: BoundingBox
+ initialValue?: string
+ onOpenChange: (open: boolean) => void
+ onConfirm: (value: string) => void
+}) {
+ const canvasContainerRef = React.useRef<HTMLDivElement>(null)
+ const canvasRef = React.useRef<HTMLCanvasElement>(null)
+ const signaturePadRef = React.useRef<SignaturePad | null>(null)
+ const [isReady, setIsReady] = React.useState(false)
+ const [hasSignature, setHasSignature] = React.useState(false)
+ const [guideSize, setGuideSize] = React.useState<{
+ width: number
+ height: number
+ } | null>(null)
+ const signatureAspectRatio = React.useMemo(
+ () => getSignatureAspectRatio(fieldBbox),
+ [fieldBbox]
+ )
+
+ React.useEffect(() => {
+ if (!open) {
+ setGuideSize(null)
+ return
+ }
+
+ let frameId = 0
+ let resizeObserver: ResizeObserver | null = null
+
+ const updateGuideSize = (container?: HTMLDivElement | null) => {
+ const currentContainer = container ?? canvasContainerRef.current
+ if (
+ !currentContainer ||
+ currentContainer.clientWidth <= 0 ||
+ currentContainer.clientHeight <= 0
+ ) {
+ return false
+ }
+
+ const nextSize = getSignatureGuideSize({
+ containerWidth: currentContainer.clientWidth,
+ containerHeight: currentContainer.clientHeight,
+ aspectRatio: signatureAspectRatio,
+ })
+
+ setGuideSize((previousSize) => {
+ if (
+ previousSize &&
+ Math.abs(previousSize.width - nextSize.width) < 0.5 &&
+ Math.abs(previousSize.height - nextSize.height) < 0.5
+ ) {
+ return previousSize
+ }
+
+ return nextSize
+ })
+
+ return true
+ }
+
+ const connect = () => {
+ const container = canvasContainerRef.current
+ if (!updateGuideSize(container)) {
+ frameId = window.requestAnimationFrame(connect)
+ return
+ }
+
+ if (container) {
+ resizeObserver = new ResizeObserver(() => {
+ updateGuideSize(container)
+ })
+ resizeObserver.observe(container)
+ }
+ }
+
+ connect()
+
+ return () => {
+ window.cancelAnimationFrame(frameId)
+ resizeObserver?.disconnect()
+ }
+ }, [open, signatureAspectRatio])
+
+ React.useEffect(() => {
+ if (!open || !guideSize || guideSize.width <= 1 || guideSize.height <= 1) {
+ signaturePadRef.current?.off()
+ signaturePadRef.current = null
+ setIsReady(false)
+ if (!open) {
+ setHasSignature(false)
+ }
+ return
+ }
+
+ let cancelled = false
+ let resizeObserver: ResizeObserver | null = null
+
+ const syncCanvasSize = (canvas: HTMLCanvasElement) => {
+ const width = Math.max(canvas.offsetWidth, 1)
+ const height = Math.max(canvas.offsetHeight, 1)
+ const ratio = Math.max(window.devicePixelRatio || 1, 1)
+
+ canvas.style.width = `${width}px`
+ canvas.style.height = `${height}px`
+ canvas.width = Math.floor(width * ratio)
+ canvas.height = Math.floor(height * ratio)
+ const context = canvas.getContext("2d")
+ context?.setTransform(1, 0, 0, 1, 0, 0)
+ context?.scale(ratio, ratio)
+
+ return { width, height, ratio }
+ }
+
+ const initialize = async () => {
+ const canvas = canvasRef.current
+ if (!canvas) return
+
+ const { default: SignaturePadConstructor } = await import("signature_pad")
+ if (cancelled) return
+
+ const signaturePad = new SignaturePadConstructor(canvas, {
+ minWidth: 1.4,
+ maxWidth: 2.8,
+ penColor: "rgb(15, 23, 42)",
+ })
+
+ signaturePadRef.current = signaturePad
+
+ const loadSignature = async (dataUrl?: string) => {
+ const size = syncCanvasSize(canvas)
- const toggleSigned = React.useCallback((fieldId: string) => {
- setFields((currentFields) =>
- currentFields.map((field) =>
- field.id === fieldId ? { ...field, signed: !field.signed } : field
- )
- )
- }, [])
+ if (dataUrl) {
+ await signaturePad.fromDataURL(dataUrl, size)
+ setHasSignature(true)
+ return
+ }
+
+ signaturePad.clear()
+ setHasSignature(false)
+ }
+
+ await loadSignature(initialValue)
+ if (cancelled) return
+
+ signaturePad.addEventListener("endStroke", () => {
+ setHasSignature(true)
+ })
+
+ resizeObserver = new ResizeObserver(() => {
+ const currentCanvas = canvasRef.current
+ const currentSignaturePad = signaturePadRef.current
+ if (!currentCanvas || !currentSignaturePad) return
+
+ const previousSignature = currentSignaturePad.isEmpty()
+ ? undefined
+ : currentSignaturePad.toDataURL("image/png")
+ void loadSignature(previousSignature)
+ })
+ resizeObserver.observe(canvas)
+ setIsReady(true)
+ }
+
+ const animationFrame = window.requestAnimationFrame(() => {
+ void initialize()
+ })
+
+ return () => {
+ cancelled = true
+ window.cancelAnimationFrame(animationFrame)
+ resizeObserver?.disconnect()
+ signaturePadRef.current?.off()
+ signaturePadRef.current = null
+ setIsReady(false)
+ }
+ }, [open, guideSize, initialValue])
return (
- <div className="grid h-[620px] min-h-[420px] overflow-hidden bg-background lg:grid-cols-[minmax(0,1fr)_340px]">
- <PDFViewer
- file={file}
- defaultZoom={0.75}
- renderPageOverlay={({ pageNumber }) =>
- fields
- .filter((field) => field.page === pageNumber)
- .map((field) => (
- <button
- key={field.id}
- type="button"
- onClick={() => toggleSigned(field.id)}
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-xl">
+ <DialogHeader>
+ <DialogTitle>Add signature</DialogTitle>
+ <DialogDescription>
+ Draw a signature to place it into the selected PDF field.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogPanel>
+ <div className="rounded-xl border bg-muted/30 p-3">
+ <div
+ ref={canvasContainerRef}
+ className="flex h-56 w-full items-center justify-center overflow-hidden rounded-lg border bg-muted/40 p-2"
+ >
+ <div
className={cn(
- "absolute z-10 flex items-center justify-center rounded border border-dashed text-xs font-medium transition-colors",
- field.signed
- ? "border-emerald-500 bg-emerald-500/10 text-emerald-700"
- : "border-blue-500 bg-blue-500/10 text-blue-700"
+ "relative overflow-hidden rounded-md border border-dashed border-slate-400 bg-white shadow-xs",
+ isReady ? "cursor-crosshair" : "cursor-wait"
)}
- style={bboxToStyle(field)}
+ style={{
+ width: guideSize ? `${guideSize.width}px` : undefined,
+ height: guideSize ? `${guideSize.height}px` : undefined,
+ opacity: guideSize ? 1 : 0,
+ }}
>
- {field.signed ? "Signed" : field.label}
- </button>
- ))
- }
- />
- <aside className="min-h-0 border-t bg-background lg:border-t-0 lg:border-l">
- <ScrollArea className="h-full" scrollFade>
- <div className="space-y-4 p-4">
- <div className="space-y-1">
- <h3 className="text-sm font-medium">Signature fields</h3>
- <p className="text-xs text-muted-foreground">
- Review fields, collect signatures, and export a signed PDF.
- </p>
+ <canvas
+ ref={canvasRef}
+ className={cn(
+ "absolute inset-0 size-full touch-none",
+ !isReady && "pointer-events-none"
+ )}
+ style={{ touchAction: "none" }}
+ />
+ </div>
</div>
- <button
+ </div>
+ </DialogPanel>
+ <DialogFooter className="sm:justify-between">
+ <Button
+ type="button"
+ variant="outline"
+ disabled={!isReady}
+ onClick={() => {
+ signaturePadRef.current?.clear()
+ setHasSignature(false)
+ }}
+ >
+ Clear
+ </Button>
+ <div className="flex flex-col-reverse gap-2 sm:flex-row">
+ <Button
type="button"
- onClick={() => toggleSigned(activeField.id)}
- 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",
- activeField.signed && "border-emerald-500/60 bg-emerald-500/5"
- )}
+ variant="outline"
+ onClick={() => onOpenChange(false)}
>
- <div className="flex items-center gap-3">
- <div className="grid size-9 place-items-center rounded-md bg-blue-500/10 text-blue-600">
- <HugeiconsIcon icon={Pen01Icon} className="size-4" />
- </div>
- <div className="min-w-0 flex-1">
- <div className="text-sm font-medium">{activeField.label}</div>
- <div className="text-xs text-muted-foreground">
- Page {activeField.page}
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ disabled={!isReady || !hasSignature}
+ onClick={() => {
+ const canvas = canvasRef.current
+ if (!canvas) return
+
+ onConfirm(getCroppedSignatureDataUrl(canvas))
+ onOpenChange(false)
+ }}
+ >
+ Confirm
+ </Button>
+ </div>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function SignatureFieldOverlay({
+ field,
+ onOpen,
+}: {
+ field: SignatureField
+ onOpen: () => void
+}) {
+ return (
+ <button
+ type="button"
+ className={cn(
+ "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",
+ field.imageDataUrl
+ ? "bg-transparent shadow-none hover:bg-blue-500/5"
+ : "bg-blue-500/10 hover:bg-blue-500/15"
+ )}
+ style={bboxToStyle(field.bbox)}
+ onClick={onOpen}
+ >
+ {field.imageDataUrl ? (
+ <img
+ src={field.imageDataUrl}
+ alt=""
+ className="size-full object-contain"
+ draggable={false}
+ />
+ ) : (
+ <span className="flex size-full items-center justify-center gap-1.5 px-2 text-[11px] font-medium text-blue-700 dark:text-blue-300">
+ <HugeiconsIcon icon={Pen01Icon} className="size-3.5" />
+ Signature
+ </span>
+ )}
+ </button>
+ )
+}
+
+async function downloadSignedPdf({
+ file,
+ field,
+}: {
+ file: string
+ field: SignatureField
+}) {
+ const { PDFDocument } = await import("pdf-lib")
+ const existingPdfBytes = await fetch(file).then((response) =>
+ response.arrayBuffer()
+ )
+ const pdfDocument = await PDFDocument.load(existingPdfBytes)
+ const page = pdfDocument.getPage(field.page - 1)
+
+ if (field.imageDataUrl) {
+ const signatureImage = await pdfDocument.embedPng(field.imageDataUrl)
+ const { width: pageWidth, height: pageHeight } = page.getSize()
+ const scaleX = pageWidth / PAGE_WIDTH
+ const scaleY = pageHeight / PAGE_HEIGHT
+ const fieldWidth = field.bbox.width * scaleX
+ const fieldHeight = field.bbox.height * scaleY
+ const imageAspectRatio = signatureImage.width / signatureImage.height
+ const fieldAspectRatio = fieldWidth / fieldHeight
+ const drawWidth =
+ fieldAspectRatio > imageAspectRatio
+ ? fieldHeight * imageAspectRatio
+ : fieldWidth
+ const drawHeight =
+ fieldAspectRatio > imageAspectRatio
+ ? fieldHeight
+ : fieldWidth / imageAspectRatio
+ const fieldX = field.bbox.x * scaleX
+ const fieldY = pageHeight - (field.bbox.y + field.bbox.height) * scaleY
+
+ page.drawImage(signatureImage, {
+ x: fieldX + (fieldWidth - drawWidth) / 2,
+ y: fieldY + (fieldHeight - drawHeight) / 2,
+ width: drawWidth,
+ height: drawHeight,
+ })
+ }
+
+ const bytes = await pdfDocument.save()
+ const blob = new Blob([new Uint8Array(bytes)], { type: "application/pdf" })
+ const url = URL.createObjectURL(blob)
+ const anchor = document.createElement("a")
+ anchor.href = url
+ anchor.download = "signed-document.pdf"
+ anchor.click()
+ URL.revokeObjectURL(url)
+}
+
+function SignatureFieldsPanel({
+ field,
+ className,
+ canExport,
+ isDownloading,
+ onSign,
+ onClear,
+ onDownload,
+}: {
+ field: SignatureField
+ className?: string
+ canExport: boolean
+ isDownloading: boolean
+ onSign: () => void
+ onClear: () => void
+ onDownload: () => void
+}) {
+ return (
+ <aside className={cn("flex min-h-0 flex-col bg-background", className)}>
+ <ScrollArea className="min-h-0 flex-1" scrollFade>
+ <div className="space-y-4 p-4">
+ <div className="space-y-1">
+ <h3 className="text-sm font-medium">Signature fields</h3>
+ <p className="text-xs text-muted-foreground">
+ Review fields, collect signatures, and export a signed PDF.
+ </p>
+ </div>
+ <div className="rounded-lg border bg-background p-3">
+ <div className="flex items-start gap-3">
+ <div className="grid size-9 shrink-0 place-items-center rounded-md bg-blue-500/10 text-blue-600 dark:text-blue-300">
+ <HugeiconsIcon icon={FilePenIcon} className="size-4" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center justify-between gap-2">
+ <div className="text-sm font-medium">{field.label}</div>
+ <div
+ className={cn(
+ "rounded-full px-2 py-0.5 text-xs",
+ field.imageDataUrl
+ ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-300"
+ : "bg-muted text-muted-foreground"
+ )}
+ >
+ {field.imageDataUrl ? "Signed" : "Unsigned"}
</div>
</div>
- <div className="rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">
- {activeField.signed ? "Signed" : "Pending"}
+ <div className="mt-2 text-xs text-muted-foreground">
+ {Math.round(field.bbox.width)} x{" "}
+ {Math.round(field.bbox.height)} on page {field.page}
+ </div>
+ <div className="mt-3 flex gap-2">
+ <Button
+ type="button"
+ size="sm"
+ variant={field.imageDataUrl ? "outline" : "default"}
+ className="flex-1"
+ onClick={onSign}
+ >
+ <HugeiconsIcon icon={Pen01Icon} className="size-4" />
+ {field.imageDataUrl ? "Edit" : "Sign"}
+ </Button>
+ {field.imageDataUrl ? (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={onClear}
+ >
+ Clear
+ </Button>
+ ) : null}
</div>
</div>
- </button>
- <div className="flex gap-2">
+ </div>
+ </div>
+ <Button
+ type="button"
+ className="w-full"
+ disabled={!canExport || isDownloading}
+ onClick={onDownload}
+ >
+ <HugeiconsIcon icon={Download01Icon} className="size-4" />
+ {isDownloading ? "Exporting..." : "Export signed PDF"}
+ </Button>
+ </div>
+ </ScrollArea>
+ </aside>
+ )
+}
+
+export function ESignatureBlock({ file }: { file?: string }) {
+ const [field, setField] = React.useState<SignatureField>(INITIAL_FIELD)
+ const [dialogOpen, setDialogOpen] = React.useState(false)
+ const [isDownloading, setIsDownloading] = React.useState(false)
+
+ const handleDownload = React.useCallback(async () => {
+ if (!file || !field.imageDataUrl) return
+
+ setIsDownloading(true)
+ try {
+ await downloadSignedPdf({ file, field })
+ } finally {
+ setIsDownloading(false)
+ }
+ }, [field, file])
+
+ return (
+ <>
+ <PdfBlockResizableShell
+ autoSaveId="pdf-block-e-signature"
+ left={
+ <PDFViewer
+ file={file}
+ defaultZoom={DEFAULT_ZOOM}
+ pageWidth={PAGE_WIDTH}
+ pageHeight={PAGE_HEIGHT}
+ toolbarActions={
<Button
type="button"
+ size="sm"
variant="outline"
- className="flex-1"
- onClick={() => toggleSigned(activeField.id)}
+ disabled={!file || !field.imageDataUrl || isDownloading}
+ onClick={handleDownload}
>
- <HugeiconsIcon icon={FilePenIcon} className="size-4" />
- {activeField.signed ? "Clear" : "Sign"}
- </Button>
- <Button type="button" className="flex-1">
<HugeiconsIcon icon={Download01Icon} className="size-4" />
- Export
+ Download
</Button>
- </div>
- </div>
- </ScrollArea>
- </aside>
- </div>
+ }
+ renderPageOverlay={({ pageNumber }) =>
+ pageNumber === field.page ? (
+ <SignatureFieldOverlay
+ field={field}
+ onOpen={() => setDialogOpen(true)}
+ />
+ ) : null
+ }
+ />
+ }
+ right={
+ <SignatureFieldsPanel
+ field={field}
+ canExport={Boolean(file && field.imageDataUrl)}
+ isDownloading={isDownloading}
+ onSign={() => setDialogOpen(true)}
+ onClear={() =>
+ setField((previousField) => ({
+ ...previousField,
+ imageDataUrl: undefined,
+ }))
+ }
+ onDownload={handleDownload}
+ />
+ }
+ />
+ <SignatureDialog
+ open={dialogOpen}
+ fieldBbox={field.bbox}
+ initialValue={field.imageDataUrl}
+ onOpenChange={setDialogOpen}
+ onConfirm={(imageDataUrl) => {
+ setField((previousField) => ({ ...previousField, imageDataUrl }))
+ }}
+ />
+ </>
)
}
diff --git a/apps/v4/registry/new-york-v4/blocks/excel-document-splits.tsx b/apps/v4/registry/new-york-v4/blocks/excel-document-splits.tsx
index aeef0f7..1be4c62 100644
--- a/apps/v4/registry/new-york-v4/blocks/excel-document-splits.tsx
+++ b/apps/v4/registry/new-york-v4/blocks/excel-document-splits.tsx
@@ -4,41 +4,52 @@ import * as React from "react"
import { FileThumbnail } from "@/components/ui/file-thumbnail"
import { XlsxViewerPreview } from "@/components/ui/xlsx-viewer"
+import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"
import { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"
const SHEETS = ["Overview", "Chart review", "Format checks", "Exceptions"]
export function ExcelDocumentSplitsBlock({ file }: { file?: string }) {
return (
- <div className="grid h-[620px] min-h-[420px] overflow-hidden bg-background lg:grid-cols-[minmax(0,1fr)_340px]">
- <XlsxViewerPreview src={file} />
- <aside className="min-h-0 border-t bg-background lg:border-t-0 lg:border-l">
- <ScrollArea className="h-full" scrollFade>
- <div className="space-y-3 p-3">
- {SHEETS.map((sheet, index) => (
- <section key={sheet} className="rounded-lg border bg-background">
- <div className="border-b px-3 py-2">
- <div className="text-sm font-medium">{sheet}</div>
- <div className="text-xs text-muted-foreground">
- Sheet {index + 1}
+ <PdfBlockResizableShell
+ autoSaveId="xlsx-block-document-splits"
+ heightClassName="h-[720px]"
+ rightDefaultSize={48}
+ rightMaxSize={64}
+ rightMinSize={30}
+ left={<XlsxViewerPreview src={file} />}
+ right={
+ <aside className="min-h-0 bg-background">
+ <ScrollArea className="h-full" scrollFade>
+ <div className="space-y-3 p-3">
+ {SHEETS.map((sheet, index) => (
+ <section
+ key={sheet}
+ className="rounded-lg border bg-background"
+ >
+ <div className="border-b px-3 py-2">
+ <div className="text-sm font-medium">{sheet}</div>
+ <div className="text-xs text-muted-foreground">
+ Sheet {index + 1}
+ </div>
</div>
- </div>
- <div className="p-3">
- <FileThumbnail
- file={{
- name: sheet,
- type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
- size: "XLSX sheet",
- }}
- className="h-20 w-full"
- showMetadata={false}
- />
- </div>
- </section>
- ))}
- </div>
- </ScrollArea>
- </aside>
- </div>
+ <div className="p-3">
+ <FileThumbnail
+ file={{
+ name: sheet,
+ type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ size: "XLSX sheet",
+ }}
+ className="h-20 w-full"
+ showMetadata={false}
+ />
+ </div>
+ </section>
+ ))}
+ </div>
+ </ScrollArea>
+ </aside>
+ }
+ />
)
}
diff --git a/apps/v4/registry/new-york-v4/blocks/human-review.tsx b/apps/v4/registry/new-york-v4/blocks/human-review.tsx
index 2c464c9..0d56d56 100644
--- a/apps/v4/registry/new-york-v4/blocks/human-review.tsx
+++ b/apps/v4/registry/new-york-v4/blocks/human-review.tsx
@@ -2,177 +2,579 @@
import * as React from "react"
import {
- CheckmarkCircle02Icon,
- MessageQuestionIcon,
+ CancelCircleIcon,
+ FileDiffIcon,
+ InputNumericIcon,
+ InputTextIcon,
+ SourceCodeSquareIcon,
+ TextCheckIcon,
+ Undo02Icon,
} from "@hugeicons/core-free-icons"
import { HugeiconsIcon } from "@hugeicons/react"
+import { MultiFileDiff, Virtualizer } from "@pierre/diffs/react"
import { cn } from "@/lib/utils"
import { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"
-import { Badge } from "@/registry/new-york-v4/ui/badge"
+import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"
import { Button } from "@/registry/new-york-v4/ui/button"
+import { Input } from "@/registry/new-york-v4/ui/input"
import { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"
+import {
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+} from "@/registry/new-york-v4/ui/tabs"
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/registry/new-york-v4/ui/tooltip"
+
+export type JsonPrimitive = string | number | boolean | null
+export type JsonObject = Record<string, JsonPrimitive>
+export type SchemaPropertyType = "string" | "number" | "integer" | "boolean"
+
+export type ReviewFieldSchema = {
+ type: SchemaPropertyType
+ title?: string
+ description?: string
+ enum?: Array<string | number>
+}
-type ReviewField = {
- id: string
- label: string
- extractedValue: string
- suggestedValue: string
- page: number
- confidence: number
- status: "needs-review" | "approved"
- area: { left: number; top: number; width: number; height: number }
+export type HighlightArea = {
+ left: number
+ top: number
+ width: number
+ height: number
}
+export type ReviewField = {
+ key: string
+ schema: ReviewFieldSchema
+ actual: JsonPrimitive
+ expected: JsonPrimitive
+ location?: {
+ page: number
+ area: HighlightArea
+ }
+}
+
+const DEFAULT_ZOOM = 0.75
+const REVIEW_HIGHLIGHT_STYLE =
+ "border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_10%)]"
+const DIFF_VIEWER_THEME = {
+ "--diffs-light-bg": "oklch(0.985 0.002 247)",
+ "--diffs-dark-bg": "oklch(0.18 0.003 247)",
+ "--diffs-light": "oklch(0.22 0.01 247)",
+ "--diffs-dark": "oklch(0.92 0.006 247)",
+ "--diffs-bg-context-override":
+ "light-dark(oklch(0.967 0.003 247), oklch(0.235 0.004 247))",
+ "--diffs-bg-context-gutter-override":
+ "light-dark(oklch(0.948 0.004 247), oklch(0.205 0.004 247))",
+ "--diffs-bg-separator-override":
+ "light-dark(oklch(0.94 0.004 247), oklch(0.255 0.005 247))",
+ "--diffs-bg-buffer-override":
+ "light-dark(oklch(0.955 0.004 247), oklch(0.225 0.004 247))",
+ "--diffs-light-addition-color": "oklch(0.54 0.13 158)",
+ "--diffs-dark-addition-color": "oklch(0.72 0.13 158)",
+ "--diffs-light-deletion-color": "oklch(0.55 0.16 28)",
+ "--diffs-dark-deletion-color": "oklch(0.72 0.14 28)",
+ "--diffs-bg-addition-override":
+ "light-dark(oklch(0.957 0.032 158), oklch(0.255 0.052 158))",
+ "--diffs-bg-addition-emphasis-override":
+ "light-dark(oklch(0.88 0.06 158), oklch(0.36 0.08 158))",
+ "--diffs-bg-deletion-override":
+ "light-dark(oklch(0.958 0.03 28), oklch(0.255 0.047 28))",
+ "--diffs-bg-deletion-emphasis-override":
+ "light-dark(oklch(0.9 0.052 28), oklch(0.36 0.075 28))",
+ "--diffs-fg-number-override":
+ "light-dark(oklch(0.56 0.018 247), oklch(0.66 0.012 247))",
+ "--diffs-font-size": "12px",
+ "--diffs-line-height": "20px",
+} as React.CSSProperties
+
const REVIEW_FIELDS: ReviewField[] = [
{
- id: "title",
- label: "Title",
- extractedValue: "Attention Is All You Need",
- suggestedValue: "Attention Is All You Need",
- page: 1,
- confidence: 0.98,
- status: "approved",
- area: { left: 31, top: 31, width: 40, height: 6 },
+ key: "vendor_name",
+ schema: {
+ type: "string",
+ title: "Vendor name",
+ description: "Supplier shown on the invoice header.",
+ },
+ actual: "Acme Supplies LLC",
+ expected: "Acme Supply LLC",
+ location: {
+ page: 1,
+ area: { left: 31, top: 30, width: 40, height: 5.8 },
+ },
+ },
+ {
+ key: "total_amount",
+ schema: {
+ type: "number",
+ title: "Total amount",
+ description: "Final amount due including tax.",
+ },
+ actual: 12480,
+ expected: 12480.75,
+ location: {
+ page: 1,
+ area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },
+ },
},
{
- id: "authors",
- label: "Authors",
- extractedValue: "Vaswani, Shazeer, Parmar, Uszkoreit",
- suggestedValue: "Vaswani, Shazeer, Parmar, Uszkoreit, Jones",
- page: 1,
- confidence: 0.82,
- status: "needs-review",
- area: { left: 12, top: 34, width: 76, height: 10 },
+ 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",
+ schema: {
+ type: "boolean",
+ title: "Requires review",
+ description: "Whether a human should verify this document before export.",
+ },
+ actual: false,
+ expected: true,
+ location: {
+ page: 2,
+ area: { left: 9.5, top: 12, width: 81, height: 11.5 },
+ },
},
]
-export function HumanReviewBlock({ file }: { file?: string }) {
- const [fields, setFields] = React.useState(REVIEW_FIELDS)
- const [activeFieldId, setActiveFieldId] = React.useState(fields[0].id)
- const viewerRef = React.useRef<PDFViewerHandle>(null)
- const activeField =
- fields.find((field) => field.id === activeFieldId) ?? fields[0]
+function valuesFromFields(
+ fields: ReviewField[],
+ valueKey: "actual" | "expected"
+) {
+ return fields.reduce<JsonObject>((values, field) => {
+ values[field.key] = field[valueKey]
+ return values
+ }, {})
+}
- const focusField = React.useCallback((field: ReviewField) => {
- setActiveFieldId(field.id)
- viewerRef.current?.scrollToPageArea(field.page, field.area)
- }, [])
+function formatJson(value: unknown) {
+ return JSON.stringify(value, null, 2)
+}
- const approveField = React.useCallback((fieldId: string) => {
- setFields((currentFields) =>
- currentFields.map((field) =>
- field.id === fieldId
- ? { ...field, status: "approved", extractedValue: field.suggestedValue }
- : field
- )
+function formatValue(value: JsonPrimitive) {
+ if (value === null) return "NULL"
+ if (typeof value === "boolean") return value ? "true" : "false"
+ return String(value)
+}
+
+function getFieldIcon(type: SchemaPropertyType) {
+ if (type === "number" || type === "integer") return InputNumericIcon
+ if (type === "boolean") return TextCheckIcon
+ return InputTextIcon
+}
+
+function HumanReviewValueInput({
+ schema,
+ value,
+ onChange,
+}: {
+ schema: ReviewFieldSchema
+ value: JsonPrimitive
+ onChange: (value: JsonPrimitive) => void
+}) {
+ if (schema.enum?.length) {
+ return (
+ <span className="relative inline-flex w-full rounded-lg border border-input bg-background text-sm text-foreground shadow-xs/5 dark:bg-input/32">
+ <select
+ value={value === null ? "" : String(value)}
+ onChange={(event) => onChange(event.target.value)}
+ className="h-8.5 w-full appearance-none rounded-[inherit] bg-transparent px-3 text-sm outline-none sm:h-7.5"
+ >
+ {schema.enum.map((option) => (
+ <option key={String(option)} value={String(option)}>
+ {String(option)}
+ </option>
+ ))}
+ </select>
+ </span>
)
- }, [])
+ }
+
+ if (schema.type === "number" || schema.type === "integer") {
+ return (
+ <Input
+ nativeInput
+ type="number"
+ value={value === null ? "" : String(value)}
+ onChange={(event) => {
+ const nextValue = event.currentTarget.value
+ onChange(nextValue === "" ? null : Number(nextValue))
+ }}
+ />
+ )
+ }
+
+ if (schema.type === "boolean") {
+ return (
+ <div className="grid grid-cols-2 gap-1 rounded-lg bg-muted p-0.5">
+ {[true, false].map((option) => (
+ <Button
+ key={String(option)}
+ type="button"
+ size="sm"
+ variant={value === option ? "outline" : "ghost"}
+ className={cn(
+ "h-7 shadow-none",
+ value === option && "bg-background dark:bg-input"
+ )}
+ onClick={() => onChange(option)}
+ >
+ {option ? "True" : "False"}
+ </Button>
+ ))}
+ </div>
+ )
+ }
return (
- <div className="grid h-[620px] min-h-[420px] overflow-hidden bg-background lg:grid-cols-[minmax(0,1fr)_390px]">
- <PDFViewer
- ref={viewerRef}
- file={file}
- defaultZoom={0.75}
- renderPageOverlay={({ pageNumber }) =>
- activeField.page === pageNumber ? (
- <div
- className="pointer-events-none absolute z-10 rounded-[3px] border border-amber-500/70 bg-amber-500/12"
- style={{
- left: `${activeField.area.left}%`,
- top: `${activeField.area.top}%`,
- width: `${activeField.area.width}%`,
- height: `${activeField.area.height}%`,
- }}
+ <Input
+ nativeInput
+ value={value === null ? "" : String(value)}
+ onChange={(event) => onChange(event.currentTarget.value)}
+ />
+ )
+}
+
+function HumanReviewFieldCard({
+ field,
+ value,
+ originalValue,
+ active,
+ onChange,
+ onFieldFocus,
+ onUndo,
+ onSetNull,
+}: {
+ field: ReviewField
+ value: JsonPrimitive
+ originalValue: JsonPrimitive
+ active?: boolean
+ onChange: (value: JsonPrimitive) => void
+ onFieldFocus?: (field: ReviewField) => void
+ onUndo: () => void
+ onSetNull: () => void
+}) {
+ const modified = value !== originalValue
+ const Icon = getFieldIcon(field.schema.type)
+
+ return (
+ <div
+ tabIndex={0}
+ onFocusCapture={() => onFieldFocus?.(field)}
+ onMouseEnter={() => onFieldFocus?.(field)}
+ 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 &&
+ "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_8%)]"
+ )}
+ >
+ <div className="mb-3 flex min-h-8 items-start justify-between gap-3">
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-center gap-2">
+ <div className="min-w-0">
+ <div className="truncate text-sm font-medium">
+ {field.schema.title ?? field.key}
+ </div>
+ </div>
+ <span
+ className={cn(
+ "size-2 shrink-0 rounded-full bg-amber-400 transition-opacity",
+ !modified && "opacity-0"
+ )}
/>
- ) : null
- }
- />
- <aside className="min-h-0 border-t bg-background lg:border-t-0 lg:border-l">
- <ScrollArea className="h-full" scrollFade>
- <div className="space-y-3 p-3">
- {fields.map((field) => {
- const isActive = field.id === activeField.id
-
- return (
- <button
- key={field.id}
+ </div>
+ <div className="truncate text-xs text-muted-foreground">
+ {field.key}
+ </div>
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ {modified ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
type="button"
- onClick={() => focusField(field)}
- 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 && "border-amber-500/60 bg-amber-500/5"
- )}
+ variant="ghost"
+ size="icon-sm"
+ className="text-muted-foreground"
+ onClick={onUndo}
+ aria-label={`Undo ${field.key}`}
>
- <div className="flex items-start justify-between gap-3">
- <div className="space-y-1">
- <div className="text-sm font-medium">{field.label}</div>
- <div className="text-xs text-muted-foreground">
- Confidence {Math.round(field.confidence * 100)}%
- </div>
- </div>
- <Badge
- variant={
- field.status === "approved" ? "default" : "secondary"
- }
- >
- {field.status === "approved" ? "Approved" : "Review"}
- </Badge>
- </div>
- <div className="mt-3 grid gap-2 text-xs">
- <div>
- <div className="text-muted-foreground">Extracted</div>
- <div className="mt-1 rounded-md bg-muted p-2 text-foreground">
- {field.extractedValue}
- </div>
- </div>
- <div>
- <div className="text-muted-foreground">Suggested</div>
- <div className="mt-1 rounded-md bg-emerald-500/10 p-2 text-emerald-700 dark:text-emerald-300">
- {field.suggestedValue}
- </div>
- </div>
- </div>
- <div className="mt-3 flex gap-2">
- <Button
- type="button"
- size="sm"
- variant="outline"
- className="flex-1"
- onClick={(event) => {
- event.stopPropagation()
- focusField(field)
- }}
- >
- <HugeiconsIcon
- icon={MessageQuestionIcon}
- className="size-4"
- />
- Review
- </Button>
- <Button
- type="button"
- size="sm"
- className="flex-1"
- onClick={(event) => {
- event.stopPropagation()
- approveField(field.id)
- }}
- >
- <HugeiconsIcon
- icon={CheckmarkCircle02Icon}
- className="size-4"
- />
- Approve
- </Button>
- </div>
- </button>
- )
- })}
+ <HugeiconsIcon icon={Undo02Icon} className="size-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Revert changes</TooltipContent>
+ </Tooltip>
+ ) : null}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="text-muted-foreground"
+ onClick={onSetNull}
+ aria-label={`Set ${field.key} to null`}
+ >
+ <HugeiconsIcon icon={CancelCircleIcon} className="size-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Set to NULL</TooltipContent>
+ </Tooltip>
+ <div className="flex h-6 items-center gap-1 rounded-md border bg-muted/50 px-1.5 text-xs text-muted-foreground">
+ <HugeiconsIcon icon={Icon} className="size-3.5" />
+ {field.schema.type}
+ </div>
+ </div>
+ </div>
+ <div className="grid gap-2 sm:grid-cols-2">
+ <div className="rounded-md border bg-muted/30 p-2">
+ {field.schema.description ? (
+ <p className="mb-2 text-xs text-muted-foreground">
+ {field.schema.description}
+ </p>
+ ) : null}
+ <div className="mb-1 text-[11px] font-medium text-muted-foreground">
+ Actual
</div>
- </ScrollArea>
- </aside>
+ <div className="min-h-7 rounded-md bg-background px-2 py-1.5 text-sm">
+ {formatValue(field.actual)}
+ </div>
+ </div>
+ <div className="rounded-md border border-blue-500/30 bg-blue-500/5 p-2">
+ <div className="mb-1 text-[11px] font-medium text-blue-700 dark:text-blue-300">
+ Expected
+ </div>
+ <HumanReviewValueInput
+ schema={field.schema}
+ value={value}
+ onChange={onChange}
+ />
+ </div>
+ </div>
</div>
)
}
+
+function HumanReviewHighlight({ field }: { field: ReviewField }) {
+ const area = field.location?.area
+
+ if (!area) return null
+
+ return (
+ <div
+ className={cn(
+ "pointer-events-none absolute z-10 rounded-[3px] border",
+ REVIEW_HIGHLIGHT_STYLE
+ )}
+ style={{
+ left: `${area.left}%`,
+ top: `${area.top}%`,
+ width: `${area.width}%`,
+ height: `${area.height}%`,
+ }}
+ />
+ )
+}
+
+export function JsonDiffView({
+ actual,
+ expected,
+}: {
+ actual: JsonObject
+ expected: JsonObject
+}) {
+ return (
+ <Virtualizer
+ className="h-full overflow-auto rounded-b-xl bg-surface/60"
+ contentClassName="min-w-full"
+ >
+ <div className="human-review-diff h-full text-xs">
+ <MultiFileDiff
+ className="block min-w-full"
+ style={DIFF_VIEWER_THEME}
+ oldFile={{
+ name: "actual.json",
+ contents: formatJson(actual),
+ lang: "json",
+ }}
+ newFile={{
+ name: "expected.json",
+ contents: formatJson(expected),
+ lang: "json",
+ }}
+ disableWorkerPool
+ options={{
+ diffStyle: "split",
+ diffIndicators: "bars",
+ hunkSeparators: "line-info-basic",
+ overflow: "wrap",
+ theme: {
+ light: "pierre-light",
+ dark: "pierre-dark",
+ },
+ }}
+ />
+ </div>
+ </Virtualizer>
+ )
+}
+
+export function HumanReviewPanel({
+ fields = REVIEW_FIELDS,
+ activeFieldKey,
+ className,
+ onFieldFocus,
+}: {
+ fields?: ReviewField[]
+ activeFieldKey?: string
+ className?: string
+ onFieldFocus?: (field: ReviewField) => void
+} = {}) {
+ const actualValues = React.useMemo(
+ () => valuesFromFields(fields, "actual"),
+ [fields]
+ )
+ const initialExpectedValues = React.useMemo(
+ () => valuesFromFields(fields, "expected"),
+ [fields]
+ )
+ const [expected, setExpected] = React.useState<JsonObject>(
+ initialExpectedValues
+ )
+
+ React.useEffect(() => {
+ setExpected(initialExpectedValues)
+ }, [initialExpectedValues])
+
+ const updateValue = React.useCallback((key: string, value: JsonPrimitive) => {
+ setExpected((current) => ({ ...current, [key]: value }))
+ }, [])
+
+ return (
+ <TooltipProvider delay={200}>
+ <Tabs
+ defaultValue="form"
+ className={cn("flex h-[560px] flex-col gap-0 bg-background", className)}
+ >
+ <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">
+ <TabsList className="h-8 sm:h-7">
+ <TabsTrigger value="form" className="h-7 sm:h-6">
+ <HugeiconsIcon icon={TextCheckIcon} className="size-4" />
+ Form
+ </TabsTrigger>
+ <TabsTrigger value="json" className="h-7 sm:h-6">
+ <HugeiconsIcon icon={SourceCodeSquareIcon} className="size-4" />
+ JSON
+ </TabsTrigger>
+ </TabsList>
+ <div className="flex h-8 items-center gap-1 rounded-md border bg-muted/40 px-2 text-xs text-muted-foreground sm:h-7">
+ <HugeiconsIcon icon={FileDiffIcon} className="size-3.5" />
+ {fields.length} fields
+ </div>
+ </div>
+ <TabsContent value="form" className="min-h-0 flex-1">
+ <ScrollArea className="h-full" scrollFade>
+ <div className="space-y-3 p-3">
+ {fields.map((field) => (
+ <HumanReviewFieldCard
+ key={field.key}
+ field={field}
+ value={expected[field.key] ?? null}
+ originalValue={field.expected}
+ active={field.key === activeFieldKey}
+ onChange={(value) => updateValue(field.key, value)}
+ onFieldFocus={onFieldFocus}
+ onUndo={() => updateValue(field.key, field.expected)}
+ onSetNull={() => updateValue(field.key, null)}
+ />
+ ))}
+ </div>
+ </ScrollArea>
+ </TabsContent>
+ <TabsContent value="json" className="min-h-0 flex-1">
+ <JsonDiffView actual={actualValues} expected={expected} />
+ </TabsContent>
+ </Tabs>
+ </TooltipProvider>
+ )
+}
+
+export function HumanReviewBlock({
+ file,
+ fields = REVIEW_FIELDS,
+ className,
+}: {
+ file?: string
+ fields?: ReviewField[]
+ className?: string
+}) {
+ const [activeFieldKey, setActiveFieldKey] = React.useState(fields[0]?.key)
+ const viewerRef = React.useRef<PDFViewerHandle>(null)
+ const activeField =
+ fields.find((field) => field.key === activeFieldKey) ?? fields[0]
+
+ React.useEffect(() => {
+ if (activeFieldKey || !fields[0]) return
+ setActiveFieldKey(fields[0].key)
+ }, [activeFieldKey, fields])
+
+ const focusField = React.useCallback((field: ReviewField) => {
+ setActiveFieldKey(field.key)
+
+ if (field.location) {
+ viewerRef.current?.scrollToPageArea(
+ field.location.page,
+ field.location.area
+ )
+ }
+ }, [])
+
+ return (
+ <PdfBlockResizableShell
+ autoSaveId="pdf-block-human-review"
+ className={className}
+ rightDefaultSize={42}
+ rightMaxSize={60}
+ rightMinSize={30}
+ left={
+ <PDFViewer
+ ref={viewerRef}
+ file={file}
+ defaultZoom={DEFAULT_ZOOM}
+ renderPageOverlay={({ pageNumber }) =>
+ activeField?.location?.page === pageNumber ? (
+ <HumanReviewHighlight field={activeField} />
+ ) : null
+ }
+ />
+ }
+ right={
+ <aside className="min-h-0 bg-background">
+ <HumanReviewPanel
+ fields={fields}
+ activeFieldKey={activeField?.key}
+ className="h-full min-h-0"
+ onFieldFocus={focusField}
+ />
+ </aside>
+ }
+ />
+ )
+}
diff --git a/apps/v4/registry/new-york-v4/blocks/ocr-blocks.tsx b/apps/v4/registry/new-york-v4/blocks/ocr-blocks.tsx
index 6cb561d..ab2224b 100644
--- a/apps/v4/registry/new-york-v4/blocks/ocr-blocks.tsx
+++ b/apps/v4/registry/new-york-v4/blocks/ocr-blocks.tsx
@@ -10,6 +10,7 @@ import { HugeiconsIcon } from "@hugeicons/react"
import { cn } from "@/lib/utils"
import { PDFViewer, type PDFViewerHandle } from "@/components/ui/pdf-viewer"
+import { PdfBlockResizableShell } from "@/components/pdf-block-resizable-shell"
import { ScrollArea } from "@/registry/new-york-v4/ui/scroll-area"
type OcrBlock = {
@@ -110,73 +111,78 @@ export function OcrBlocksBlock({ file }: { file?: string }) {
}, [])
return (
- <div className="grid h-[620px] min-h-[420px] overflow-hidden bg-background lg:grid-cols-[minmax(0,1fr)_360px]">
- <PDFViewer
- ref={viewerRef}
- 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)}
- />
- )
- )
- }
- />
- <aside className="min-h-0 border-t bg-background lg:border-t-0 lg:border-l">
- <ScrollArea className="h-full" scrollFade>
- <div className="space-y-2 p-3">
- {OCR_BLOCKS.map((block) => {
- const isActive = block.id === activeBlock.id
-
- return (
- <button
+ <PdfBlockResizableShell
+ autoSaveId="pdf-block-ocr"
+ left={
+ <PDFViewer
+ ref={viewerRef}
+ file={file}
+ defaultZoom={0.75}
+ renderPageOverlay={({ pageNumber }) =>
+ OCR_BLOCKS.filter((block) => block.page === pageNumber).map(
+ (block) => (
+ <div
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
+ "pointer-events-none absolute z-10 rounded-[3px] border",
+ block.id === activeBlock.id
+ ? block.accentClassName
+ : "border-muted-foreground/30 bg-muted/20"
)}
- >
- <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="truncate text-sm font-medium">
- {block.label}
+ style={polygonToArea(block.polygon)}
+ />
+ )
+ )
+ }
+ />
+ }
+ 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
+
+ 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="truncate text-sm font-medium">
+ {block.label}
+ </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="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">
- p. {block.page}
+ <div className="mt-0.5 text-xs font-medium text-muted-foreground">
+ {block.kind} - {Math.round(block.confidence * 100)}%
+ </div>
+ <div className="mt-2 line-clamp-3 text-sm text-foreground/90">
+ {block.text}
</div>
- </div>
- <div className="mt-0.5 text-xs font-medium text-muted-foreground">
- {block.kind} - {Math.round(block.confidence * 100)}%
- </div>
- <div className="mt-2 line-clamp-3 text-sm text-foreground/90">
- {block.text}
</div>
</div>
- </div>
- </button>
- )
- })}
- </div>
- </ScrollArea>
- </aside>
- </div>
+ </button>
+ )
+ })}
+ </div>
+ </ScrollArea>
+ </aside>
+ }
+ />
)
}
diff --git a/apps/v4/registry/new-york-v4/ui/file-upload.tsx b/apps/v4/registry/new-york-v4/ui/file-upload.tsx
index 0aab9ca..fac25e8 100644
--- a/apps/v4/registry/new-york-v4/ui/file-upload.tsx
+++ b/apps/v4/registry/new-york-v4/ui/file-upload.tsx
@@ -8,9 +8,11 @@ import {
Upload01Icon,
} from "@hugeicons/core-free-icons"
import { HugeiconsIcon } from "@hugeicons/react"
+import { BorderBeam } from "border-beam"
import { cn } from "@/lib/utils"
import { FileThumbnail } from "@/components/ui/file-thumbnail"
+import { Card } from "@/registry/new-york-v4/ui/card"
type FileUploadItem = {
id: string
@@ -28,11 +30,13 @@ type AcceptedFileType = {
type FileUploadProps = {
accept?: string
acceptedFileTypes?: AcceptedFileType[]
+ borderBeamTheme?: React.ComponentProps<typeof BorderBeam>["theme"]
browseLabel?: string
className?: string
description?: string
draggingLabel?: string
multiple?: boolean
+ showBorderBeam?: boolean
showFileList?: boolean
title?: string
onFilesAccepted?: (files: File[]) => void
@@ -44,6 +48,20 @@ const ACCEPTED_FILE_TYPES: AcceptedFileType[] = [
{ label: "PDF", icon: FileUploadIcon },
{ label: "Sheet", icon: FileSpreadsheetIcon },
]
+const ICON_TRANSFORMS = [
+ {
+ idle: "translate(-78%, -50%) rotate(-8deg)",
+ active: "translate(-114%, -50%) rotate(-12deg) scale(1.08)",
+ },
+ {
+ idle: "translate(-50%, -50%) rotate(0deg)",
+ active: "translate(-50%, -50%) rotate(0deg) scale(1.18)",
+ },
+ {
+ idle: "translate(-22%, -50%) rotate(8deg)",
+ active: "translate(14%, -50%) rotate(12deg) scale(1.08)",
+ },
+]
function formatBytes(bytes: number) {
if (bytes === 0) return "0 B"
@@ -85,14 +103,51 @@ function toUploadItems(files: FileList | File[]): FileUploadItem[] {
}))
}
+function UploadIconCluster({
+ acceptedFileTypes,
+ isDragging,
+}: {
+ acceptedFileTypes: AcceptedFileType[]
+ isDragging: boolean
+}) {
+ const singleIcon = acceptedFileTypes.length === 1
+
+ return (
+ <div className="relative h-14 w-36">
+ {acceptedFileTypes.map((item, index) => (
+ <Card
+ key={item.label}
+ className={cn(
+ "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"
+ )}
+ style={{
+ transform: singleIcon
+ ? `translate(-50%, -50%) scale(${isDragging ? 1.14 : 1})`
+ : isDragging
+ ? ICON_TRANSFORMS[index]?.active
+ : ICON_TRANSFORMS[index]?.idle,
+ }}
+ >
+ <HugeiconsIcon icon={item.icon} className="size-5" />
+ </Card>
+ ))}
+ </div>
+ )
+}
+
export function FileUpload({
accept,
acceptedFileTypes = ACCEPTED_FILE_TYPES,
+ borderBeamTheme = "light",
browseLabel = "Browse files",
className,
description = "PDF, DOCX, XLSX, CSV, PNG, or JPG",
draggingLabel = "Drop to add",
multiple = true,
+ showBorderBeam = true,
showFileList = true,
title = "Click to upload or drop files",
onFilesAccepted,
@@ -135,72 +190,84 @@ export function FileUpload({
}
}, [files])
- return (
- <div className={cn("space-y-3", className)}>
- <label
- className={cn(
- "relative flex min-h-64 cursor-pointer flex-col items-center justify-center gap-5 overflow-hidden rounded-2xl border border-dashed bg-background px-6 py-10 text-center transition-colors",
- isDragging
- ? "border-foreground/40 bg-accent/35"
- : "border-border hover:border-foreground/30 hover:bg-muted/35"
- )}
- onDragEnter={(event) => {
- event.preventDefault()
- dragDepthRef.current += 1
- setIsDragging(true)
- }}
- onDragLeave={(event) => {
- event.preventDefault()
- dragDepthRef.current = Math.max(0, dragDepthRef.current - 1)
- if (dragDepthRef.current === 0) setIsDragging(false)
- }}
- onDragOver={(event) => event.preventDefault()}
- onDrop={(event) => {
- event.preventDefault()
- dragDepthRef.current = 0
- setIsDragging(false)
- if (event.dataTransfer.files.length > 0) {
- commitFiles(event.dataTransfer.files)
+ const dropzone = (
+ <label
+ className={cn(
+ "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",
+ "motion-reduce:transition-none",
+ isDragging
+ ? "border-foreground/40 bg-accent/35"
+ : "border-border hover:border-foreground/30 hover:bg-muted/35"
+ )}
+ onDragEnter={(event) => {
+ event.preventDefault()
+ dragDepthRef.current += 1
+ setIsDragging(true)
+ }}
+ onDragLeave={(event) => {
+ event.preventDefault()
+ dragDepthRef.current = Math.max(0, dragDepthRef.current - 1)
+ if (dragDepthRef.current === 0) setIsDragging(false)
+ }}
+ onDragOver={(event) => event.preventDefault()}
+ onDrop={(event) => {
+ event.preventDefault()
+ dragDepthRef.current = 0
+ setIsDragging(false)
+ if (event.dataTransfer.files.length > 0) {
+ commitFiles(event.dataTransfer.files)
+ }
+ }}
+ >
+ <UploadIconCluster
+ acceptedFileTypes={acceptedFileTypes}
+ isDragging={isDragging}
+ />
+ <div className="space-y-1">
+ <div className="text-sm font-medium">{title}</div>
+ <div className="text-xs text-muted-foreground">{description}</div>
+ {rejectionMessage ? (
+ <div className="text-xs text-destructive">{rejectionMessage}</div>
+ ) : null}
+ </div>
+ <div className="inline-flex items-center gap-2 rounded-full border bg-background px-3 py-1 text-xs text-muted-foreground">
+ <HugeiconsIcon icon={Upload01Icon} className="size-3.5" />
+ <span>{isDragging ? draggingLabel : browseLabel}</span>
+ </div>
+ <input
+ type="file"
+ accept={accept}
+ multiple={multiple}
+ className="sr-only"
+ onChange={(event) => {
+ if (event.target.files) {
+ commitFiles(event.target.files)
+ event.currentTarget.value = ""
}
}}
- >
- <div className="flex items-center justify-center gap-2">
- {acceptedFileTypes.map((item) => (
- <div
- key={item.label}
- className={cn(
- "grid size-12 place-items-center rounded-xl border bg-background text-muted-foreground transition-colors",
- isDragging && "bg-accent text-foreground"
- )}
- >
- <HugeiconsIcon icon={item.icon} className="size-5" />
- </div>
- ))}
- </div>
- <div className="space-y-1">
- <div className="text-sm font-medium">{title}</div>
- <div className="text-xs text-muted-foreground">{description}</div>
- {rejectionMessage ? (
- <div className="text-xs text-destructive">{rejectionMessage}</div>
- ) : null}
- </div>
- <div className="inline-flex items-center gap-2 rounded-full border bg-background px-3 py-1 text-xs text-muted-foreground">
- <HugeiconsIcon icon={Upload01Icon} className="size-3.5" />
- <span>{isDragging ? draggingLabel : browseLabel}</span>
- </div>
- <input
- type="file"
- accept={accept}
- multiple={multiple}
- className="sr-only"
- onChange={(event) => {
- if (event.target.files) {
- commitFiles(event.target.files)
- event.currentTarget.value = ""
- }
- }}
- />
- </label>
+ />
+ </label>
+ )
+
+ return (
+ <div className={cn("space-y-3", className)}>
+ {showBorderBeam ? (
+ <BorderBeam
+ active={isDragging}
+ borderRadius={18}
+ brightness={2.4}
+ className="rounded-[1.125rem]"
+ colorVariant="ocean"
+ duration={2.4}
+ size="md"
+ strength={1}
+ theme={borderBeamTheme}
+ >
+ {dropzone}
+ </BorderBeam>
+ ) : (
+ dropzone
+ )}
{showFileList && files.length > 0 ? (
<div className="rounded-xl border bg-background">
{files.map((file) => (
diff --git a/apps/v4/registry/new-york-v4/ui/scroll-area.tsx b/apps/v4/registry/new-york-v4/ui/scroll-area.tsx
index 4ef37e4..e925908 100644
--- a/apps/v4/registry/new-york-v4/ui/scroll-area.tsx
+++ b/apps/v4/registry/new-york-v4/ui/scroll-area.tsx
@@ -8,33 +8,53 @@ import { cn } from "@/lib/utils"
export function ScrollArea({
className,
children,
+ orientation = "both",
scrollFade = false,
scrollbarGutter = false,
+ scrollbarOverflowOnly = false,
+ viewportClassName,
+ viewportRef,
...props
}: ScrollAreaPrimitive.Root.Props & {
+ orientation?: "vertical" | "horizontal" | "both"
scrollFade?: boolean
scrollbarGutter?: boolean
+ scrollbarOverflowOnly?: boolean
+ viewportClassName?: string
+ viewportRef?: React.Ref<HTMLDivElement>
}): React.ReactElement {
return (
<ScrollAreaPrimitive.Root
- className={cn("size-full min-h-0", className)}
+ className={cn(
+ "size-full min-h-0",
+ scrollbarOverflowOnly && "scrollbar-overflow-only",
+ className
+ )}
{...props}
>
<ScrollAreaPrimitive.Viewport
+ ref={viewportRef}
className={cn(
"transition-shadows h-full rounded-[inherit] outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-has-overflow-x:overscroll-x-contain data-has-overflow-y:overscroll-y-contain",
scrollFade &&
"mask-t-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-start)))] mask-r-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-end)))] mask-b-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-end)))] mask-l-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-start)))] [--fade-size:1.5rem]",
scrollbarGutter &&
- "data-has-overflow-x:pb-2.5 data-has-overflow-y:pe-2.5"
+ "data-has-overflow-x:pb-2.5 data-has-overflow-y:pe-2.5",
+ viewportClassName
)}
data-slot="scroll-area-viewport"
>
{children}
</ScrollAreaPrimitive.Viewport>
- <ScrollBar orientation="vertical" />
- <ScrollBar orientation="horizontal" />
- <ScrollAreaPrimitive.Corner data-slot="scroll-area-corner" />
+ {orientation !== "horizontal" ? (
+ <ScrollBar orientation="vertical" />
+ ) : null}
+ {orientation !== "vertical" ? (
+ <ScrollBar orientation="horizontal" />
+ ) : null}
+ {orientation === "both" ? (
+ <ScrollAreaPrimitive.Corner data-slot="scroll-area-corner" />
+ ) : null}
</ScrollAreaPrimitive.Root>
)
}