feat(transcode): add PDF preview, sprite generation, and annotation support

This commit is contained in:
yiling
2026-07-18 10:32:38 +08:00
parent 3383079787
commit bc1491bed5
31 changed files with 928 additions and 46 deletions
@@ -11,6 +11,7 @@ type FilePreviewItem = {
originalWidth?: number
originalHeight?: number
duration?: number
pageCount?: number
} | null
}
@@ -22,23 +23,30 @@ interface FilePreviewProps {
export const FilePreview = ({ item, showDuration = false }: FilePreviewProps) => {
const isVideo = item.preview?.mediaType?.startsWith('video/')
const isAudio = item.preview?.mediaType?.startsWith('audio/')
const isPdf = item.preview?.mediaType === 'application/pdf'
const hasDuration = isVideo || isAudio
const duration = item.preview?.duration
const durationOverlay =
const pageCount = item.preview?.pageCount
const overlay =
showDuration && hasDuration && typeof duration === 'number' && duration > 0 ? (
<span className="pointer-events-none absolute bottom-1 right-1 text-xs font-medium tabular-nums text-white">
<span className="pointer-events-none absolute bottom-1 right-1 rounded bg-black/60 px-1 py-0.5 text-xs font-medium tabular-nums text-white">
{formatTime(duration)}
</span>
) : showDuration && isPdf && typeof pageCount === 'number' && pageCount > 0 ? (
<span className="pointer-events-none absolute bottom-1 right-1 rounded bg-black/60 px-1 py-0.5 text-xs font-medium tabular-nums text-white">
{pageCount} P
</span>
) : null
const isVideoWithSprite =
isVideo &&
const isMediaWithSprite =
(isVideo || isPdf) &&
item.preview?.spriteUrl &&
item.preview.thumbnailUrl &&
item.preview.originalWidth &&
item.preview.originalHeight
if (isVideoWithSprite && item.preview) {
if (isMediaWithSprite && item.preview) {
return (
<>
<SpriteScrubber
@@ -47,7 +55,7 @@ export const FilePreview = ({ item, showDuration = false }: FilePreviewProps) =>
videoWidth={item.preview.originalWidth!}
videoHeight={item.preview.originalHeight!}
/>
{durationOverlay}
{overlay}
</>
)
}
@@ -60,7 +68,7 @@ export const FilePreview = ({ item, showDuration = false }: FilePreviewProps) =>
alt="Preview"
className="w-full h-full object-contain bg-black"
/>
{durationOverlay}
{overlay}
</>
)
}
@@ -71,7 +79,7 @@ export const FilePreview = ({ item, showDuration = false }: FilePreviewProps) =>
<div className="w-full h-full flex items-center justify-center bg-zinc-950">
<AudioLines className="w-8 h-8 text-zinc-500" />
</div>
{durationOverlay}
{overlay}
</>
)
}
@@ -0,0 +1,14 @@
import { FileTypeDefinition } from '../types'
import PdfViewer from './pdf-viewer'
export const pdfTypeDefinition: FileTypeDefinition = {
id: 'pdf',
name: 'PDF',
match: (file) => file.mediaType === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf'),
viewer: PdfViewer,
commentsConfig: {
hasTimestamp: false,
hasAnnotations: true,
hasAiBots: true,
},
}
@@ -0,0 +1,91 @@
import { ChevronLeft, ChevronRight, Download, Minus, Plus } from 'lucide-react'
import { m } from '@/ui/paraglide/messages.js'
export interface PdfControlBarProps {
currentPage: number
totalPages: number
onPageChange: (newPage: number) => void
zoom: number
onZoomIn: () => void
onZoomOut: () => void
onFit: () => void
onDownload: () => void
canDownload: boolean
}
export function PdfControlBar({
currentPage,
totalPages,
onPageChange,
zoom,
onZoomIn,
onZoomOut,
onFit,
onDownload,
canDownload,
}: PdfControlBarProps) {
return (
<div className="relative px-4 py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-between gap-2 transition-colors duration-200">
{/* Page Navigation */}
<div className="flex items-center gap-1.5 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5">
<button
onClick={() => onPageChange(Math.max(1, currentPage - 1))}
disabled={currentPage <= 1}
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors disabled:opacity-40"
title={m.previous_page()}
>
<ChevronLeft size={16} />
</button>
<span className="px-2 text-xs font-mono font-medium text-gray-900 dark:text-gray-100 select-none">
{m.page_of_pages({ current: currentPage, total: totalPages || 1 })}
</span>
<button
onClick={() => onPageChange(Math.min(totalPages, currentPage + 1))}
disabled={currentPage >= totalPages}
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors disabled:opacity-40"
title={m.next_page()}
>
<ChevronRight size={16} />
</button>
</div>
{/* Zoom & Action Controls */}
<div className="flex items-center gap-2">
<div className="flex items-center gap-1 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5">
<button
onClick={onZoomOut}
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
title={m.zoom_out()}
>
<Minus size={16} />
</button>
<span className="w-12 text-center text-xs font-mono font-medium text-gray-900 dark:text-gray-100 select-none">
{Math.round(zoom * 100)}%
</span>
<button
onClick={onZoomIn}
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
title={m.zoom_in()}
>
<Plus size={16} />
</button>
</div>
<button
onClick={onFit}
className="text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent"
>
{m.fit()}
</button>
<button
onClick={onDownload}
disabled={!canDownload}
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50"
title={m.download_original_file()}
>
<Download size={14} />
{m.download()}
</button>
</div>
</div>
)
}
@@ -0,0 +1,257 @@
import { client } from '@/ui/api/client'
import DrawingCanvas from '@/ui/components/drawing-canvas'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
import * as pdfjsLib from 'pdfjs-dist'
import React, { useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react'
import { FileViewerProps, MediaController } from '../types'
import { PdfControlBar } from './pdf-control-bar'
if (typeof window !== 'undefined' && pdfjsLib.GlobalWorkerOptions) {
pdfjsLib.GlobalWorkerOptions.workerSrc = `https://unpkg.com/pdfjs-dist@${pdfjsLib.version}/build/pdf.worker.min.mjs`
}
export const PdfViewer = React.forwardRef<MediaController, FileViewerProps>(
({ file, annotations, shareId, children }, ref) => {
useImperativeHandle(ref, () => ({
play: () => {},
pause: () => {},
seekTo: () => {},
}))
const {
isDrawing,
currentTool,
currentColor,
addAnnotation,
annotations: draftAnnotations,
} = useAnnotationStore()
const [pdfDoc, setPdfDoc] = useState<pdfjsLib.PDFDocumentProxy | null>(null)
const [currentPage, setCurrentPage] = useState(1)
const [totalPages, setTotalPages] = useState(1)
const [pageImageUrl, setPageImageUrl] = useState<string>('')
const [pageDimensions, setPageDimensions] = useState({ width: 800, height: 1000 })
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 })
const [zoom, setZoom] = useState(1)
const [pan, setPan] = useState({ x: 0, y: 0 })
const observerRef = useRef<ResizeObserver | null>(null)
const containerRef = useCallback((node: HTMLDivElement | null) => {
if (observerRef.current) {
observerRef.current.disconnect()
observerRef.current = null
}
if (node !== null) {
const observer = new ResizeObserver((entries) => {
const entry = entries[0]
if (entry) {
setContainerSize({
width: entry.contentRect.width,
height: entry.contentRect.height,
})
}
})
observer.observe(node)
observerRef.current = observer
}
}, [])
const fileUrl = file.media?.original?.downloadUrl
// Load PDF Document
useEffect(() => {
if (!fileUrl) {
setError('No PDF URL available')
setLoading(false)
return
}
let active = true
setLoading(true)
setError(null)
const loadingTask = pdfjsLib.getDocument({ url: fileUrl })
loadingTask.promise
.then((doc) => {
if (!active) return
setPdfDoc(doc)
setTotalPages(doc.numPages)
setCurrentPage(1)
setLoading(false)
})
.catch((err) => {
if (!active) return
console.error('Failed to load PDF:', err)
setError('Failed to load PDF document')
setLoading(false)
})
return () => {
active = false
}
}, [fileUrl])
// Render active PDF page into image
useEffect(() => {
if (!pdfDoc) return
let active = true
pdfDoc
.getPage(currentPage)
.then((page) => {
if (!active) return
const unscaledViewport = page.getViewport({ scale: 1.0 })
const renderScale = 2.0
const viewport = page.getViewport({ scale: renderScale })
const canvas = document.createElement('canvas')
canvas.width = viewport.width
canvas.height = viewport.height
const ctx = canvas.getContext('2d')
if (!ctx) return
page
.render({ canvasContext: ctx, viewport, canvas })
.promise.then(() => {
if (!active) return
setPageImageUrl(canvas.toDataURL('image/png'))
setPageDimensions({
width: unscaledViewport.width,
height: unscaledViewport.height,
})
})
.catch((err) => {
console.error('Failed to render page:', err)
})
})
.catch((err) => {
console.error('Failed to get page:', err)
})
return () => {
active = false
}
}, [pdfDoc, currentPage])
const conW = containerSize.width
const conH = containerSize.height
const pdfW = pageDimensions.width
const pdfH = pageDimensions.height
let baseScale = 1
if (conW > 0 && conH > 0 && pdfW > 0 && pdfH > 0) {
baseScale = Math.min(conW / pdfW, conH / pdfH)
}
useEffect(() => {
if (conW > 0 && conH > 0 && pdfW > 0 && pdfH > 0) {
setZoom(baseScale)
const x = (conW - pdfW * baseScale) / 2
const y = (conH - pdfH * baseScale) / 2
setPan({ x, y })
}
}, [file.id, currentPage, conW, conH, baseScale, pdfW, pdfH])
const handleZoom = (factor: number) => {
const cx = conW / 2
const cy = conH / 2
const newZoom = zoom * factor
if (newZoom < 0.01 || newZoom > 50) return
const newPanX = cx - (cx - pan.x) * (newZoom / zoom)
const newPanY = cy - (cy - pan.y) * (newZoom / zoom)
setZoom(newZoom)
setPan({ x: newPanX, y: newPanY })
}
const handleFit = () => {
setZoom(baseScale)
const x = (conW - pdfW * baseScale) / 2
const y = (conH - pdfH * baseScale) / 2
setPan({ x, y })
}
const handleDownload = async () => {
const key = file.media?.original?.key
if (!key || !file.id) return
try {
const res = shareId
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
param: { shareId, fileId: file.id },
json: { key },
})
: await client.api.files['download-url'].$post({
json: { key, assetId: file.id },
})
if (!res.ok) return
const { url } = await res.json()
const link = document.createElement('a')
link.href = url
link.download = file.name || 'document.pdf'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch {
// fail silently
}
}
const displayAnnotations = [...(annotations || []), ...draftAnnotations]
return (
<div className="flex flex-col flex-1 h-full overflow-hidden bg-gray-100 dark:bg-gray-950 relative">
<div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
{children}
<div ref={containerRef} className="flex-1 relative overflow-hidden">
{loading ? (
<div className="absolute inset-0 flex items-center justify-center bg-black/40 z-20">
<div className="w-8 h-8 border-4 border-white/30 border-t-white rounded-full animate-spin" />
</div>
) : error ? (
<div className="absolute inset-0 flex items-center justify-center text-gray-500 text-sm">
{error}
</div>
) : (
<DrawingCanvas
width={conW}
height={conH}
mediaDimensions={pageDimensions}
imageUrl={pageImageUrl}
annotations={displayAnnotations}
scale={zoom}
offset={pan}
onPan={setPan}
className="absolute inset-0 z-0"
isDrawing={isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={addAnnotation}
/>
)}
</div>
</div>
<PdfControlBar
currentPage={currentPage}
totalPages={totalPages}
onPageChange={setCurrentPage}
zoom={zoom}
onZoomIn={() => handleZoom(1.2)}
onZoomOut={() => handleZoom(0.8)}
onFit={handleFit}
onDownload={handleDownload}
canDownload={!!file.media?.original?.key}
/>
</div>
)
},
)
export default PdfViewer
@@ -2,9 +2,10 @@ import type { AssetInfo } from '@shumai/dtos'
import { FileTypeDefinition } from './types'
import { videoTypeDefinition } from './video'
import { imageTypeDefinition } from './image'
import { pdfTypeDefinition } from './pdf'
import { defaultTypeDefinition } from './default'
const registry: FileTypeDefinition[] = [videoTypeDefinition, imageTypeDefinition]
const registry: FileTypeDefinition[] = [pdfTypeDefinition, videoTypeDefinition, imageTypeDefinition]
export function getViewerForFile(file: AssetInfo | null | undefined): FileTypeDefinition {
if (!file) return defaultTypeDefinition
+5
View File
@@ -2,3 +2,8 @@ declare module '*.css' {
const content: { [className: string]: string }
export default content
}
declare module '*?url' {
const content: string
export default content
}
+3
View File
@@ -475,6 +475,9 @@
"zoom_out": "Zoom Out",
"zoom_in": "Zoom In",
"fit": "Fit",
"previous_page": "Previous Page",
"next_page": "Next Page",
"page_of_pages": "Page {current} of {total}",
"copy_image_to_clipboard": "Copy optimized image to clipboard",
"download_original_image": "Download original image",
+4 -1
View File
@@ -474,7 +474,10 @@
"download_original_file": "下载原始文件",
"zoom_out": "缩小",
"zoom_in": "放大",
"fit": "适应",
"fit": "适应窗口",
"previous_page": "上一页",
"next_page": "下一页",
"page_of_pages": "第 {current} / {total} 页",
"copy_image_to_clipboard": "复制优化图片到剪贴板",
"download_original_image": "下载原始图片",
+3
View File
@@ -451,6 +451,9 @@ export * from "./download_original_file.js";
export * from "./zoom_out.js";
export * from "./zoom_in.js";
export * from "./fit.js";
export * from "./previous_page.js";
export * from "./next_page.js";
export * from "./page_of_pages.js";
export * from "./copy_image_to_clipboard.js";
export * from "./download_original_image.js";
export * from "./no_item_selected.js";
+3
View File
@@ -453,6 +453,9 @@ export * from './download_original_file.js'
export * from './zoom_out.js'
export * from './zoom_in.js'
export * from './fit.js'
export * from './previous_page.js'
export * from './next_page.js'
export * from './page_of_pages.js'
export * from './copy_image_to_clipboard.js'
export * from './download_original_image.js'
export * from './no_item_selected.js'
+1 -1
View File
@@ -10,7 +10,7 @@ const en_fit = /** @type {(inputs: FitInputs) => LocalizedString} */ () => {
};
const zh_fit = /** @type {(inputs: FitInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`适应`)
return /** @type {LocalizedString} */ (`适应窗口`)
};
/**
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Next Page" |
*
* @param {Next_PageInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const next_page: ((inputs?: Next_PageInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Next_PageInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Next_PageInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Next_PageInputs */
const en_next_page = /** @type {(inputs: Next_PageInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Next Page`)
};
const zh_next_page = /** @type {(inputs: Next_PageInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`下一页`)
};
/**
* | output |
* | --- |
* | "Next Page" |
*
* @param {Next_PageInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const next_page = /** @type {((inputs?: Next_PageInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Next_PageInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_next_page(inputs)
return zh_next_page(inputs)
});
+19
View File
@@ -0,0 +1,19 @@
/**
* | output |
* | --- |
* | "Page {current} of {total}" |
*
* @param {Page_Of_PagesInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const page_of_pages: ((inputs: Page_Of_PagesInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Page_Of_PagesInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Page_Of_PagesInputs = {
current: NonNullable<unknown>;
total: NonNullable<unknown>;
};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{ current: NonNullable<unknown>, total: NonNullable<unknown> }} Page_Of_PagesInputs */
const en_page_of_pages = /** @type {(inputs: Page_Of_PagesInputs) => LocalizedString} */ (i) => {
return /** @type {LocalizedString} */ (`Page ${i?.current} of ${i?.total}`)
};
const zh_page_of_pages = /** @type {(inputs: Page_Of_PagesInputs) => LocalizedString} */ (i) => {
return /** @type {LocalizedString} */ (`第 ${i?.current} / ${i?.total} 页`)
};
/**
* | output |
* | --- |
* | "Page {current} of {total}" |
*
* @param {Page_Of_PagesInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const page_of_pages = /** @type {((inputs: Page_Of_PagesInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Page_Of_PagesInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_page_of_pages(inputs)
return zh_page_of_pages(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Previous Page" |
*
* @param {Previous_PageInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const previous_page: ((inputs?: Previous_PageInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Previous_PageInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Previous_PageInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Previous_PageInputs */
const en_previous_page = /** @type {(inputs: Previous_PageInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Previous Page`)
};
const zh_previous_page = /** @type {(inputs: Previous_PageInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`上一页`)
};
/**
* | output |
* | --- |
* | "Previous Page" |
*
* @param {Previous_PageInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const previous_page = /** @type {((inputs?: Previous_PageInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Previous_PageInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_previous_page(inputs)
return zh_previous_page(inputs)
});