Skip to content

armgit / ui

Public Imported from GitHub
0
TypeScript
21.2 KB
Raw Blame
"use client"

import * as React from "react"
import {
  DocxEditorViewer,
  useDocxEditor,
  useDocxViewerThumbnails,
  type DocxEditorController,
} from "@extend-ai/react-docx"
import {
  useXlsxViewerController,
  useXlsxViewerThumbnails,
  XlsxViewerProvider,
} from "@extend-ai/react-xlsx"

import { renderPdfThumbnailUrl } from "@/lib/pdf-thumbnail-utils"
import { withUiBasePath } from "@/lib/zone-path"
import { Button } from "@/components/ui/button"
import {
  DocsSourceCodeBlock,
  DocsViewCodeBlock,
} from "@/components/docs-code-block"
import {
  FileThumbnail,
  type ThumbnailFile,
} from "@/components/extend/file-thumbnail"

const DOCX_MIME_TYPE =
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
const XLSX_MIME_TYPE =
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
const PDF_THUMBNAIL_WIDTH = 240
const DOCX_THUMBNAIL_WIDTH = 240
const XLSX_THUMBNAIL_WIDTH = 520

type DemoFileKind = "image" | "pdf" | "docx" | "xlsx"

type DemoFile = ThumbnailFile & {
  description: string
  kind: DemoFileKind
  url: string
}

type DocxThumbnailRenderState = {
  aspectRatio: number
  isMounted: boolean
  pixelHeightPx: number
  pixelWidthPx: number
  status: string
}

export const SAMPLE_FILES: DemoFile[] = [
  {
    name: "invoice-preview.png",
    type: "image/png",
    description: "Image",
    kind: "image",
    url: withUiBasePath("/opengraph-image.png"),
  },
  {
    name: "attention.pdf",
    type: "application/pdf",
    description: "PDF",
    kind: "pdf",
    url: withUiBasePath("/samples/attention.pdf"),
  },
  {
    name: "demo.docx",
    type: DOCX_MIME_TYPE,
    description: "DOCX",
    kind: "docx",
    url: withUiBasePath("/samples/demo.docx"),
  },
  {
    name: "crazy-chart-zoo.xlsx",
    type: XLSX_MIME_TYPE,
    description: "XLSX",
    kind: "xlsx",
    url: withUiBasePath("/samples/crazy-chart-zoo.xlsx"),
  },
]

async function fetchFile(file: DemoFile) {
  const response = await fetch(file.url)

  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,
  })
}

export function getFileKindLabel(file: ThumbnailFile) {
  if (file.type.startsWith("image/")) return "Image"
  if (file.type === "application/pdf") return "PDF"
  if (file.name.endsWith(".docx")) return "DOCX"
  if (file.name.endsWith(".xlsx")) return "XLSX"

  return "File"
}

function ImageThumbnailPreview({
  file,
  previewAspectRatio,
}: {
  file: DemoFile
  previewAspectRatio?: number
}) {
  return (
    <FileThumbnail
      file={file}
      previewImageUrl={file.url}
      previewAspectRatio={previewAspectRatio}
      previewClassName="bg-background"
    />
  )
}

function PdfThumbnailPreview({
  file,
  previewAspectRatio,
}: {
  file: DemoFile
  previewAspectRatio?: number
}) {
  const [imageUrl, setImageUrl] = React.useState<string | null>(null)
  const [hasError, setHasError] = React.useState(false)

  const [previousUrl, setPreviousUrl] = React.useState(file.url)
  if (previousUrl !== file.url) {
    setPreviousUrl(file.url)
    setImageUrl(null)
    setHasError(false)
  }

  React.useEffect(() => {
    let isCurrent = true

    void renderPdfThumbnailUrl({
      pageIndex: 0,
      url: file.url,
      width: PDF_THUMBNAIL_WIDTH,
    })
      .then((nextImageUrl) => {
        if (isCurrent) {
          setImageUrl(nextImageUrl)
          setHasError(!nextImageUrl)
        }
      })
      .catch(() => {
        if (isCurrent) {
          setHasError(true)
        }
      })

    return () => {
      isCurrent = false
    }
  }, [file.url])

  return (
    <FileThumbnail
      file={file}
      previewAspectRatio={previewAspectRatio ?? 0.77}
      previewClassName="bg-white"
      previewImageUrl={imageUrl}
      isLoading={!imageUrl && !hasError}
      hasError={hasError}
    />
  )
}

