mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 10:55:27 +00:00
feat(comments): add printable comments page with frame thumbnails and markup overlays (#550)
* feat(comments): add printable comments page with frame thumbnails and markup overlays * fix(comments): guarantee frame-accurate ffmpeg seeking for printable comment thumbnails * fix(comments): address printable comments review findings
This commit is contained in:
@@ -154,7 +154,8 @@ describe('FileViewerRightSidebar - Comments Export', () => {
|
||||
expect(screen.getByRole('button', { name: 'More options' })).toBeDefined()
|
||||
})
|
||||
|
||||
it('does NOT render "All comments" header row in public share view', async () => {
|
||||
it('renders "All comments" header with Print Comments (and without Export Comments) in public share view', async () => {
|
||||
const windowOpenSpy = vi.spyOn(window, 'open').mockImplementation(() => null)
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<FileViewerRightSidebar
|
||||
@@ -169,8 +170,49 @@ describe('FileViewerRightSidebar - Comments Export', () => {
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.queryByText('All comments')).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: 'More options' })).toBeNull()
|
||||
expect(screen.getByText('All comments')).toBeDefined()
|
||||
const moreButton = screen.getByRole('button', { name: 'More options' })
|
||||
fireEvent.pointerDown(moreButton, { button: 0, ctrlKey: false })
|
||||
|
||||
const printItem = await screen.findByText('Print Comments')
|
||||
expect(printItem).toBeDefined()
|
||||
expect(screen.queryByText('Export Comments')).toBeNull()
|
||||
|
||||
fireEvent.click(printItem)
|
||||
expect(windowOpenSpy).toHaveBeenCalledWith(
|
||||
'/print/comments/file-123?shareId=share-123',
|
||||
'_blank',
|
||||
'noopener,noreferrer',
|
||||
)
|
||||
windowOpenSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('opens printable comments page from authenticated sidebar menu', async () => {
|
||||
const windowOpenSpy = vi.spyOn(window, 'open').mockImplementation(() => null)
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<FileViewerRightSidebar
|
||||
teamId="team-1"
|
||||
projectId="proj-1"
|
||||
file={mockFile}
|
||||
onSaveField={vi.fn()}
|
||||
members={[{ id: 'user-1', name: 'User One', role: 'owner' }]}
|
||||
isPublic={false}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
const moreButton = screen.getByRole('button', { name: 'More options' })
|
||||
fireEvent.pointerDown(moreButton, { button: 0, ctrlKey: false })
|
||||
|
||||
const printItem = await screen.findByText('Print Comments')
|
||||
fireEvent.click(printItem)
|
||||
expect(windowOpenSpy).toHaveBeenCalledWith(
|
||||
'/print/comments/file-123',
|
||||
'_blank',
|
||||
'noopener,noreferrer',
|
||||
)
|
||||
windowOpenSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('opens dropdown menu with Export Comments and the 4 NLE options', async () => {
|
||||
|
||||
@@ -88,6 +88,15 @@ export function FileViewerRightSidebar({
|
||||
second?: number | null
|
||||
} | null>(null)
|
||||
|
||||
const handlePrintComments = () => {
|
||||
if (!file?.id) return
|
||||
const url =
|
||||
isPublic && shareId
|
||||
? `/print/comments/${encodeURIComponent(file.id)}?shareId=${encodeURIComponent(shareId)}`
|
||||
: `/print/comments/${encodeURIComponent(file.id)}`
|
||||
window.open(url, '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
|
||||
const handleExportComments = async (format: CommentExportFormat) => {
|
||||
if (!file?.id || isExporting) return
|
||||
try {
|
||||
@@ -361,21 +370,21 @@ export function FileViewerRightSidebar({
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="comments" className="flex-1 flex flex-col overflow-hidden min-h-0 mt-0">
|
||||
{!isPublic && (
|
||||
<div className="flex items-center justify-between px-1 py-1.5 shrink-0 border-b border-border/50">
|
||||
<span className="text-xs font-semibold text-foreground">{m.all_comments()}</span>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6 text-muted-foreground hover:text-foreground cursor-pointer"
|
||||
aria-label={m.more_options()}
|
||||
>
|
||||
<MoreHorizontal className="size-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<div className="flex items-center justify-between px-1 py-1.5 shrink-0 border-b border-border/50">
|
||||
<span className="text-xs font-semibold text-foreground">{m.all_comments()}</span>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6 text-muted-foreground hover:text-foreground cursor-pointer"
|
||||
aria-label={m.more_options()}
|
||||
>
|
||||
<MoreHorizontal className="size-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
{!isPublic && (
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger className="cursor-pointer">
|
||||
<span>{m.export_comments()}</span>
|
||||
@@ -396,10 +405,13 @@ export function FileViewerRightSidebar({
|
||||
))}
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
<DropdownMenuItem className="cursor-pointer" onClick={handlePrintComments}>
|
||||
<span>{m.print_comments()}</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
<ScrollArea className="flex-1 min-h-0 [&>div>div]:block!">
|
||||
<div className="space-y-4 pt-2">
|
||||
{comments.map((comment) => (
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import React from 'react'
|
||||
|
||||
export function parseAnnotations(raw: unknown): Annotation[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const valid: Annotation[] = []
|
||||
for (const item of raw) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
const rec = item as Record<string, unknown>
|
||||
const type = rec.type
|
||||
const color = rec.color
|
||||
const points = rec.points
|
||||
if (
|
||||
(type === 'box' || type === 'line' || type === 'arrow' || type === 'freehand') &&
|
||||
typeof color === 'string' &&
|
||||
Array.isArray(points) &&
|
||||
points.length >= 2 &&
|
||||
points.every(
|
||||
(pt) =>
|
||||
Array.isArray(pt) &&
|
||||
pt.length >= 2 &&
|
||||
typeof pt[0] === 'number' &&
|
||||
typeof pt[1] === 'number',
|
||||
)
|
||||
) {
|
||||
valid.push({
|
||||
type,
|
||||
color,
|
||||
points: points as [number, number][],
|
||||
} as Annotation)
|
||||
}
|
||||
}
|
||||
return valid
|
||||
}
|
||||
|
||||
interface AnnotationOverlaySvgProps {
|
||||
annotations: Annotation[]
|
||||
width: number
|
||||
height: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
function buildFreehandPath(points: [number, number][], w: number, h: number): string {
|
||||
if (points.length === 0) return ''
|
||||
const scaled = points.map(([nx, ny]) => [nx * w, ny * h] as const)
|
||||
if (scaled.length === 2) {
|
||||
return `M ${scaled[0][0]} ${scaled[0][1]} L ${scaled[1][0]} ${scaled[1][1]}`
|
||||
}
|
||||
|
||||
// Smooth quadratic path matching Konva's tension ~0.5 appearance
|
||||
let d = `M ${scaled[0][0]} ${scaled[0][1]}`
|
||||
for (let i = 1; i < scaled.length - 1; i++) {
|
||||
const midX = (scaled[i][0] + scaled[i + 1][0]) / 2
|
||||
const midY = (scaled[i][1] + scaled[i + 1][1]) / 2
|
||||
d += ` Q ${scaled[i][0]} ${scaled[i][1]} ${midX} ${midY}`
|
||||
}
|
||||
const last = scaled[scaled.length - 1]
|
||||
d += ` L ${last[0]} ${last[1]}`
|
||||
return d
|
||||
}
|
||||
|
||||
/**
|
||||
* Vector SVG overlay for normalized [0..1] comment annotations.
|
||||
* Using inline SVG instead of rasterized canvas ensures sharp markups when
|
||||
* printing or exporting to PDF and avoids browser canvas limits on long lists.
|
||||
*/
|
||||
export const AnnotationOverlaySvg: React.FC<AnnotationOverlaySvgProps> = ({
|
||||
annotations,
|
||||
width,
|
||||
height,
|
||||
className,
|
||||
}) => {
|
||||
if (annotations.length === 0 || width <= 0 || height <= 0) return null
|
||||
|
||||
// Keep stroke visually consistent with DrawingCanvas regardless of image dimensions
|
||||
const baseDim = Math.max(width, height)
|
||||
const strokeWidth = Math.max(1.5, baseDim * 0.014)
|
||||
const headLength = strokeWidth * 3.8
|
||||
const headHalfWidth = strokeWidth * 2.1
|
||||
|
||||
return (
|
||||
<svg
|
||||
viewBox={`0 0 ${width} ${height}`}
|
||||
preserveAspectRatio="none"
|
||||
className={className}
|
||||
data-testid="print-annotation-overlay"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{annotations.map((ann, idx) => {
|
||||
if (ann.type === 'box') {
|
||||
const [start, end] = ann.points
|
||||
const x = Math.min(start[0], end[0]) * width
|
||||
const y = Math.min(start[1], end[1]) * height
|
||||
const boxW = Math.abs(end[0] - start[0]) * width
|
||||
const boxH = Math.abs(end[1] - start[1]) * height
|
||||
return (
|
||||
<rect
|
||||
key={idx}
|
||||
x={x}
|
||||
y={y}
|
||||
width={boxW}
|
||||
height={boxH}
|
||||
fill="none"
|
||||
stroke={ann.color}
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (ann.type === 'line') {
|
||||
const [start, end] = ann.points
|
||||
return (
|
||||
<line
|
||||
key={idx}
|
||||
x1={start[0] * width}
|
||||
y1={start[1] * height}
|
||||
x2={end[0] * width}
|
||||
y2={end[1] * height}
|
||||
stroke={ann.color}
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (ann.type === 'arrow') {
|
||||
const [start, end] = ann.points
|
||||
const x1 = start[0] * width
|
||||
const y1 = start[1] * height
|
||||
const x2 = end[0] * width
|
||||
const y2 = end[1] * height
|
||||
const angle = Math.atan2(y2 - y1, x2 - x1)
|
||||
const lineLen = Math.hypot(x2 - x1, y2 - y1)
|
||||
const clampedHeadLen = Math.min(headLength, lineLen * 0.65)
|
||||
const clampedHalfW = (clampedHeadLen / headLength) * headHalfWidth
|
||||
const baseX = x2 - clampedHeadLen * Math.cos(angle)
|
||||
const baseY = y2 - clampedHeadLen * Math.sin(angle)
|
||||
const leftX = baseX - clampedHalfW * Math.sin(angle)
|
||||
const leftY = baseY + clampedHalfW * Math.cos(angle)
|
||||
const rightX = baseX + clampedHalfW * Math.sin(angle)
|
||||
const rightY = baseY - clampedHalfW * Math.cos(angle)
|
||||
|
||||
return (
|
||||
<g key={idx}>
|
||||
<line
|
||||
x1={x1}
|
||||
y1={y1}
|
||||
x2={baseX}
|
||||
y2={baseY}
|
||||
stroke={ann.color}
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<polygon
|
||||
points={`${x2},${y2} ${leftX},${leftY} ${rightX},${rightY}`}
|
||||
fill={ann.color}
|
||||
/>
|
||||
</g>
|
||||
)
|
||||
}
|
||||
|
||||
if (ann.type === 'freehand') {
|
||||
const d = buildFreehandPath(ann.points, width, height)
|
||||
return (
|
||||
<path
|
||||
key={idx}
|
||||
d={d}
|
||||
fill="none"
|
||||
stroke={ann.color}
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return null
|
||||
})}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import { ImageOff, Loader2 } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { AnnotationOverlaySvg } from './annotation-overlay-svg'
|
||||
|
||||
const BOX_WIDTH = 200
|
||||
const BOX_HEIGHT = 112
|
||||
|
||||
interface CommentFrameThumbnailProps {
|
||||
src: string
|
||||
annotations: Annotation[]
|
||||
alt?: string
|
||||
onStatusChange?: (status: 'loaded' | 'error') => void
|
||||
}
|
||||
|
||||
export const CommentFrameThumbnail: React.FC<CommentFrameThumbnailProps> = ({
|
||||
src,
|
||||
annotations,
|
||||
alt = '',
|
||||
onStatusChange,
|
||||
}) => {
|
||||
const [status, setStatus] = useState<'loading' | 'loaded' | 'error'>('loading')
|
||||
const [naturalSize, setNaturalSize] = useState<{ width: number; height: number }>({
|
||||
width: BOX_WIDTH,
|
||||
height: BOX_HEIGHT,
|
||||
})
|
||||
const imgRef = useRef<HTMLImageElement>(null)
|
||||
const onStatusChangeRef = useRef(onStatusChange)
|
||||
onStatusChangeRef.current = onStatusChange
|
||||
|
||||
useEffect(() => {
|
||||
setStatus('loading')
|
||||
const img = imgRef.current
|
||||
if (img && img.complete && img.naturalWidth > 0) {
|
||||
setNaturalSize({ width: img.naturalWidth, height: img.naturalHeight })
|
||||
setStatus('loaded')
|
||||
onStatusChangeRef.current?.('loaded')
|
||||
}
|
||||
}, [src])
|
||||
|
||||
const handleLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
|
||||
const img = e.currentTarget
|
||||
const nw = img.naturalWidth || BOX_WIDTH
|
||||
const nh = img.naturalHeight || BOX_HEIGHT
|
||||
setNaturalSize({ width: nw, height: nh })
|
||||
setStatus('loaded')
|
||||
onStatusChangeRef.current?.('loaded')
|
||||
}
|
||||
|
||||
const handleError = () => {
|
||||
setStatus('error')
|
||||
onStatusChangeRef.current?.('error')
|
||||
}
|
||||
|
||||
// Fit the actual image rect inside 200x112 while preserving aspect ratio so the
|
||||
// SVG markup overlay aligns accurately for portrait, square, PDF, and ultrawide media.
|
||||
const scale = Math.min(BOX_WIDTH / naturalSize.width, BOX_HEIGHT / naturalSize.height)
|
||||
const fittedWidth = Math.max(1, Math.round(naturalSize.width * scale))
|
||||
const fittedHeight = Math.max(1, Math.round(naturalSize.height * scale))
|
||||
|
||||
return (
|
||||
<div
|
||||
className="relative flex items-center justify-center overflow-hidden rounded-sm border border-border transparency-checkerboard shrink-0"
|
||||
style={{ width: BOX_WIDTH, height: BOX_HEIGHT }}
|
||||
data-testid="print-comment-frame"
|
||||
>
|
||||
{status === 'loading' && (
|
||||
<div
|
||||
className="absolute inset-0 z-10 flex flex-col items-center justify-center gap-1.5 bg-muted/95 text-muted-foreground"
|
||||
data-testid="print-frame-loading"
|
||||
>
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span className="text-[11px] leading-none">{m.print_comments_frame_loading()}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status === 'error' ? (
|
||||
<div
|
||||
className="flex flex-col items-center justify-center gap-1.5 px-2 text-center text-muted-foreground"
|
||||
data-testid="print-frame-error"
|
||||
>
|
||||
<ImageOff className="h-4 w-4" />
|
||||
<span className="text-[11px] leading-tight">{m.print_comments_frame_unavailable()}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="relative"
|
||||
style={{
|
||||
width: status === 'loaded' ? fittedWidth : BOX_WIDTH,
|
||||
height: status === 'loaded' ? fittedHeight : BOX_HEIGHT,
|
||||
}}
|
||||
>
|
||||
<img
|
||||
ref={imgRef}
|
||||
src={src}
|
||||
alt={alt}
|
||||
onLoad={handleLoad}
|
||||
onError={handleError}
|
||||
className={`block h-full w-full object-contain ${
|
||||
status === 'loaded' ? 'opacity-100' : 'opacity-0'
|
||||
}`}
|
||||
/>
|
||||
{status === 'loaded' && annotations.length > 0 && (
|
||||
<AnnotationOverlaySvg
|
||||
annotations={annotations}
|
||||
width={fittedWidth}
|
||||
height={fittedHeight}
|
||||
className="pointer-events-none absolute inset-0 h-full w-full z-10"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { AssetInfo, CommentInfo } from '@shumai/dtos'
|
||||
import { PrintCommentsView } from './print-comments-view'
|
||||
|
||||
function makeComment(overrides: Partial<CommentInfo> = {}): CommentInfo {
|
||||
return {
|
||||
id: 'c-1',
|
||||
assetId: 'asset-1',
|
||||
message: 'Check the color grade here',
|
||||
annotations: null,
|
||||
second: 1.5,
|
||||
creator: { id: 'u-1', name: 'Alice' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: '2026-11-25T14:53:00.000Z',
|
||||
updatedAt: '2026-11-25T14:53:00.000Z',
|
||||
sessionId: null,
|
||||
isCompleted: false,
|
||||
completionLastChangedBy: null,
|
||||
reactionCounts: [],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('PrintCommentsView', () => {
|
||||
let printMock: ReturnType<typeof vi.fn>
|
||||
const originalPrint = window.print
|
||||
|
||||
beforeEach(() => {
|
||||
printMock = vi.fn()
|
||||
Object.defineProperty(window, 'print', {
|
||||
value: printMock,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
Object.defineProperty(window, 'print', {
|
||||
value: originalPrint,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
})
|
||||
|
||||
const videoAsset: AssetInfo = {
|
||||
id: 'asset-video-1',
|
||||
name: '3D_printer_building_model_20261017121617.mp4',
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
sizeByte: 1024,
|
||||
fileCount: 1,
|
||||
proxyType: 'video',
|
||||
preview: { thumbnailUrl: 'https://example.com/thumb.jpg' },
|
||||
creator: { id: 'u-1', name: 'Alice' },
|
||||
createdAt: '2026-11-06T10:00:00.000Z',
|
||||
updatedAt: '2026-11-06T10:00:00.000Z',
|
||||
media: {
|
||||
proxyType: 'video',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
metadata: { frameRate: 24 },
|
||||
},
|
||||
}
|
||||
|
||||
it('renders video comments sorted by timecode with frames, SVG annotations, replies, completed status, reactions, and attachments without auto-printing', () => {
|
||||
const comments: CommentInfo[] = [
|
||||
makeComment({
|
||||
id: 'c-2',
|
||||
second: 5,
|
||||
message: 'Second comment later in timeline',
|
||||
}),
|
||||
makeComment({
|
||||
id: 'c-1',
|
||||
second: 1.5,
|
||||
message: 'First comment <@u-2>',
|
||||
mentions: [{ id: 'u-2', name: 'Bob' }],
|
||||
isCompleted: true,
|
||||
annotations: [
|
||||
{
|
||||
type: 'box',
|
||||
color: '#ef4444',
|
||||
points: [
|
||||
[0.1, 0.1],
|
||||
[0.5, 0.5],
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'arrow',
|
||||
color: '#22c55e',
|
||||
points: [
|
||||
[0.2, 0.2],
|
||||
[0.8, 0.8],
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'line',
|
||||
color: '#3b82f6',
|
||||
points: [
|
||||
[0.1, 0.9],
|
||||
[0.9, 0.1],
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'freehand',
|
||||
color: '#eab308',
|
||||
points: [
|
||||
[0.1, 0.2],
|
||||
[0.2, 0.3],
|
||||
[0.4, 0.35],
|
||||
],
|
||||
},
|
||||
],
|
||||
attachments: [
|
||||
{ id: 'att-1', assetId: 'a-1', url: 'https://example.com/ref-frame.png' },
|
||||
{ id: 'att-2', assetId: 'a-2', url: 'https://example.com/notes.pdf' },
|
||||
],
|
||||
reactionCounts: [
|
||||
{ code: '👍', count: 2, requestingUserReacted: true, creatorNames: ['Bob'] },
|
||||
],
|
||||
replies: [
|
||||
makeComment({
|
||||
id: 'r-1',
|
||||
second: null,
|
||||
message: 'Updated in v2!',
|
||||
creator: { id: 'u-2', name: 'Bob' },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
]
|
||||
|
||||
const { container } = render(
|
||||
<PrintCommentsView
|
||||
asset={videoAsset}
|
||||
breadcrumbs={['Untitled Project', 'Dailies']}
|
||||
comments={comments}
|
||||
/>,
|
||||
)
|
||||
|
||||
// Never auto-trigger print
|
||||
expect(printMock).not.toHaveBeenCalled()
|
||||
|
||||
// Header breadcrumbs & creator
|
||||
expect(screen.getByText('Untitled Project')).toBeDefined()
|
||||
expect(screen.getByText('Dailies')).toBeDefined()
|
||||
expect(screen.getByText('Sorted by timecode')).toBeDefined()
|
||||
|
||||
// Progress indicator while thumbnails are loading
|
||||
expect(screen.getByTestId('print-frames-progress')).toBeDefined()
|
||||
expect(screen.getAllByTestId('print-frame-loading')).toHaveLength(2)
|
||||
|
||||
// Sorted by timecode: c-1 (1.5s) appears before c-2 (5s)
|
||||
const threads = screen.getAllByTestId('print-comment-thread')
|
||||
expect(threads).toHaveLength(2)
|
||||
expect(threads[0].textContent).toContain('First comment')
|
||||
expect(threads[0].textContent).toContain('@Bob')
|
||||
expect(threads[0].textContent).toContain('Updated in v2!')
|
||||
expect(threads[1].textContent).toContain('Second comment later in timeline')
|
||||
|
||||
// Completed badge, reactions, and attachments
|
||||
expect(screen.getByTestId('print-comment-completed').textContent).toContain('Completed')
|
||||
expect(screen.getByTestId('print-comment-reactions').textContent).toContain('👍')
|
||||
expect(screen.getByTestId('print-comment-reactions').textContent).toContain('2')
|
||||
expect(screen.getByTestId('print-comment-attachments').textContent).toContain('ref-frame.png')
|
||||
expect(screen.getByTestId('print-comment-attachments').textContent).toContain('notes.pdf')
|
||||
|
||||
// Frame image requests point to backend frame endpoint
|
||||
const frameImgs = container.querySelectorAll('[data-testid="print-comment-frame"] img')
|
||||
expect(frameImgs).toHaveLength(2)
|
||||
expect(frameImgs[0].getAttribute('src')).toBe(
|
||||
'/api/files/asset-video-1/comments/frame?second=1.5&width=400',
|
||||
)
|
||||
|
||||
// Simulate frame image load -> SVG overlay renders all 4 annotation shapes
|
||||
Object.defineProperty(frameImgs[0], 'naturalWidth', { value: 400, configurable: true })
|
||||
Object.defineProperty(frameImgs[0], 'naturalHeight', { value: 225, configurable: true })
|
||||
fireEvent.load(frameImgs[0])
|
||||
fireEvent.load(frameImgs[1])
|
||||
|
||||
expect(screen.queryByTestId('print-frames-progress')).toBeNull()
|
||||
const overlay = screen.getByTestId('print-annotation-overlay')
|
||||
expect(overlay.querySelector('rect')).not.toBeNull()
|
||||
expect(overlay.querySelector('polygon')).not.toBeNull()
|
||||
expect(overlay.querySelector('path')).not.toBeNull()
|
||||
|
||||
// Clicking Print button invokes window.print()
|
||||
fireEvent.click(screen.getByTestId('print-comments-button'))
|
||||
expect(printMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('uses public share frame endpoint with password query param when shareId is set', () => {
|
||||
const { container } = render(
|
||||
<PrintCommentsView
|
||||
asset={videoAsset}
|
||||
breadcrumbs={['Client Share']}
|
||||
comments={[makeComment({ id: 'c-1', second: 3.25 })]}
|
||||
shareId="share-99"
|
||||
sharePassword="pw!"
|
||||
/>,
|
||||
)
|
||||
|
||||
const img = container.querySelector('[data-testid="print-comment-frame"] img')
|
||||
expect(img?.getAttribute('src')).toBe(
|
||||
'/api/shares/share-99/files/asset-video-1/comments/frame?second=3.25&width=400&p=pw%21',
|
||||
)
|
||||
})
|
||||
|
||||
it('renders an annotated reply at its own timestamp and waits for it before printing', () => {
|
||||
const { container } = render(
|
||||
<PrintCommentsView
|
||||
asset={videoAsset}
|
||||
breadcrumbs={[]}
|
||||
comments={[
|
||||
makeComment({
|
||||
second: 1,
|
||||
replies: [
|
||||
makeComment({
|
||||
id: 'reply',
|
||||
message: '',
|
||||
second: 2,
|
||||
annotations: [
|
||||
{
|
||||
type: 'box',
|
||||
color: 'red',
|
||||
points: [
|
||||
[0.1, 0.1],
|
||||
[0.5, 0.5],
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
]}
|
||||
/>,
|
||||
)
|
||||
|
||||
const [commentFrame, replyFrame] = container.querySelectorAll(
|
||||
'[data-testid="print-comment-frame"] img',
|
||||
)
|
||||
expect(replyFrame?.getAttribute('src')).toContain('second=2&')
|
||||
fireEvent.load(commentFrame)
|
||||
|
||||
const printButton = screen.getByRole<HTMLButtonElement>('button', { name: 'Print' })
|
||||
expect(printButton.disabled).toBe(true)
|
||||
expect(screen.getByTestId('print-frames-progress').textContent).toContain('1/2')
|
||||
fireEvent.load(replyFrame)
|
||||
|
||||
expect(screen.getByTestId('print-reply-item').querySelector('svg rect')).not.toBeNull()
|
||||
expect(printButton.disabled).toBe(false)
|
||||
fireEvent.click(printButton)
|
||||
expect(printMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('reuses image proxy URL directly for image assets without calling frame API', () => {
|
||||
const imageAsset = {
|
||||
...videoAsset,
|
||||
id: 'asset-img-1',
|
||||
name: 'poster.png',
|
||||
proxyType: 'image',
|
||||
media: {
|
||||
proxyType: 'image',
|
||||
imageTranscodes: [
|
||||
{
|
||||
id: 't1',
|
||||
key: 'k1',
|
||||
url: 'https://cdn.example.com/poster-600.webp',
|
||||
width: 600,
|
||||
height: 400,
|
||||
size: 100,
|
||||
},
|
||||
],
|
||||
videoTranscodes: [],
|
||||
},
|
||||
} as unknown as AssetInfo
|
||||
|
||||
const { container } = render(
|
||||
<PrintCommentsView
|
||||
asset={imageAsset}
|
||||
breadcrumbs={['Design']}
|
||||
comments={[makeComment({ id: 'c-img', second: null, message: 'Adjust logo spacing' })]}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Sorted by oldest')).toBeDefined()
|
||||
const img = container.querySelector('[data-testid="print-comment-frame"] img')
|
||||
expect(img?.getAttribute('src')).toBe('https://cdn.example.com/poster-600.webp')
|
||||
})
|
||||
|
||||
it('supports PDF page formatting, 3D angle formatting, and audio without frame column', () => {
|
||||
const pdfAsset = {
|
||||
...videoAsset,
|
||||
id: 'asset-pdf-1',
|
||||
name: 'script.pdf',
|
||||
proxyType: 'pdf',
|
||||
media: { proxyType: 'pdf', imageTranscodes: [], videoTranscodes: [] },
|
||||
} as unknown as AssetInfo
|
||||
|
||||
const { rerender } = render(
|
||||
<PrintCommentsView
|
||||
asset={pdfAsset}
|
||||
breadcrumbs={['Docs']}
|
||||
comments={[makeComment({ id: 'c-pdf', second: 3, message: 'Fix typo on page 3' })]}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('Sorted by page')).toBeDefined()
|
||||
expect(screen.getByTestId('print-comment-timestamp').textContent).toBe('P3')
|
||||
|
||||
const modelAsset = {
|
||||
...videoAsset,
|
||||
id: 'asset-3d-1',
|
||||
name: 'chair.glb',
|
||||
proxyType: '3d',
|
||||
media: { proxyType: '3d', imageTranscodes: [], videoTranscodes: [] },
|
||||
} as unknown as AssetInfo
|
||||
|
||||
rerender(
|
||||
<PrintCommentsView
|
||||
asset={modelAsset}
|
||||
breadcrumbs={['Models']}
|
||||
comments={[makeComment({ id: 'c-3d', second: 3, message: 'Smooth bevel' })]}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('Sorted by angle')).toBeDefined()
|
||||
expect(screen.getByTestId('print-comment-timestamp').textContent).toBe('270°')
|
||||
|
||||
const audioAsset = {
|
||||
...videoAsset,
|
||||
id: 'asset-audio-1',
|
||||
name: 'mix.wav',
|
||||
proxyType: 'audio',
|
||||
preview: null,
|
||||
media: {
|
||||
proxyType: 'audio',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
metadata: { frameRate: 30 },
|
||||
},
|
||||
} as unknown as AssetInfo
|
||||
|
||||
rerender(
|
||||
<PrintCommentsView
|
||||
asset={audioAsset}
|
||||
breadcrumbs={['Audio']}
|
||||
comments={[makeComment({ id: 'c-aud', second: 2, message: 'Reduce reverb' })]}
|
||||
/>,
|
||||
)
|
||||
expect(screen.queryByTestId('print-comment-frame')).toBeNull()
|
||||
})
|
||||
|
||||
it('shows friendly fallback when a frame fails to load', () => {
|
||||
const { container } = render(
|
||||
<PrintCommentsView
|
||||
asset={videoAsset}
|
||||
breadcrumbs={['Project']}
|
||||
comments={[makeComment({ id: 'c-err', second: 2 })]}
|
||||
/>,
|
||||
)
|
||||
|
||||
const img = container.querySelector('[data-testid="print-comment-frame"] img')!
|
||||
fireEvent.error(img)
|
||||
|
||||
expect(screen.getByTestId('print-frame-error').textContent).toContain('Frame unavailable')
|
||||
expect(screen.queryByTestId('print-frames-progress')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,629 @@
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { DrawAnnotation, ShumaiLogo } from '@/ui/components/ui/icons'
|
||||
import { getViewerForFile } from '@/ui/components/viewers/registry'
|
||||
import { formatFrame, formatTimecode } from '@/ui/components/viewers/video/utils'
|
||||
import { isImageFileName } from '@/ui/lib/media'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import type { AssetInfo, CommentInfo } from '@shumai/dtos'
|
||||
import {
|
||||
ArrowDownWideNarrow,
|
||||
CheckCircle2,
|
||||
FileAudio,
|
||||
FileIcon,
|
||||
FileText,
|
||||
Loader2,
|
||||
Printer,
|
||||
} from 'lucide-react'
|
||||
import React, { useCallback, useMemo, useState } from 'react'
|
||||
import Markdown from 'react-markdown'
|
||||
import { parseAnnotations } from './annotation-overlay-svg'
|
||||
import { CommentFrameThumbnail } from './comment-frame-thumbnail'
|
||||
|
||||
export type PrintSortMode = 'position' | 'oldest' | 'newest'
|
||||
|
||||
export interface PrintCommentsViewProps {
|
||||
asset: AssetInfo
|
||||
breadcrumbs: string[]
|
||||
comments: CommentInfo[]
|
||||
shareId?: string
|
||||
sharePassword?: string
|
||||
}
|
||||
|
||||
function getHeaderThumbnailUrl(asset: AssetInfo): string | null {
|
||||
if (asset.preview?.thumbnailUrl) return asset.preview.thumbnailUrl
|
||||
if (asset.media?.imageTranscodes && asset.media.imageTranscodes.length > 0) {
|
||||
const sorted = [...asset.media.imageTranscodes]
|
||||
.filter((t) => Boolean(t.url))
|
||||
.sort((a, b) => (a.width || 0) - (b.width || 0))
|
||||
if (sorted[0]?.url) return sorted[0].url
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function getImageCommentThumbnailUrl(asset: AssetInfo): string | null {
|
||||
if (asset.media?.imageTranscodes && asset.media.imageTranscodes.length > 0) {
|
||||
const valid = asset.media.imageTranscodes.filter((t) => Boolean(t.url))
|
||||
const adequate = valid
|
||||
.filter((t) => (t.width || 0) >= 400)
|
||||
.sort((a, b) => (a.width || 0) - (b.width || 0))
|
||||
if (adequate[0]?.url) return adequate[0].url
|
||||
const largest = [...valid].sort((a, b) => (b.width || 0) - (a.width || 0))
|
||||
if (largest[0]?.url) return largest[0].url
|
||||
}
|
||||
return asset.preview?.thumbnailUrl || null
|
||||
}
|
||||
|
||||
function buildFrameEndpointUrl(params: {
|
||||
assetId: string
|
||||
second: number
|
||||
width?: number
|
||||
shareId?: string
|
||||
sharePassword?: string
|
||||
}): string {
|
||||
const qs = new URLSearchParams({
|
||||
second: String(params.second),
|
||||
width: String(params.width ?? 400),
|
||||
})
|
||||
if (params.shareId) {
|
||||
if (params.sharePassword) {
|
||||
qs.set('p', params.sharePassword)
|
||||
}
|
||||
return `/api/shares/${encodeURIComponent(params.shareId)}/files/${encodeURIComponent(params.assetId)}/comments/frame?${qs.toString()}`
|
||||
}
|
||||
return `/api/files/${encodeURIComponent(params.assetId)}/comments/frame?${qs.toString()}`
|
||||
}
|
||||
|
||||
function formatShortDate(iso?: string | null): string {
|
||||
if (!iso) return ''
|
||||
const date = new Date(iso)
|
||||
if (Number.isNaN(date.getTime())) return ''
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
month: 'numeric',
|
||||
day: 'numeric',
|
||||
year: '2-digit',
|
||||
}).format(date)
|
||||
}
|
||||
|
||||
function formatCommentDateTime(iso?: string | null): string {
|
||||
if (!iso) return ''
|
||||
const date = new Date(iso)
|
||||
if (Number.isNaN(date.getTime())) return ''
|
||||
const datePart = new Intl.DateTimeFormat(undefined, {
|
||||
month: 'numeric',
|
||||
day: 'numeric',
|
||||
year: '2-digit',
|
||||
}).format(date)
|
||||
const timePart = new Intl.DateTimeFormat(undefined, {
|
||||
hour: 'numeric',
|
||||
minute: '2-digit',
|
||||
}).format(date)
|
||||
return `${datePart} · ${timePart}`
|
||||
}
|
||||
|
||||
function splitMiddleTruncate(name: string): { head: string; tail: string } {
|
||||
if (name.length <= 16) return { head: name, tail: '' }
|
||||
const tailLen = 10
|
||||
return {
|
||||
head: name.slice(0, name.length - tailLen),
|
||||
tail: name.slice(name.length - tailLen),
|
||||
}
|
||||
}
|
||||
|
||||
function preprocessMarkdown(text: string): string {
|
||||
return text.replace(/<@([a-zA-Z0-9_-]+)>/g, '@$1').replace(/^\[([^\]]+)\]:/gm, '\\[$1\\]:')
|
||||
}
|
||||
|
||||
function renderPlainCommentText(comment: CommentInfo): React.ReactNode {
|
||||
const text = comment.message ?? ''
|
||||
const parts = text.split(/(<@[a-zA-Z0-9_-]+>)/g)
|
||||
return parts.map((part, index) => {
|
||||
if (part.match(/^<@[a-zA-Z0-9_-]+>$/)) {
|
||||
const userId = part.slice(2, -1)
|
||||
const mentionedUser = comment.mentions?.find((u) => u.id === userId)
|
||||
return (
|
||||
<span key={index} className="font-medium text-primary">
|
||||
@{mentionedUser?.name || 'Unknown'}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
return <React.Fragment key={index}>{part}</React.Fragment>
|
||||
})
|
||||
}
|
||||
|
||||
export const PrintCommentsView: React.FC<PrintCommentsViewProps> = ({
|
||||
asset,
|
||||
breadcrumbs,
|
||||
comments,
|
||||
shareId,
|
||||
sharePassword,
|
||||
}) => {
|
||||
const { videoTimeDisplayMode } = useUiStore()
|
||||
const viewerDef = useMemo(() => getViewerForFile(asset), [asset])
|
||||
const proxyType = asset.proxyType ?? asset.media?.proxyType ?? null
|
||||
|
||||
const hasPositionSort = Boolean(viewerDef.commentsConfig?.hasTimestamp)
|
||||
const [sortMode, setSortMode] = useState<PrintSortMode>(hasPositionSort ? 'position' : 'oldest')
|
||||
const [settledFrameUrls, setSettledFrameUrls] = useState<Record<string, string>>({})
|
||||
|
||||
const frameRate = viewerDef.commentsConfig?.hasTimestamp
|
||||
? asset.media?.metadata?.frameRate || 30
|
||||
: undefined
|
||||
const startTimecode = viewerDef.commentsConfig?.hasTimestamp
|
||||
? asset.media?.metadata?.startTimecode
|
||||
: undefined
|
||||
|
||||
const formatCommentTimestamp = useCallback(
|
||||
(second: number | null | undefined): string => {
|
||||
if (second === null || second === undefined) return ''
|
||||
if (viewerDef.commentsConfig?.formatTimestamp) {
|
||||
return viewerDef.commentsConfig.formatTimestamp(second)
|
||||
}
|
||||
if (!frameRate) return ''
|
||||
const frameIndex = formatFrame(second, frameRate)
|
||||
return formatTimecode(frameIndex, frameRate, videoTimeDisplayMode, startTimecode)
|
||||
},
|
||||
[viewerDef, frameRate, videoTimeDisplayMode, startTimecode],
|
||||
)
|
||||
|
||||
const sortedComments = useMemo(() => {
|
||||
const list = [...comments]
|
||||
if (sortMode === 'position') {
|
||||
list.sort((a, b) => {
|
||||
const aHas = a.second !== null && a.second !== undefined
|
||||
const bHas = b.second !== null && b.second !== undefined
|
||||
if (aHas && bHas) {
|
||||
if (a.second! !== b.second!) return a.second! - b.second!
|
||||
return a.id.localeCompare(b.id)
|
||||
}
|
||||
if (aHas) return -1
|
||||
if (bHas) return 1
|
||||
return a.id.localeCompare(b.id)
|
||||
})
|
||||
} else if (sortMode === 'newest') {
|
||||
list.sort((a, b) => b.id.localeCompare(a.id))
|
||||
} else {
|
||||
list.sort((a, b) => a.id.localeCompare(b.id))
|
||||
}
|
||||
return list
|
||||
}, [comments, sortMode])
|
||||
|
||||
const hasVisualThumbnailColumn =
|
||||
proxyType === 'video' || proxyType === '3d' || proxyType === 'pdf' || proxyType === 'image'
|
||||
|
||||
const getCommentFrameUrl = useCallback(
|
||||
(comment: CommentInfo): string | null => {
|
||||
if (!hasVisualThumbnailColumn) return null
|
||||
if (proxyType === 'image') {
|
||||
return getImageCommentThumbnailUrl(asset)
|
||||
}
|
||||
if (proxyType === 'video' || proxyType === '3d' || proxyType === 'pdf') {
|
||||
if (comment.second !== null && comment.second !== undefined) {
|
||||
return buildFrameEndpointUrl({
|
||||
assetId: asset.id,
|
||||
second: comment.second,
|
||||
width: 400,
|
||||
shareId,
|
||||
sharePassword,
|
||||
})
|
||||
}
|
||||
// If an untimestamped comment still carries visual annotations, show the asset poster/thumbnail
|
||||
const anns = parseAnnotations(comment.annotations)
|
||||
if (anns.length > 0) {
|
||||
return getHeaderThumbnailUrl(asset)
|
||||
}
|
||||
return null
|
||||
}
|
||||
return null
|
||||
},
|
||||
[hasVisualThumbnailColumn, proxyType, asset, shareId, sharePassword],
|
||||
)
|
||||
|
||||
const frameUrls = useMemo(() => {
|
||||
const urls = new Map<string, string>()
|
||||
for (const comment of comments) {
|
||||
const url = getCommentFrameUrl(comment)
|
||||
if (url) urls.set(comment.id, url)
|
||||
|
||||
for (const reply of comment.replies ?? []) {
|
||||
if (parseAnnotations(reply.annotations).length === 0) continue
|
||||
const replyUrl = getCommentFrameUrl(reply)
|
||||
if (replyUrl) urls.set(reply.id, replyUrl)
|
||||
}
|
||||
}
|
||||
return urls
|
||||
}, [comments, getCommentFrameUrl])
|
||||
|
||||
const settledFrameCount = Array.from(frameUrls).filter(
|
||||
([id, url]) => settledFrameUrls[id] === url,
|
||||
).length
|
||||
const isLoadingFrames = settledFrameCount < frameUrls.size
|
||||
|
||||
const sortIndicatorLabel = useMemo(() => {
|
||||
if (sortMode === 'oldest') return m.print_comments_sorted_by_oldest()
|
||||
if (sortMode === 'newest') return m.print_comments_sorted_by_newest()
|
||||
if (proxyType === 'pdf') return m.print_comments_sorted_by_page()
|
||||
if (proxyType === '3d') return m.print_comments_sorted_by_angle()
|
||||
return m.print_comments_sorted_by_timecode()
|
||||
}, [sortMode, proxyType])
|
||||
|
||||
const positionSortOptionLabel = useMemo(() => {
|
||||
if (proxyType === 'pdf') return m.print_comments_sort_page()
|
||||
if (proxyType === '3d') return m.print_comments_sort_angle()
|
||||
return m.print_comments_sort_timecode()
|
||||
}, [proxyType])
|
||||
|
||||
const headerThumbUrl = useMemo(() => getHeaderThumbnailUrl(asset), [asset])
|
||||
const { head: nameHead, tail: nameTail } = splitMiddleTruncate(asset.name || '')
|
||||
const creatorAndDate = [asset.creator?.name, formatShortDate(asset.createdAt)]
|
||||
.filter(Boolean)
|
||||
.join(', ')
|
||||
|
||||
const commentCountLabel =
|
||||
comments.length === 1
|
||||
? m.print_comments_count_one()
|
||||
: m.print_comments_count({ count: String(comments.length) })
|
||||
|
||||
const renderFrame = (commentId: string, annotations: ReturnType<typeof parseAnnotations>) => {
|
||||
const url = frameUrls.get(commentId)
|
||||
if (!url) return null
|
||||
|
||||
return (
|
||||
<CommentFrameThumbnail
|
||||
key={url}
|
||||
src={url}
|
||||
annotations={annotations}
|
||||
onStatusChange={() =>
|
||||
setSettledFrameUrls((prev) =>
|
||||
prev[commentId] === url ? prev : { ...prev, [commentId]: url },
|
||||
)
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const renderCommentEntry = (
|
||||
comment: CommentInfo,
|
||||
options: {
|
||||
indexNumber?: number
|
||||
isReply: boolean
|
||||
hasReplies: boolean
|
||||
isLastReply: boolean
|
||||
},
|
||||
) => {
|
||||
const timestamp = formatCommentTimestamp(comment.second)
|
||||
const annotations = parseAnnotations(comment.annotations)
|
||||
const hasAnnotations = annotations.length > 0
|
||||
const creatorName = comment.creator?.name || 'Unknown'
|
||||
|
||||
return (
|
||||
<div
|
||||
key={comment.id}
|
||||
className={`relative flex gap-2.5 ${options.isReply ? 'pt-3' : ''}`}
|
||||
data-testid={options.isReply ? 'print-reply-item' : 'print-comment-item'}
|
||||
>
|
||||
{/* Avatar + vertical thread connector matching Frame.io / Shumai threads */}
|
||||
<div className="relative flex w-6 shrink-0 flex-col items-center">
|
||||
{options.isReply && (
|
||||
<div className="absolute -top-3 left-1/2 h-3.5 w-px -translate-x-1/2 bg-border" />
|
||||
)}
|
||||
{((options.hasReplies && !options.isReply) ||
|
||||
(options.isReply && !options.isLastReply)) && (
|
||||
<div className="absolute top-6 bottom-[-12px] left-1/2 w-px -translate-x-1/2 bg-border" />
|
||||
)}
|
||||
<Avatar className="relative z-10 h-6 w-6">
|
||||
{comment.creator?.image && (
|
||||
<AvatarImage src={comment.creator.image} alt={creatorName} className="object-cover" />
|
||||
)}
|
||||
<AvatarFallback className="bg-muted text-[10px] font-semibold text-foreground">
|
||||
{creatorName[0]?.toUpperCase() || 'U'}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</div>
|
||||
|
||||
{/* Entry content */}
|
||||
<div className="min-w-0 flex-1">
|
||||
{/* Author + timestamp + #index + completed status */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span className="truncate text-sm font-semibold text-foreground">{creatorName}</span>
|
||||
<span className="whitespace-nowrap text-xs text-muted-foreground">
|
||||
{formatCommentDateTime(comment.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{comment.isCompleted && (
|
||||
<span
|
||||
className="inline-flex items-center gap-1 rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-[11px] font-medium text-emerald-700"
|
||||
data-testid="print-comment-completed"
|
||||
>
|
||||
<CheckCircle2 className="h-3 w-3" />
|
||||
<span>{m.print_comments_completed()}</span>
|
||||
</span>
|
||||
)}
|
||||
{options.indexNumber !== undefined && (
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
<span className="opacity-70">#</span>
|
||||
{options.indexNumber}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Prefix (timecode / page / angle + annotation indicator) + Comment text */}
|
||||
<div className="mt-1 text-sm leading-relaxed text-foreground">
|
||||
{(timestamp || hasAnnotations) && (
|
||||
<span className="mr-2 inline-flex items-center gap-1.5 align-middle">
|
||||
{timestamp && (
|
||||
<span
|
||||
className="inline-block rounded bg-muted px-1.5 py-0.5 font-mono text-xs font-semibold leading-none text-foreground"
|
||||
data-testid="print-comment-timestamp"
|
||||
>
|
||||
{timestamp}
|
||||
</span>
|
||||
)}
|
||||
{hasAnnotations && (
|
||||
<span
|
||||
className="inline-flex items-center text-muted-foreground"
|
||||
title={m.print_comments_has_annotations()}
|
||||
aria-label={m.print_comments_has_annotations()}
|
||||
>
|
||||
<DrawAnnotation className="h-3.5 w-3.5" />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{comment.sessionId && comment.message ? (
|
||||
<div className="prose prose-sm mt-0.5 max-w-none break-words text-foreground">
|
||||
<Markdown>{preprocessMarkdown(comment.message)}</Markdown>
|
||||
</div>
|
||||
) : (
|
||||
<span className="whitespace-pre-wrap break-words">
|
||||
{renderPlainCommentText(comment)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{options.isReply && frameUrls.has(comment.id) && (
|
||||
<div className="mt-2">{renderFrame(comment.id, annotations)}</div>
|
||||
)}
|
||||
|
||||
{/* Attachments */}
|
||||
{comment.attachments && comment.attachments.length > 0 && (
|
||||
<div className="mt-2 flex flex-wrap gap-2" data-testid="print-comment-attachments">
|
||||
{comment.attachments.map((att) => {
|
||||
const rawName = att.url?.split('/').pop()?.split('?')[0] || 'file'
|
||||
const name = decodeURIComponent(rawName)
|
||||
const isImage = isImageFileName(name)
|
||||
return (
|
||||
<div
|
||||
key={att.id}
|
||||
className="inline-flex max-w-full items-center gap-2 rounded-md border border-border bg-card px-2 py-1"
|
||||
>
|
||||
{isImage ? (
|
||||
<img
|
||||
src={att.url}
|
||||
alt={name}
|
||||
className="h-10 w-10 shrink-0 rounded object-cover"
|
||||
/>
|
||||
) : (
|
||||
<FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
|
||||
)}
|
||||
<span className="max-w-[220px] truncate text-xs font-medium text-foreground">
|
||||
{name}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Emoji reactions */}
|
||||
{comment.reactionCounts && comment.reactionCounts.length > 0 && (
|
||||
<div
|
||||
className="mt-2 flex flex-wrap items-center gap-1.5"
|
||||
data-testid="print-comment-reactions"
|
||||
>
|
||||
{comment.reactionCounts.map((reaction) => (
|
||||
<span
|
||||
key={reaction.code}
|
||||
className="inline-flex items-center gap-1 rounded-full border border-border bg-card px-2 py-0.5 text-xs text-foreground"
|
||||
>
|
||||
<span className="leading-none">{reaction.code}</span>
|
||||
<span className="font-semibold">{reaction.count}</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="print-sheet min-h-screen bg-background text-foreground">
|
||||
{/* Non-printable action toolbar */}
|
||||
<div className="sticky top-0 z-20 border-b border-border bg-background/95 backdrop-blur-sm print:hidden">
|
||||
<div className="mx-auto flex max-w-[860px] flex-wrap items-center justify-between gap-3 px-6 py-3">
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
{isLoadingFrames ? (
|
||||
<span
|
||||
className="inline-flex items-center gap-2 font-medium text-foreground"
|
||||
data-testid="print-frames-progress"
|
||||
>
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin text-primary" />
|
||||
<span>
|
||||
{m.print_comments_loading_frames({
|
||||
loaded: String(settledFrameCount),
|
||||
total: String(frameUrls.size),
|
||||
})}
|
||||
</span>
|
||||
</span>
|
||||
) : (
|
||||
<span>{commentCountLabel}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="inline-flex items-center rounded-md border border-border bg-card p-0.5 text-xs">
|
||||
{hasPositionSort && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSortMode('position')}
|
||||
className={`rounded px-2.5 py-1 font-medium transition-colors cursor-pointer ${
|
||||
sortMode === 'position'
|
||||
? 'bg-background text-foreground shadow-xs'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{positionSortOptionLabel}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSortMode('oldest')}
|
||||
className={`rounded px-2.5 py-1 font-medium transition-colors cursor-pointer ${
|
||||
sortMode === 'oldest'
|
||||
? 'bg-background text-foreground shadow-xs'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{m.print_comments_sort_oldest()}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSortMode('newest')}
|
||||
className={`rounded px-2.5 py-1 font-medium transition-colors cursor-pointer ${
|
||||
sortMode === 'newest'
|
||||
? 'bg-background text-foreground shadow-xs'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{m.print_comments_sort_newest()}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
disabled={isLoadingFrames}
|
||||
onClick={() => window.print()}
|
||||
className="gap-1.5 cursor-pointer"
|
||||
data-testid="print-comments-button"
|
||||
>
|
||||
<Printer className="h-3.5 w-3.5" />
|
||||
<span>{m.print()}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Printable document body */}
|
||||
<div className="mx-auto max-w-[860px] px-6 py-8 print:max-w-none print:px-0 print:py-0">
|
||||
{/* Document Header */}
|
||||
<header className="flex items-center gap-4 pb-5">
|
||||
<div
|
||||
className="flex shrink-0 items-center justify-center overflow-hidden rounded-sm border border-border transparency-checkerboard"
|
||||
style={{ width: 96, height: 54 }}
|
||||
>
|
||||
{headerThumbUrl ? (
|
||||
<img src={headerThumbUrl} alt="" className="h-full w-full object-contain" />
|
||||
) : proxyType === 'audio' ? (
|
||||
<FileAudio className="h-5 w-5 text-muted-foreground" />
|
||||
) : proxyType === 'pdf' ? (
|
||||
<FileText className="h-5 w-5 text-muted-foreground" />
|
||||
) : (
|
||||
<FileIcon className="h-5 w-5 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex min-w-0 flex-1 flex-col justify-between gap-1.5">
|
||||
{/* Top row: Breadcrumbs + Shumai Logo */}
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<nav
|
||||
aria-label="Breadcrumb"
|
||||
className="flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground"
|
||||
>
|
||||
{breadcrumbs.map((segment, i) => (
|
||||
<React.Fragment key={`${segment}-${i}`}>
|
||||
{i > 0 && <span className="shrink-0 opacity-60">/</span>}
|
||||
<span className="truncate">{segment}</span>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</nav>
|
||||
<ShumaiLogo className="h-4 w-4 shrink-0 text-foreground" aria-label="Shumai" />
|
||||
</div>
|
||||
|
||||
{/* Bottom row: Filename + Creator & Date */}
|
||||
<div className="flex items-baseline justify-between gap-4">
|
||||
<h1
|
||||
className="flex min-w-0 text-base font-semibold leading-tight text-foreground"
|
||||
title={asset.name}
|
||||
>
|
||||
<span className="truncate">{nameHead}</span>
|
||||
{nameTail && <span className="shrink-0">{nameTail}</span>}
|
||||
</h1>
|
||||
{creatorAndDate && (
|
||||
<span className="shrink-0 whitespace-nowrap text-xs text-muted-foreground">
|
||||
{creatorAndDate}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="border-b border-border" />
|
||||
|
||||
{/* Sort Indicator */}
|
||||
<div className="flex items-center gap-1.5 py-4 text-xs font-medium text-muted-foreground">
|
||||
<ArrowDownWideNarrow className="h-4 w-4" />
|
||||
<span>{sortIndicatorLabel}</span>
|
||||
</div>
|
||||
|
||||
{/* Comments List */}
|
||||
{sortedComments.length === 0 ? (
|
||||
<div className="py-12 text-center text-sm text-muted-foreground">
|
||||
{m.print_comments_empty()}
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-border">
|
||||
{sortedComments.map((comment, idx) => {
|
||||
const annotations = parseAnnotations(comment.annotations)
|
||||
const replies = comment.replies ?? []
|
||||
|
||||
return (
|
||||
<article
|
||||
key={comment.id}
|
||||
className="flex gap-5 py-5 break-inside-avoid"
|
||||
data-testid="print-comment-thread"
|
||||
>
|
||||
{hasVisualThumbnailColumn && (
|
||||
<div className="w-[200px] shrink-0">{renderFrame(comment.id, annotations)}</div>
|
||||
)}
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
{renderCommentEntry(comment, {
|
||||
indexNumber: idx + 1,
|
||||
isReply: false,
|
||||
hasReplies: replies.length > 0,
|
||||
isLastReply: false,
|
||||
})}
|
||||
{replies.map((reply, replyIdx) =>
|
||||
renderCommentEntry(reply, {
|
||||
isReply: true,
|
||||
hasReplies: false,
|
||||
isLastReply: replyIdx === replies.length - 1,
|
||||
}),
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -203,3 +203,48 @@
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 0.875em;
|
||||
}
|
||||
|
||||
/* Always render printable comment sheets with light paper tokens, even when the app is in dark mode */
|
||||
.print-sheet {
|
||||
color-scheme: light;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.153 0.006 107.1);
|
||||
--card: oklch(0.988 0.003 106.5);
|
||||
--card-foreground: oklch(0.153 0.006 107.1);
|
||||
--muted: oklch(0.966 0.005 106.5);
|
||||
--muted-foreground: oklch(0.5 0.02 107.3);
|
||||
--border: oklch(0.91 0.007 106.5);
|
||||
--accent: oklch(0.966 0.005 106.5);
|
||||
--accent-foreground: oklch(0.228 0.013 107.4);
|
||||
--primary: oklch(0.553 0.195 38.402);
|
||||
--primary-foreground: oklch(0.98 0.016 73.684);
|
||||
}
|
||||
|
||||
.transparency-checkerboard {
|
||||
background-color: #f5f5f5;
|
||||
background-image:
|
||||
linear-gradient(45deg, #e5e5e5 25%, transparent 25%),
|
||||
linear-gradient(-45deg, #e5e5e5 25%, transparent 25%),
|
||||
linear-gradient(45deg, transparent 75%, #e5e5e5 75%),
|
||||
linear-gradient(-45deg, transparent 75%, #e5e5e5 75%);
|
||||
background-size: 16px 16px;
|
||||
background-position:
|
||||
0 0,
|
||||
0 8px,
|
||||
8px -8px,
|
||||
-8px 0;
|
||||
}
|
||||
|
||||
@media print {
|
||||
@page {
|
||||
margin: 12mm;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
background: #ffffff !important;
|
||||
color: #171717 !important;
|
||||
-webkit-print-color-adjust: exact;
|
||||
print-color-adjust: exact;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1771,5 +1771,27 @@
|
||||
"agent_runner_team_default_with_name": "Team Default ({name})",
|
||||
"agent_runner_none_configured_warning": "No runners are configured for this team yet. The bash and download_asset tools will remain unavailable until you register a runner in Team Settings → Agent Runners.",
|
||||
"advanced_settings": "Advanced settings",
|
||||
"failed_add_to_share_link": "Failed to add to share link"
|
||||
"failed_add_to_share_link": "Failed to add to share link",
|
||||
"print_comments": "Print Comments",
|
||||
"print": "Print",
|
||||
"print_comments_loading": "Loading comments...",
|
||||
"print_comments_loading_frames": "Loading thumbnails ({loaded}/{total})...",
|
||||
"print_comments_frame_loading": "Loading frame...",
|
||||
"print_comments_frame_unavailable": "Frame unavailable",
|
||||
"print_comments_sorted_by_timecode": "Sorted by timecode",
|
||||
"print_comments_sorted_by_page": "Sorted by page",
|
||||
"print_comments_sorted_by_angle": "Sorted by angle",
|
||||
"print_comments_sorted_by_oldest": "Sorted by oldest",
|
||||
"print_comments_sorted_by_newest": "Sorted by newest",
|
||||
"print_comments_sort_timecode": "Timecode",
|
||||
"print_comments_sort_page": "Page",
|
||||
"print_comments_sort_angle": "Angle",
|
||||
"print_comments_sort_oldest": "Oldest",
|
||||
"print_comments_sort_newest": "Newest",
|
||||
"print_comments_completed": "Completed",
|
||||
"print_comments_empty": "No comments on this file.",
|
||||
"print_comments_error": "Failed to load printable comments.",
|
||||
"print_comments_count": "{count} comments",
|
||||
"print_comments_count_one": "1 comment",
|
||||
"print_comments_has_annotations": "Comment has annotations"
|
||||
}
|
||||
|
||||
@@ -1701,5 +1701,27 @@
|
||||
"agent_runner_team_default_with_name": "팀 기본({name})",
|
||||
"agent_runner_none_configured_warning": "이 팀에 아직 구성된 러너가 없습니다. 팀 설정 → 에이전트 러너에서 러너를 등록할 때까지 bash 및 download_asset 도구를 사용할 수 없습니다.",
|
||||
"advanced_settings": "고급 설정",
|
||||
"failed_add_to_share_link": "공유 링크에 추가하지 못했습니다"
|
||||
"failed_add_to_share_link": "공유 링크에 추가하지 못했습니다",
|
||||
"print_comments": "댓글 인쇄",
|
||||
"print": "인쇄",
|
||||
"print_comments_loading": "댓글을 불러오는 중...",
|
||||
"print_comments_loading_frames": "썸네일 불러오는 중 ({loaded}/{total})...",
|
||||
"print_comments_frame_loading": "프레임 불러오는 중...",
|
||||
"print_comments_frame_unavailable": "프레임을 불러올 수 없음",
|
||||
"print_comments_sorted_by_timecode": "타임코드순 정렬",
|
||||
"print_comments_sorted_by_page": "페이지순 정렬",
|
||||
"print_comments_sorted_by_angle": "각도순 정렬",
|
||||
"print_comments_sorted_by_oldest": "오래된순 정렬",
|
||||
"print_comments_sorted_by_newest": "최신순 정렬",
|
||||
"print_comments_sort_timecode": "타임코드",
|
||||
"print_comments_sort_page": "페이지",
|
||||
"print_comments_sort_angle": "각도",
|
||||
"print_comments_sort_oldest": "오래된순",
|
||||
"print_comments_sort_newest": "최신순",
|
||||
"print_comments_completed": "완료됨",
|
||||
"print_comments_empty": "이 파일에 댓글이 없습니다.",
|
||||
"print_comments_error": "인쇄용 댓글을 불러오지 못했습니다.",
|
||||
"print_comments_count": "댓글 {count}개",
|
||||
"print_comments_count_one": "댓글 1개",
|
||||
"print_comments_has_annotations": "주석이 포함된 댓글"
|
||||
}
|
||||
|
||||
@@ -1771,5 +1771,27 @@
|
||||
"agent_runner_team_default_with_name": "团队默认({name})",
|
||||
"agent_runner_none_configured_warning": "当前团队尚未配置任何运行器。在“团队设置 → Agent 运行器”中注册运行器之前,bash 和 download_asset 工具将不可用。",
|
||||
"advanced_settings": "高级设置",
|
||||
"failed_add_to_share_link": "添加到分享链接失败"
|
||||
"failed_add_to_share_link": "添加到分享链接失败",
|
||||
"print_comments": "打印评论",
|
||||
"print": "打印",
|
||||
"print_comments_loading": "正在加载评论...",
|
||||
"print_comments_loading_frames": "正在加载缩略图 ({loaded}/{total})...",
|
||||
"print_comments_frame_loading": "正在生成预览...",
|
||||
"print_comments_frame_unavailable": "无法加载预览",
|
||||
"print_comments_sorted_by_timecode": "按时间码排序",
|
||||
"print_comments_sorted_by_page": "按页码排序",
|
||||
"print_comments_sorted_by_angle": "按角度排序",
|
||||
"print_comments_sorted_by_oldest": "按最早排序",
|
||||
"print_comments_sorted_by_newest": "按最新排序",
|
||||
"print_comments_sort_timecode": "时间码",
|
||||
"print_comments_sort_page": "页码",
|
||||
"print_comments_sort_angle": "角度",
|
||||
"print_comments_sort_oldest": "最早",
|
||||
"print_comments_sort_newest": "最新",
|
||||
"print_comments_completed": "已完成",
|
||||
"print_comments_empty": "此文件暂无评论。",
|
||||
"print_comments_error": "加载可打印评论失败。",
|
||||
"print_comments_count": "{count} 条评论",
|
||||
"print_comments_count_one": "1 条评论",
|
||||
"print_comments_has_annotations": "评论包含标注"
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import { Route as TeamsTeamIdDashboardRouteImport } from './routes/teams/$teamId
|
||||
import { Route as ProjectsProjectIdRecentsRouteImport } from './routes/projects/$projectId/recents'
|
||||
import { Route as ProjectsProjectIdRecentlyDeletedRouteImport } from './routes/projects/$projectId/recently-deleted'
|
||||
import { Route as ProjectsProjectIdAgentsmdRouteImport } from './routes/projects/$projectId/agentsmd'
|
||||
import { Route as PrintCommentsAssetIdRouteImport } from './routes/print/comments/$assetId'
|
||||
import { Route as ProjectsProjectIdSharesIndexRouteImport } from './routes/projects/$projectId/shares/index'
|
||||
import { Route as ProjectsProjectIdCollectionsIndexRouteImport } from './routes/projects/$projectId/collections/index'
|
||||
import { Route as ShareShareIdFoldersFolderIdRouteImport } from './routes/share/$shareId/folders/$folderId'
|
||||
@@ -111,6 +112,11 @@ const ProjectsProjectIdAgentsmdRoute = ProjectsProjectIdAgentsmdRouteImport.upda
|
||||
path: '/projects/$projectId/agentsmd',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any).lazy(() => import('./routes/projects/$projectId/agentsmd.lazy').then((d) => d.Route))
|
||||
const PrintCommentsAssetIdRoute = PrintCommentsAssetIdRouteImport.update({
|
||||
id: '/print/comments/$assetId',
|
||||
path: '/print/comments/$assetId',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any).lazy(() => import('./routes/print/comments/$assetId.lazy').then((d) => d.Route))
|
||||
const ProjectsProjectIdSharesIndexRoute = ProjectsProjectIdSharesIndexRouteImport.update({
|
||||
id: '/projects/$projectId/shares/',
|
||||
path: '/projects/$projectId/shares/',
|
||||
@@ -176,6 +182,7 @@ export interface FileRoutesByFullPath {
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/signup': typeof SignupRoute
|
||||
'/share/$shareId': typeof ShareShareIdRouteWithChildren
|
||||
'/print/comments/$assetId': typeof PrintCommentsAssetIdRoute
|
||||
'/projects/$projectId/agentsmd': typeof ProjectsProjectIdAgentsmdRoute
|
||||
'/projects/$projectId/recently-deleted': typeof ProjectsProjectIdRecentlyDeletedRoute
|
||||
'/projects/$projectId/recents': typeof ProjectsProjectIdRecentsRoute
|
||||
@@ -201,6 +208,7 @@ export interface FileRoutesByTo {
|
||||
'/login': typeof LoginRoute
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/signup': typeof SignupRoute
|
||||
'/print/comments/$assetId': typeof PrintCommentsAssetIdRoute
|
||||
'/projects/$projectId/agentsmd': typeof ProjectsProjectIdAgentsmdRoute
|
||||
'/projects/$projectId/recently-deleted': typeof ProjectsProjectIdRecentlyDeletedRoute
|
||||
'/projects/$projectId/recents': typeof ProjectsProjectIdRecentsRoute
|
||||
@@ -228,6 +236,7 @@ export interface FileRoutesById {
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/signup': typeof SignupRoute
|
||||
'/share/$shareId': typeof ShareShareIdRouteWithChildren
|
||||
'/print/comments/$assetId': typeof PrintCommentsAssetIdRoute
|
||||
'/projects/$projectId/agentsmd': typeof ProjectsProjectIdAgentsmdRoute
|
||||
'/projects/$projectId/recently-deleted': typeof ProjectsProjectIdRecentlyDeletedRoute
|
||||
'/projects/$projectId/recents': typeof ProjectsProjectIdRecentsRoute
|
||||
@@ -256,6 +265,7 @@ export interface FileRouteTypes {
|
||||
| '/reset-password'
|
||||
| '/signup'
|
||||
| '/share/$shareId'
|
||||
| '/print/comments/$assetId'
|
||||
| '/projects/$projectId/agentsmd'
|
||||
| '/projects/$projectId/recently-deleted'
|
||||
| '/projects/$projectId/recents'
|
||||
@@ -281,6 +291,7 @@ export interface FileRouteTypes {
|
||||
| '/login'
|
||||
| '/reset-password'
|
||||
| '/signup'
|
||||
| '/print/comments/$assetId'
|
||||
| '/projects/$projectId/agentsmd'
|
||||
| '/projects/$projectId/recently-deleted'
|
||||
| '/projects/$projectId/recents'
|
||||
@@ -307,6 +318,7 @@ export interface FileRouteTypes {
|
||||
| '/reset-password'
|
||||
| '/signup'
|
||||
| '/share/$shareId'
|
||||
| '/print/comments/$assetId'
|
||||
| '/projects/$projectId/agentsmd'
|
||||
| '/projects/$projectId/recently-deleted'
|
||||
| '/projects/$projectId/recents'
|
||||
@@ -334,6 +346,7 @@ export interface RootRouteChildren {
|
||||
ResetPasswordRoute: typeof ResetPasswordRoute
|
||||
SignupRoute: typeof SignupRoute
|
||||
ShareShareIdRoute: typeof ShareShareIdRouteWithChildren
|
||||
PrintCommentsAssetIdRoute: typeof PrintCommentsAssetIdRoute
|
||||
ProjectsProjectIdAgentsmdRoute: typeof ProjectsProjectIdAgentsmdRoute
|
||||
ProjectsProjectIdRecentlyDeletedRoute: typeof ProjectsProjectIdRecentlyDeletedRoute
|
||||
ProjectsProjectIdRecentsRoute: typeof ProjectsProjectIdRecentsRoute
|
||||
@@ -458,6 +471,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof ProjectsProjectIdAgentsmdRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/print/comments/$assetId': {
|
||||
id: '/print/comments/$assetId'
|
||||
path: '/print/comments/$assetId'
|
||||
fullPath: '/print/comments/$assetId'
|
||||
preLoaderRoute: typeof PrintCommentsAssetIdRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/projects/$projectId/shares/': {
|
||||
id: '/projects/$projectId/shares/'
|
||||
path: '/projects/$projectId/shares'
|
||||
@@ -545,6 +565,7 @@ const rootRouteChildren: RootRouteChildren = {
|
||||
ResetPasswordRoute: ResetPasswordRoute,
|
||||
SignupRoute: SignupRoute,
|
||||
ShareShareIdRoute: ShareShareIdRouteWithChildren,
|
||||
PrintCommentsAssetIdRoute: PrintCommentsAssetIdRoute,
|
||||
ProjectsProjectIdAgentsmdRoute: ProjectsProjectIdAgentsmdRoute,
|
||||
ProjectsProjectIdRecentlyDeletedRoute: ProjectsProjectIdRecentlyDeletedRoute,
|
||||
ProjectsProjectIdRecentsRoute: ProjectsProjectIdRecentsRoute,
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { PrintCommentsView } from '@/ui/components/print-comments/print-comments-view'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/ui/components/ui/card'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { PrintCommentsResponse } from '@shumai/dtos'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import { AlertCircle, Loader2, Lock } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
|
||||
class PrintAuthError extends Error {
|
||||
status: number
|
||||
constructor(status: number, message: string) {
|
||||
super(message)
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
function PrintCommentsPage() {
|
||||
const { assetId } = Route.useParams()
|
||||
const { shareId } = Route.useSearch()
|
||||
|
||||
const [sharePassword, setSharePassword] = useState(() => {
|
||||
if (!shareId || typeof window === 'undefined') return ''
|
||||
return localStorage.getItem(`share_pwd_${shareId}`) || ''
|
||||
})
|
||||
const [passwordInput, setPasswordInput] = useState('')
|
||||
|
||||
const { data, isLoading, error } = useQuery<PrintCommentsResponse>({
|
||||
queryKey: shareId
|
||||
? ['print-comments', 'share', shareId, assetId, sharePassword]
|
||||
: ['print-comments', 'file', assetId],
|
||||
queryFn: async () => {
|
||||
if (shareId) {
|
||||
const res = await client.api.shares[':shareId'].files[':fileId'].comments.print.$get(
|
||||
{
|
||||
param: { shareId, fileId: assetId },
|
||||
},
|
||||
{
|
||||
// A 401 here is a share-password challenge handled by this page.
|
||||
fetch,
|
||||
headers: sharePassword ? { 'x-share-password': sharePassword } : undefined,
|
||||
},
|
||||
)
|
||||
if (res.status === 401) {
|
||||
throw new PrintAuthError(401, 'Unauthorized')
|
||||
}
|
||||
if (!res.ok) {
|
||||
throw new PrintAuthError(res.status, 'Failed to fetch printable comments')
|
||||
}
|
||||
return (await res.json()) as unknown as PrintCommentsResponse
|
||||
}
|
||||
|
||||
const res = await client.api.files[':fileId'].comments.print.$get({
|
||||
param: { fileId: assetId },
|
||||
})
|
||||
if (!res.ok) {
|
||||
throw new PrintAuthError(res.status, 'Failed to fetch printable comments')
|
||||
}
|
||||
return (await res.json()) as unknown as PrintCommentsResponse
|
||||
},
|
||||
retry: false,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (data?.asset?.name) {
|
||||
document.title = `${data.asset.name} - ${m.print_comments()}`
|
||||
}
|
||||
}, [data?.asset?.name])
|
||||
|
||||
useEffect(() => {
|
||||
if (data && shareId && sharePassword) {
|
||||
localStorage.setItem(`share_pwd_${shareId}`, sharePassword)
|
||||
}
|
||||
}, [data, shareId, sharePassword])
|
||||
|
||||
const handlePasswordSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!shareId) return
|
||||
setSharePassword(passwordInput)
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div
|
||||
className="print-sheet flex min-h-screen flex-col items-center justify-center gap-3 bg-background text-foreground"
|
||||
data-testid="print-comments-loading"
|
||||
>
|
||||
<Loader2 className="h-6 w-6 animate-spin text-primary" />
|
||||
<p className="text-sm text-muted-foreground">{m.print_comments_loading()}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (shareId && error instanceof PrintAuthError && error.status === 401) {
|
||||
return (
|
||||
<div className="print-sheet flex min-h-screen items-center justify-center bg-background p-4 text-foreground">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<Lock className="h-4 w-4" />
|
||||
<span>{m.password_protected()}</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handlePasswordSubmit} className="space-y-3">
|
||||
<Input
|
||||
type="password"
|
||||
value={passwordInput}
|
||||
onChange={(e) => setPasswordInput(e.target.value)}
|
||||
placeholder={m.enter_password()}
|
||||
autoFocus
|
||||
/>
|
||||
{sharePassword && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{m.incorrect_password()}
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" className="w-full cursor-pointer">
|
||||
{m.confirm()}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error || !data) {
|
||||
return (
|
||||
<div
|
||||
className="print-sheet flex min-h-screen flex-col items-center justify-center gap-3 bg-background p-6 text-center text-foreground"
|
||||
data-testid="print-comments-error"
|
||||
>
|
||||
<AlertCircle className="h-6 w-6 text-destructive" />
|
||||
<p className="text-sm font-medium">{m.print_comments_error()}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<PrintCommentsView
|
||||
asset={data.asset}
|
||||
breadcrumbs={data.breadcrumbs}
|
||||
comments={data.comments}
|
||||
shareId={shareId}
|
||||
sharePassword={sharePassword || undefined}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createLazyFileRoute('/print/comments/$assetId')({
|
||||
component: PrintCommentsPage,
|
||||
})
|
||||
@@ -0,0 +1,11 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
export const Route = createFileRoute('/print/comments/$assetId')({
|
||||
validateSearch: (search: Record<string, unknown>) => {
|
||||
return {
|
||||
shareId: typeof search.shareId === 'string' && search.shareId ? search.shareId : undefined,
|
||||
} as {
|
||||
shareId?: string
|
||||
}
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user