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
+1
View File
@@ -2021,6 +2021,7 @@ export class AssetService {
originalWidth: asset.media.metadata?.originalWidth,
spriteUrl,
duration: asset.media.metadata?.duration,
pageCount: asset.media.metadata?.totalFrames,
}
}
+133
View File
@@ -287,6 +287,139 @@ export class TranscodeService {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
}
async generatePdfSprite(
inputFile: string,
outputSprite: string,
outputPoster: string,
): Promise<{ pageCount: number; originalWidth: number; originalHeight: number }> {
const tmpDir = this.createTempDir('pdf-sprite-')
try {
const pagePrefix = path.join(tmpDir, 'page')
try {
await execFileAsync('pdftoppm', ['-png', '-f', '1', '-l', '100', inputFile, pagePrefix])
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
if (msg.includes('pdftoppm') || msg.includes('ENOENT') || msg.includes('not found')) {
throw new Error(
`pdftoppm executable not found in $PATH. Please install poppler-utils / poppler. (${msg})`,
{ cause: err },
)
}
throw err
}
const files = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.png'))
if (files.length === 0) {
throw new Error('pdftoppm produced no image outputs')
}
files.sort((a, b) => {
const numA = parseInt(a.replace(/[^0-9]/g, ''), 10)
const numB = parseInt(b.replace(/[^0-9]/g, ''), 10)
return numA - numB
})
const extractedCount = files.length
const firstPagePath = path.join(tmpDir, files[0])
const firstMeta = await sharp(firstPagePath, { limitInputPixels: false }).metadata()
const originalWidth = firstMeta.width || 800
const originalHeight = firstMeta.height || 1000
for (let f = 1; f <= 100; f++) {
const pageIdx = Math.min(extractedCount - 1, Math.floor(((f - 1) * extractedCount) / 100))
const srcPath = path.join(tmpDir, files[pageIdx])
const destPath = path.join(tmpDir, `frame_${f}.png`)
if (srcPath !== destPath) {
fs.copyFileSync(srcPath, destPath)
}
}
const spriteArgs = [
'-i',
path.join(tmpDir, 'frame_%d.png'),
'-filter_complex',
'scale=w=480:h=-2,tile=10x10',
'-frames:v',
'1',
'-c:v',
'libwebp',
'-q:v',
'75',
outputSprite,
]
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...spriteArgs])
await sharp(firstPagePath, { limitInputPixels: false })
.resize(480, null, { withoutEnlargement: true, fit: 'inside' })
.webp({ quality: 75 })
.toFile(outputPoster)
let totalPages = extractedCount
try {
const { stdout } = await execFileAsync('pdfinfo', [inputFile])
const match = stdout.match(/Pages:\s+(\d+)/)
if (match) {
totalPages = parseInt(match[1], 10)
}
} catch {
// Fallback to extracted count if pdfinfo is unavailable
}
return {
pageCount: totalPages,
originalWidth,
originalHeight,
}
} finally {
this.removeDir(tmpDir)
}
}
async getPdfInfo(inputFile: string): Promise<MediaMetadata> {
const tmpDir = this.createTempDir('pdf-info-')
let originalWidth = 800
let originalHeight = 1000
let pageCount = 1
try {
const pagePrefix = path.join(tmpDir, 'page')
await execFileAsync('pdftoppm', ['-png', '-f', '1', '-l', '1', inputFile, pagePrefix])
const files = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.png'))
if (files.length > 0) {
const meta = await sharp(path.join(tmpDir, files[0]), {
limitInputPixels: false,
}).metadata()
originalWidth = meta.width || 800
originalHeight = meta.height || 1000
}
} catch (err) {
console.warn('pdftoppm not available for PDF dimensions extraction:', err)
}
try {
const { stdout } = await execFileAsync('pdfinfo', [inputFile])
const match = stdout.match(/Pages:\s+(\d+)/)
if (match) {
pageCount = parseInt(match[1], 10)
}
} catch {
// Fallback
} finally {
this.removeDir(tmpDir)
}
return {
originalWidth,
originalHeight,
duration: 0,
bitRate: 0,
frameRate: 0,
totalFrames: pageCount,
hasAudio: false,
mimeType: 'application/pdf',
}
}
async extractAudio(inputFile: string, outputFile: string, bitrate: string): Promise<void> {
const args = ['-i', inputFile, '-vn', '-acodec', 'libmp3lame', '-b:a', bitrate, outputFile]
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
+9 -2
View File
@@ -18,7 +18,7 @@ import {
PresignedUrl,
TaskInfo,
} from '@shumai/dtos'
import { ImageTranscoder, VideoTranscoder } from '@shumai/transcode'
import { ImageTranscoder, PdfTranscoder, VideoTranscoder } from '@shumai/transcode'
import { generateKeyBetween } from 'jittered-fractional-indexing'
import { ulid } from 'ulid'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
@@ -303,6 +303,7 @@ export class UploadService {
const isVideo = asset.mediaType?.startsWith('video/')
const isImage = asset.mediaType?.startsWith('image/')
const isAudio = asset.mediaType?.startsWith('audio/')
const isPdf = asset.mediaType === 'application/pdf' || asset.name.toLowerCase().endsWith('.pdf')
if (autofillAgent && (isVideo || isImage)) {
await tx.workflowTask.create({
@@ -320,7 +321,7 @@ export class UploadService {
})
}
if (!isVideo && !isImage && !isAudio) {
if (!isVideo && !isImage && !isAudio && !isPdf) {
await tx.asset.update({
where: { id: asset.id },
data: { status: AssetStatus.processed },
@@ -341,6 +342,12 @@ export class UploadService {
} else if (isImage) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new ImageTranscoder(tx as any, asset.id, team.id, projectId).withThumbnail().submit()
} else if (isPdf) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new PdfTranscoder(tx as any, asset.id, team.id, projectId)
.withSprite()
.withPoster()
.submit()
}
}
}
+1
View File
@@ -14,6 +14,7 @@ export const previewInfoSchema = z.object({
originalWidth: z.number().optional(),
spriteUrl: z.string().optional(),
duration: z.number().optional(),
pageCount: z.number().optional(),
})
export type PreviewInfo = z.infer<typeof previewInfoSchema>
@@ -3,7 +3,7 @@ import { s3Service } from '@shumai/core/src/s3/s3'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { transcodeService } from '@shumai/core'
import { transcodeService } from '@shumai/core/src/transcode/transcode'
import * as child_process from 'child_process'
vi.mock('child_process', () => ({
@@ -39,10 +39,25 @@ vi.mock('@shumai/core/src/transcode/transcode', () => ({
getVideoInfo: vi.fn(),
getAudioInfo: vi.fn(),
getImageInfo: vi.fn(),
getPdfInfo: vi.fn().mockResolvedValue({
originalWidth: 800,
originalHeight: 1000,
duration: 0,
bitRate: 0,
frameRate: 0,
totalFrames: 10,
hasAudio: false,
mimeType: 'application/pdf',
}),
transcodeVideo: vi.fn(),
transcodeAudio: vi.fn(),
transcodeImage: vi.fn(),
generateSprite: vi.fn(),
generatePdfSprite: vi.fn().mockResolvedValue({
pageCount: 10,
originalWidth: 800,
originalHeight: 1000,
}),
createTempDir: vi.fn().mockReturnValue('/tmp'),
removeDir: vi.fn(),
takeScreenshots: vi.fn(),
+40 -7
View File
@@ -1,6 +1,6 @@
import { prisma, WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core'
import { transcodeService } from '@shumai/core/src/transcode/transcode'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { stemFromKey } from '@shumai/core/src/utils/filename'
import { ApplicationFailure } from '@temporalio/activity'
@@ -163,6 +163,25 @@ export async function getMediaInfoActivity(params: {
{ key: 'resolution_width', value: info.originalWidth },
{ key: 'resolution_height', value: info.originalHeight },
)
} else if (params.mediaType === 'application/pdf') {
const info = await transcodeService.getPdfInfo(params.filePath)
mediaInfo.frames = info.totalFrames
mediaInfo.metadata = {
originalWidth: info.originalWidth,
originalHeight: info.originalHeight,
duration: 0,
bitRate: 0,
frameRate: 0,
totalFrames: info.totalFrames,
startTimecode: '00:00:00:00',
hasAudio: false,
format: {},
}
metadataUpdates.push(
{ key: 'resolution_width', value: info.originalWidth },
{ key: 'resolution_height', value: info.originalHeight },
{ key: 'total_pages', value: info.totalFrames },
)
}
await metadataService.updateAssetMetadata(params.assetId, metadataUpdates, true)
@@ -401,12 +420,26 @@ export async function generateSpriteActivity(params: GenerateSpriteActivityParam
const posterFile = path.join(tmpDir, 'poster.webp')
try {
await transcodeService.generateSprite(
params.filePath,
spriteFile,
posterFile,
params.mediaInfo.duration,
)
if (params.mediaInfo.mimeType === 'application/pdf') {
const pdfRes = await transcodeService.generatePdfSprite(
params.filePath,
spriteFile,
posterFile,
)
if (params.mediaInfo && params.mediaInfo.metadata) {
params.mediaInfo.metadata.totalFrames = pdfRes.pageCount
params.mediaInfo.metadata.originalWidth = pdfRes.originalWidth
params.mediaInfo.metadata.originalHeight = pdfRes.originalHeight
params.mediaInfo.frames = pdfRes.pageCount
}
} else {
await transcodeService.generateSprite(
params.filePath,
spriteFile,
posterFile,
params.mediaInfo.duration,
)
}
const spriteBuffer = fs.readFileSync(spriteFile)
await s3Service.putObject(
+38
View File
@@ -82,3 +82,41 @@ export class ImageTranscoder {
return task.id
}
}
export class PdfTranscoder {
private spec: PrismaJson.TaskSpec = {}
constructor(
private readonly db: TransactionClient,
private readonly assetId: string,
private readonly teamId: string,
private readonly projectId: string,
) {}
withSprite(): this {
this.spec.sprite = true
return this
}
withPoster(): this {
this.spec.poster = true
return this
}
async submit(): Promise<string> {
const task = await this.db.workflowTask.create({
data: {
assetId: this.assetId,
teamId: this.teamId,
projectId: this.projectId,
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
payload: {
projectId: this.projectId,
transcode: this.spec,
},
},
})
return task.id
}
}
@@ -245,6 +245,89 @@ describe('Transcode Workflow', () => {
})
})
it('should process pdf transcode and sprite generation successfully', async () => {
const task: WorkflowTask = {
id: 'task-pdf',
assetId: 'asset-pdf',
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
sessionId: null,
output: null,
payload: {
projectId: 'proj-1',
transcode: {
sprite: true,
poster: true,
},
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid-pdf',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-pdf',
storageKey: { key: 'document.pdf' },
mediaType: 'application/pdf',
})
mockActivities.getMediaInfoActivity.mockResolvedValue({
mimeType: 'application/pdf',
metadata: {
originalWidth: 800,
originalHeight: 1000,
duration: 0,
frameRate: 0,
totalFrames: 12,
startTimecode: '00:00:00:00',
bitRate: 0,
hasAudio: false,
format: {},
},
videoTranscodes: [],
imageTranscodes: [],
})
mockActivities.generateSpriteActivity.mockResolvedValue({
sprite: { key: 'sprite.webp', frames: 100, tileX: 10, tileY: 10 },
poster: { key: 'poster.webp' },
})
await transcodeMedia(task)
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
assetId: 'asset-pdf',
status: AssetStatus.processing,
})
expect(mockActivities.generateSpriteActivity).toHaveBeenCalledWith({
assetKey: 'document.pdf',
filePath: '/tmp/video.mp4',
spriteSpec: expect.objectContaining({ key: 'sprite.webp' }),
posterSpec: expect.objectContaining({ key: 'poster.webp' }),
mediaInfo: expect.objectContaining({ mimeType: 'application/pdf' }),
})
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith({
assetId: 'asset-pdf',
mediaInfo: expect.objectContaining({
sprite: { key: 'sprite.webp', frames: 100, tileX: 10, tileY: 10 },
poster: { key: 'poster.webp' },
}),
})
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
assetId: 'asset-pdf',
status: AssetStatus.processed,
})
})
it('should handle failures and update task status with error', async () => {
const task: WorkflowTask = {
id: 'task-fail',
@@ -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)
});