function DocxThumbnailPreview({
  file,
  previewAspectRatio,
}: {
  file: DemoFile
  previewAspectRatio?: number
}) {
  const editor = useDocxEditor({
    initialDocumentTheme: "light",
    initialFileName: file.name,
  })
  const { importDocxFile } = editor
  const [isLoading, setIsLoading] = React.useState(true)
  const [hasError, setHasError] = React.useState(false)
  const thumbnailEditor = React.useMemo<DocxEditorController>(
    () => ({
      ...editor,
      totalPages: Math.max(editor.totalPages, 1),
    }),
    [editor]
  )
  const { thumbnails } = useDocxViewerThumbnails(
    thumbnailEditor,
    React.useMemo(
      () => ({
        pixelRatio: 2,
        resolution: {
          maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,
          maxWidth: DOCX_THUMBNAIL_WIDTH,
        },
      }),
      []
    )
  )
  const firstThumbnail = thumbnails[0]
  const thumbnailRenderState = firstThumbnail
  const attachDocxThumbnailCanvas = firstThumbnail?.canvasRef

  const [previousInputs, setPreviousInputs] = React.useState({
    file,
    importDocxFile,
  })
  if (
    previousInputs.file !== file ||
    previousInputs.importDocxFile !== importDocxFile
  ) {
    setPreviousInputs({ file, importDocxFile })
    setIsLoading(true)
    setHasError(false)
  }

  React.useEffect(() => {
    let isCurrent = true

    void fetchFile(file)
      .then((docxFile) => importDocxFile(docxFile))
      .then(() => {
        if (isCurrent) {
          setIsLoading(false)
        }
      })
      .catch(() => {
        if (isCurrent) {
          setIsLoading(false)
          setHasError(true)
        }
      })

    return () => {
      isCurrent = false
    }
  }, [file, importDocxFile])

  const thumbnailIsLoading =
    isLoading ||
    (!thumbnailRenderState && !hasError) ||
    Boolean(
      thumbnailRenderState &&
        !thumbnailRenderState.isMounted &&
        thumbnailRenderState.status !== "ready" &&
        thumbnailRenderState.status !== "error"
    )
  const thumbnailHasError = hasError || thumbnailRenderState?.status === "error"

  return (
    <>
      <FileThumbnail
        file={file}
        previewAspectRatio={
          previewAspectRatio ?? thumbnailRenderState?.aspectRatio ?? 0.77
        }
        previewClassName="bg-white"
        previewContent={
          thumbnailRenderState ? (
            <canvas
              ref={attachDocxThumbnailCanvas}
              width={thumbnailRenderState.pixelWidthPx}
              height={thumbnailRenderState.pixelHeightPx}
              className="!size-full bg-white object-cover object-top"
            />
          ) : null
        }
        isLoading={thumbnailIsLoading}
        hasError={thumbnailHasError}
      />
      {!thumbnailHasError ? (
        <div
          aria-hidden="true"
          className="pointer-events-none fixed top-0 left-0 -z-10 h-[1056px] w-[816px] overflow-hidden bg-white opacity-0 [contain:layout_paint]"
        >
          <div className="w-[816px]">
            <DocxEditorViewer
              editor={editor}
              mode="read-only"
              pageBackgroundColor="#ffffff"
              pageGapBackgroundColor="transparent"
              visiblePageRange={{ endPageIndex: 0, startPageIndex: 0 }}
              pageVirtualization={{ enabled: false }}
              deferInitialPaginationPaint={false}
            />
          </div>
        </div>
      ) : null}
    </>
  )
}

function XlsxThumbnailPreview({
  file,
  previewAspectRatio,
}: {
  file: DemoFile
  previewAspectRatio?: number
}) {
  const [workbookBuffer, setWorkbookBuffer] =
    React.useState<ArrayBuffer | null>(null)
  const [imageUrl, setImageUrl] = React.useState<string | null>(null)
  const [hasError, setHasError] = React.useState(false)

  const [previousInputs, setPreviousInputs] = React.useState({ file })
  if (previousInputs.file !== file) {
    setPreviousInputs({ file })
    setWorkbookBuffer(null)
    setImageUrl(null)
    setHasError(false)
  }

  React.useEffect(() => {
    let isCurrent = true

    void fetch(file.url)
      .then(async (response) => {
        if (!response.ok) {
          throw new Error(`Failed to fetch ${file.name} (${response.status})`)
        }

        return response.arrayBuffer()
      })
      .then((buffer) => {
        if (isCurrent) {
          setWorkbookBuffer(buffer)
        }
      })
      .catch(() => {
        if (isCurrent) {
          setHasError(true)
        }
      })

    return () => {
      isCurrent = false
    }
  }, [file])

  return (
    <>
      <FileThumbnail
        file={file}
        previewAspectRatio={previewAspectRatio ?? 11 / 7}
        previewClassName="bg-white [&>img]:object-left-top"
        previewImageUrl={imageUrl}
        isLoading={!imageUrl && !hasError}
        hasError={hasError}
      />
      {workbookBuffer && !imageUrl && !hasError ? (
        <XlsxThumbnailGenerator
          file={file}
          workbookBuffer={workbookBuffer}
          onError={() => setHasError(true)}
          onImageUrl={setImageUrl}
        />
      ) : null}
    </>
  )
}

function XlsxThumbnailGenerator({
  file,
  onError,
  onImageUrl,
  workbookBuffer,
}: {
  file: DemoFile
  onError: () => void
  onImageUrl: (url: string) => void
  workbookBuffer: ArrayBuffer
}) {
  const controller = useXlsxViewerController(
    React.useMemo(
      () => ({
        file: workbookBuffer,
        fileName: file.name,
        readOnly: true,
        useWorker: true,
      }),
      [file.name, workbookBuffer]
    )
  )

  return (
    <XlsxViewerProvider controller={controller}>
      <XlsxThumbnailCapture onError={onError} onImageUrl={onImageUrl} />
    </XlsxViewerProvider>
  )
}

function XlsxThumbnailCapture({
  onError,
  onImageUrl,
}: {
  onError: () => void
  onImageUrl: (url: string) => void
}) {
  const { thumbnails } = useXlsxViewerThumbnails(
    React.useMemo(
      () => ({
        includeHeaders: true,
        resolution: {
          maxHeight: XLSX_THUMBNAIL_WIDTH,
          maxWidth: XLSX_THUMBNAIL_WIDTH,
        },
      }),
      []
    )
  )
  const firstThumbnail = thumbnails[0]

  React.useEffect(() => {
    if (!firstThumbnail) return

    const canvas = document.createElement("canvas")

    canvas.width = firstThumbnail.width
    canvas.height = firstThumbnail.height

    if (!firstThumbnail.paint(canvas)) {
      onError()
      return
    }

    onImageUrl(canvas.toDataURL("image/png"))
  }, [firstThumbnail, onError, onImageUrl])

  return null
}

function FileThumbnailExample({
  className,
  file,
  previewAspectRatio,
}: {
  className?: string
  file: DemoFile
  previewAspectRatio?: number
}) {
  return (
    <div className={className}>
      {file.kind === "image" ? (
        <ImageThumbnailPreview
          file={file}
          previewAspectRatio={previewAspectRatio}
        />
      ) : null}
      {file.kind === "pdf" ? (
        <PdfThumbnailPreview
          file={file}
          previewAspectRatio={previewAspectRatio}
        />
      ) : null}
      {file.kind === "docx" ? (
        <DocxThumbnailPreview
          file={file}
          previewAspectRatio={previewAspectRatio}
        />
      ) : null}
      {file.kind === "xlsx" ? (
        <XlsxThumbnailPreview
          file={file}
          previewAspectRatio={previewAspectRatio}
        />
      ) : null}
    </div>
  )
}

export function DocumentAwareFileThumbnail({
  file,
  className,
}: {
  file: DemoFile
  className?: string
}) {
  return (
    <FileThumbnailExample
      file={file}
      className={className}
      previewAspectRatio={1}
    />
  )
}

export function FileThumbnailDemo() {
  return (
    <div
      data-slot="component-preview"
      className="group relative mt-4 mb-12 flex flex-col overflow-hidden rounded-xl border"
    >
      <div className="grid gap-6 bg-background p-6 sm:grid-cols-2 lg:grid-cols-4">
        {SAMPLE_FILES.map((file) => (
          <div key={file.name} className="space-y-2">
            <div className="text-sm font-medium">{file.description}</div>
            <FileThumbnailExample file={file} previewAspectRatio={1} />
          </div>
        ))}
      </div>
      <DocsViewCodeBlock code={fileThumbnailDemoCode} />
    </div>
  )
}

const fileThumbnailDemoCode = `"use client"

import * as React from "react"
import {
  DocxEditorViewer,
  useDocxEditor,
  useDocxViewerThumbnails,
} from "@extend-ai/react-docx"
import {
  useXlsxViewerController,
  useXlsxViewerThumbnails,
  XlsxViewerProvider,
} from "@extend-ai/react-xlsx"

import { FileThumbnail } from "@/components/extend/file-thumbnail"
import { renderPdfThumbnailUrl } from "@/lib/pdf-thumbnail-utils"

export function PdfAttachmentThumbnail({ fileUrl }) {
  const [imageUrl, setImageUrl] = React.useState(null)

  React.useEffect(() => {
    let isCurrent = true

    renderPdfThumbnailUrl({
      pageIndex: 0,
      url: fileUrl,
      width: 240,
    }).then((nextImageUrl) => {
      if (isCurrent) setImageUrl(nextImageUrl)
    })

    return () => {
      isCurrent = false
    }
  }, [fileUrl])

  return (
    <FileThumbnail
      file={{ name: "contract.pdf", type: "application/pdf" }}
      previewAspectRatio={0.77}
      previewClassName="bg-white"
      previewImageUrl={imageUrl}
      isLoading={!imageUrl}
    />
  )
}

export function DocxAttachmentThumbnail({ file }) {
  const editor = useDocxEditor({ initialFileName: file.name })
  const { thumbnails } = useDocxViewerThumbnails(editor, {
    pixelRatio: 2,
    resolution: { maxHeight: 324, maxWidth: 240 },
  })
  const firstThumbnail = thumbnails[0]

  React.useEffect(() => {
    void editor.importDocxFile(file)
  }, [editor, file])

  return (
    <>
      <FileThumbnail
        file={file}
        previewAspectRatio={firstThumbnail?.aspectRatio ?? 0.77}
        previewClassName="bg-white"
        previewContent={
          firstThumbnail ? (
            <canvas
              ref={firstThumbnail.canvasRef}
              width={firstThumbnail.pixelWidthPx}
              height={firstThumbnail.pixelHeightPx}
              className="!size-full bg-white object-cover object-top"
            />
          ) : null
        }
        isLoading={!firstThumbnail}
      />
      <div className="pointer-events-none fixed -z-10 opacity-0">
        <DocxEditorViewer editor={editor} mode="read-only" />
      </div>
    </>
  )
}

export function XlsxAttachmentThumbnail({ workbookBuffer }) {
  const [imageUrl, setImageUrl] = React.useState(null)
  const controller = useXlsxViewerController({
    file: workbookBuffer,
    fileName: "workbook.xlsx",
    readOnly: true,
    useWorker: true,
  })

  return (
    <XlsxViewerProvider controller={controller}>
      <XlsxThumbnailCapture onImageUrl={setImageUrl} />
      <FileThumbnail
        file={{ name: "workbook.xlsx", type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }}
        previewAspectRatio={11 / 7}
        previewClassName="bg-white [&>img]:object-left-top"
        previewImageUrl={imageUrl}
        isLoading={!imageUrl}
      />
    </XlsxViewerProvider>
  )
}

function XlsxThumbnailCapture({ onImageUrl }) {
  const { thumbnails } = useXlsxViewerThumbnails({
    includeHeaders: true,
    resolution: { maxHeight: 520, maxWidth: 520 },
  })

  React.useEffect(() => {
    const thumbnail = thumbnails[0]
    if (!thumbnail) return

    const canvas = document.createElement("canvas")
    canvas.width = thumbnail.width
    canvas.height = thumbnail.height
    if (thumbnail.paint(canvas)) {
      onImageUrl(canvas.toDataURL("image/png"))
    }
  }, [onImageUrl, thumbnails])

  return null
}`

const fileThumbnailSourceCode =
  '"use client"\n\nimport * as React from "react"\n\nexport type ThumbnailFile = {\n  name: string\n  type: string\n}\n\nexport type FileThumbnailProps = {\n  file: ThumbnailFile | File\n  className?: string\n  previewAspectRatio?: number\n  previewClassName?: string\n  previewContent?: React.ReactNode\n  previewImageUrl?: string | null\n  isLoading?: boolean\n  hasError?: boolean\n}\n\nfunction cx(...classes: Array<string | false | null | undefined>) {\n  return classes.filter(Boolean).join(" ")\n}\n\n// Preview URLs that have completed a reveal this session. View/tab switches\n// remount thumbnails; URLs in this set render instantly instead of replaying\n// the blur-in, so only an image\'s first load animates.\nconst revealedPreviewImageUrls = new Set<string>()\n\nexport function FileThumbnailLoadingOverlay() {\n  return (\n    <div\n      aria-hidden="true"\n      className="absolute inset-0 z-10 overflow-hidden bg-muted"\n    >\n      <div className="absolute inset-0 bg-muted" />\n      <div className="absolute inset-0 animate-pulse bg-background/55 motion-reduce:animate-none" />\n    </div>\n  )\n}\n\nexport function FileThumbnail({\n  className,\n  previewAspectRatio,\n  previewClassName,\n  previewContent,\n  previewImageUrl,\n  isLoading = false,\n  hasError = false,\n}: FileThumbnailProps) {\n  const imageRef = React.useRef<HTMLImageElement | null>(null)\n  const revealFrameRef = React.useRef<number | null>(null)\n  const [loadedPreviewImageUrl, setLoadedPreviewImageUrl] = React.useState<\n    string | null\n  >(() =>\n    previewImageUrl && revealedPreviewImageUrls.has(previewImageUrl)\n      ? previewImageUrl\n      : null\n  )\n  const [failedPreviewImageUrl, setFailedPreviewImageUrl] = React.useState<\n    string | null\n  >(null)\n  const imageFailed = Boolean(\n    previewImageUrl && failedPreviewImageUrl === previewImageUrl\n  )\n  const isImageLoading = Boolean(\n    previewImageUrl &&\n      loadedPreviewImageUrl !== previewImageUrl &&\n      !imageFailed &&\n      !revealedPreviewImageUrls.has(previewImageUrl)\n  )\n  const showLoading = isLoading || isImageLoading\n  const hasPreviewContent = Boolean(previewContent)\n  const showFallback =\n    !showLoading &&\n    (hasError || imageFailed || (!previewImageUrl && !hasPreviewContent))\n  const cancelImageReveal = React.useCallback(() => {\n    if (revealFrameRef.current === null) return\n\n    window.cancelAnimationFrame(revealFrameRef.current)\n    revealFrameRef.current = null\n  }, [])\n  const markImageLoaded = React.useCallback(\n    (image: HTMLImageElement, imageUrl: string | null | undefined) => {\n      if (!imageUrl) return\n\n      const didLoad = image.naturalWidth > 0 && image.naturalHeight > 0\n\n      setFailedPreviewImageUrl(didLoad ? null : imageUrl)\n      if (didLoad) {\n        revealedPreviewImageUrls.add(imageUrl)\n        cancelImageReveal()\n        revealFrameRef.current = window.requestAnimationFrame(() => {\n          revealFrameRef.current = window.requestAnimationFrame(() => {\n            setLoadedPreviewImageUrl(imageUrl)\n            revealFrameRef.current = null\n          })\n        })\n      }\n    },\n    [cancelImageReveal]\n  )\n\n  React.useEffect(() => {\n    cancelImageReveal()\n  }, [cancelImageReveal, previewImageUrl])\n\n  React.useEffect(() => cancelImageReveal, [cancelImageReveal])\n\n  React.useEffect(() => {\n    const image = imageRef.current\n\n    if (!image || !previewImageUrl) return\n\n    if (image.complete) {\n      markImageLoaded(image, previewImageUrl)\n    }\n  }, [markImageLoaded, previewImageUrl])\n\n  return (\n    <div\n      className={cx(\n        "group overflow-hidden rounded-lg border bg-background text-foreground",\n        className\n      )}\n    >\n      <div\n        className={cx(\n          "relative aspect-square overflow-hidden bg-muted [contain:layout_paint]",\n          previewClassName\n        )}\n        style={\n          previewAspectRatio\n            ? { aspectRatio: String(previewAspectRatio) }\n            : undefined\n        }\n      >\n        {previewImageUrl ? (\n          // eslint-disable-next-line @next/next/no-img-element -- Preview URLs can be transient object or presigned URLs outside Next image optimization.\n          <img\n            ref={imageRef}\n            src={previewImageUrl}\n            alt=""\n            draggable={false}\n            loading="lazy"\n            decoding="async"\n            className={cx(\n              "absolute inset-0 block size-full object-cover transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",\n              showLoading ? "opacity-0 blur-sm" : "blur-0 opacity-100"\n            )}\n            onLoad={(event) => {\n              markImageLoaded(event.currentTarget, previewImageUrl)\n            }}\n            onError={() => {\n              if (previewImageUrl) {\n                revealedPreviewImageUrls.delete(previewImageUrl)\n                cancelImageReveal()\n                setFailedPreviewImageUrl(previewImageUrl)\n                setLoadedPreviewImageUrl((currentUrl) =>\n                  currentUrl === previewImageUrl ? null : currentUrl\n                )\n              }\n            }}\n          />\n        ) : null}\n        {previewContent ? (\n          <div\n            className={cx(\n              "absolute inset-0 size-full transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",\n              showLoading ? "opacity-0 blur-sm" : "blur-0 opacity-100"\n            )}\n          >\n            {previewContent}\n          </div>\n        ) : null}\n        {showLoading ? <FileThumbnailLoadingOverlay /> : null}\n        {showFallback ? (\n          <div className="absolute inset-0 bg-muted" aria-hidden="true" />\n        ) : null}\n      </div>\n    </div>\n  )\n}\n'

export function FileThumbnailSource() {
  return (
    <DocsSourceCodeBlock
      code={fileThumbnailSourceCode}
      fileName="components/extend/file-thumbnail.tsx"
    />
  )
}