{activeGroup ? (
-
+
{
+ if (!annotationMode || (event.button ?? 0) !== 0) return
+ pointerStartRef.current = { x: event.clientX, y: event.clientY }
+ }}
+ onPointerUp={(event) => {
+ if (!annotationMode || !pointerStartRef.current) return
+ const distance = Math.hypot(
+ event.clientX - pointerStartRef.current.x,
+ event.clientY - pointerStartRef.current.y,
+ )
+ pointerStartRef.current = null
+ if (distance <= 8) placeAnnotation(event.currentTarget, event.clientX, event.clientY)
+ }}
+ onPointerCancel={() => {
+ pointerStartRef.current = null
+ }}
+ onKeyDown={(event) => {
+ if (annotationMode && (event.key === 'Enter' || event.key === ' ')) {
+ event.preventDefault()
+ const bounds = event.currentTarget.getBoundingClientRect()
+ placeAnnotation(event.currentTarget, bounds.left + bounds.width / 2, bounds.top + bounds.height / 2)
+ }
+ }}
+ >
{(activeGroup.slices.length > 0 ? activeGroup.slices : [{
url: activeGroup.previewUrl,
width: activeGroup.previewWidth,
@@ -119,7 +219,15 @@ function LongImagePane({
height={slice.height}
unoptimized
loading={sliceIndex === 0 ? 'eager' : 'lazy'}
- className="block h-auto w-full"
+ className="pointer-events-none block h-auto w-full select-none"
+ draggable={false}
+ />
+ ))}
+ {annotations.map((item) => (
+ onSelectDraftAnnotation?.(item.annotation.id) : undefined}
/>
))}
@@ -133,23 +241,47 @@ function LongImagePane({
)
}
+function getImageCount(version?: WorkReviewVersion) {
+ if (!version) return 0
+ return version.imageGroups?.length || version.imageUrls?.length || 0
+}
+
+function summarizeAnnotations(annotations: WorkReviewImageAnnotation[]) {
+ if (annotations.length === 0) return '通过'
+ return annotations
+ .map((annotation, index) => `标注 ${index + 1}:${annotation.comment.trim()}`)
+ .join('\n')
+ .slice(0, 2000)
+}
+
export function WorkReviewReviewerWorkspace({
project,
- onReview,
+ onSubmitReview,
}: {
project: WorkReviewProject
- onReview: (version: WorkReviewVersion, role: WorkReviewRole) => void
+ onSubmitReview: (version: WorkReviewVersion, input: WorkReviewReviewInput) => Promise
}) {
const latestVersion = project.versions[0]
const [selectedVersionId, setSelectedVersionId] = useState(latestVersion?.id || '')
const [workPanePercent, setWorkPanePercent] = useState(50)
+ const [activeWorkImageIndex, setActiveWorkImageIndex] = useState(0)
+ const [draftAnnotations, setDraftAnnotations] = useState(() => (
+ Array.from({ length: getImageCount(latestVersion) }, () => [])
+ ))
+ const [selectedAnnotation, setSelectedAnnotation] = useState<{ imageIndex: number; id: string } | null>(null)
+ const [annotationMode, setAnnotationMode] = useState(false)
+ const [busyAction, setBusyAction] = useState<'approved' | 'revision_required' | null>(null)
+ const [error, setError] = useState(null)
+ const [liveMessage, setLiveMessage] = useState('')
const comparisonRef = useRef(null)
const draggingRef = useRef(false)
const mobileScrollerRef = useRef(null)
+ const annotationInputRef = useRef(null)
const selectedVersion = useMemo(
() => project.versions.find((version) => version.id === selectedVersionId) || latestVersion,
[latestVersion, project.versions, selectedVersionId],
)
+ const workImageCount = getImageCount(selectedVersion)
useEffect(() => {
if (!project.versions.some((version) => version.id === selectedVersionId)) {
@@ -157,12 +289,44 @@ export function WorkReviewReviewerWorkspace({
}
}, [project.versions, selectedVersionId])
+ useEffect(() => {
+ setActiveWorkImageIndex(0)
+ setDraftAnnotations(Array.from({ length: workImageCount }, () => []))
+ setSelectedAnnotation(null)
+ setAnnotationMode(false)
+ setError(null)
+ }, [selectedVersion?.id, workImageCount])
+
+ useEffect(() => {
+ if (!selectedAnnotation) return
+ const frame = window.requestAnimationFrame(() => annotationInputRef.current?.focus())
+ return () => window.cancelAnimationFrame(frame)
+ }, [selectedAnnotation])
+
if (!selectedVersion || !latestVersion) return null
const isLatestSelected = selectedVersion.id === latestVersion.id
const pendingRole = isLatestSelected ? project.permissions.pendingReviewRoles[0] : undefined
const hasReferenceImages = (selectedVersion.referenceImageGroups?.length || 0) > 0
|| (selectedVersion.referenceImageUrls?.length || 0) > 0
+ const currentDrafts = draftAnnotations[activeWorkImageIndex] || []
+ const selectedDraft = selectedAnnotation
+ ? draftAnnotations[selectedAnnotation.imageIndex]?.find((item) => item.id === selectedAnnotation.id)
+ : undefined
+ const totalDraftCount = draftAnnotations.reduce((sum, annotations) => sum + annotations.length, 0)
+ const submittedAnnotations: WorkReviewDisplayAnnotation[] = selectedVersion.reviews.flatMap((review) => {
+ const imageComment = (review.imageComments || []).find((item) => item.imageIndex === activeWorkImageIndex)
+ return (imageComment?.annotations || []).map((annotation, index) => ({
+ annotation,
+ markerNumber: index + 1,
+ reviewerName: review.reviewerName,
+ reviewerRole: review.reviewerRole,
+ }))
+ })
+ const visibleAnnotations: WorkReviewDisplayAnnotation[] = [
+ ...submittedAnnotations,
+ ...currentDrafts.map((annotation, index) => ({ annotation, markerNumber: index + 1, draft: true })),
+ ]
const updateSplitFromPointer = (clientX: number) => {
const bounds = comparisonRef.current?.getBoundingClientRect()
@@ -177,6 +341,106 @@ export function WorkReviewReviewerWorkspace({
scroller.scrollTo({ left: scroller.clientWidth * index, behavior: 'smooth' })
}
+ const addAnnotation = (x: number, y: number) => {
+ if (!pendingRole) return
+ if (currentDrafts.length >= MAX_ANNOTATIONS_PER_IMAGE) {
+ setError(`单张图片最多添加 ${MAX_ANNOTATIONS_PER_IMAGE} 个批注`)
+ return
+ }
+ const annotation: WorkReviewImageAnnotation = { id: createAnnotationId(), x, y, comment: '' }
+ setDraftAnnotations((current) => current.map((items, index) => (
+ index === activeWorkImageIndex ? [...items, annotation] : items
+ )))
+ setSelectedAnnotation({ imageIndex: activeWorkImageIndex, id: annotation.id })
+ setAnnotationMode(false)
+ setError(null)
+ setLiveMessage(`已在图 ${activeWorkImageIndex + 1} 添加标注点`)
+ }
+
+ const updateSelectedAnnotation = (comment: string) => {
+ if (!selectedAnnotation) return
+ setDraftAnnotations((current) => current.map((items, imageIndex) => (
+ imageIndex === selectedAnnotation.imageIndex
+ ? items.map((item) => item.id === selectedAnnotation.id ? { ...item, comment } : item)
+ : items
+ )))
+ setError(null)
+ }
+
+ const deleteSelectedAnnotation = () => {
+ if (!selectedAnnotation) return
+ setDraftAnnotations((current) => current.map((items, imageIndex) => (
+ imageIndex === selectedAnnotation.imageIndex
+ ? items.filter((item) => item.id !== selectedAnnotation.id)
+ : items
+ )))
+ setSelectedAnnotation(null)
+ setError(null)
+ setLiveMessage('批注已删除')
+ }
+
+ const finishEditingAnnotation = () => {
+ if (!selectedDraft?.comment.trim()) {
+ setError('请填写这个标注点的修改意见')
+ return
+ }
+ setSelectedAnnotation(null)
+ setError(null)
+ setLiveMessage('批注已保存到本次评审草稿')
+ }
+
+ const findIncompleteAnnotation = () => {
+ for (let imageIndex = 0; imageIndex < draftAnnotations.length; imageIndex += 1) {
+ const annotation = draftAnnotations[imageIndex].find((item) => !item.comment.trim())
+ if (annotation) return { imageIndex, id: annotation.id }
+ }
+ return null
+ }
+
+ const submitDecision = async (decision: 'approved' | 'revision_required') => {
+ if (!pendingRole || workImageCount === 0) return
+ const incomplete = findIncompleteAnnotation()
+ if (incomplete) {
+ setActiveWorkImageIndex(incomplete.imageIndex)
+ setSelectedAnnotation(incomplete)
+ setAnnotationMode(false)
+ setError('请先填写未完成标注点的修改意见')
+ return
+ }
+ if (decision === 'revision_required' && totalDraftCount === 0) {
+ setError('请先在作品图片上标注至少一个需要修改的位置')
+ setAnnotationMode(true)
+ return
+ }
+
+ setBusyAction(decision)
+ setError(null)
+ try {
+ await onSubmitReview(selectedVersion, {
+ reviewerRole: pendingRole,
+ imageComments: Array.from({ length: workImageCount }, (_, imageIndex) => {
+ const annotations = draftAnnotations[imageIndex] || []
+ return {
+ imageIndex,
+ decision: decision === 'revision_required' && annotations.length > 0
+ ? 'revision_required'
+ : 'approved',
+ comment: summarizeAnnotations(annotations),
+ annotations,
+ }
+ }),
+ generalComment: '',
+ })
+ setDraftAnnotations(Array.from({ length: workImageCount }, () => []))
+ setSelectedAnnotation(null)
+ setAnnotationMode(false)
+ } catch (submitError) {
+ setError(submitError instanceof Error ? submitError.message : '评审提交失败')
+ } finally {
+ setBusyAction(null)
+ }
+ }
+
return (
)
diff --git a/lib/__tests__/work-review-policy.test.ts b/lib/__tests__/work-review-policy.test.ts
index 4318b5fc..18685798 100644
--- a/lib/__tests__/work-review-policy.test.ts
+++ b/lib/__tests__/work-review-policy.test.ts
@@ -1,5 +1,3 @@
-/** @jest-environment node */
-
import {
canSubmitWorkReview,
deriveCompletedWorkReviewStatus,
@@ -10,6 +8,7 @@ import {
getWorkReviewReviewerSelectionError,
isSameWorkReviewEmployeeAlias,
isSameWorkReviewEmployeeIdentity,
+ validateWorkReviewAnnotations,
} from '@/lib/work-review-policy'
describe('work review policy', () => {
@@ -100,4 +99,30 @@ describe('work review policy', () => {
{ reviewerRole: 'final_reviewer', decision: 'approved' },
])).toBe('revision_required')
})
+
+ test('normalizes image annotations without storing viewport pixels', () => {
+ expect(validateWorkReviewAnnotations([
+ { id: 'point-1', x: 0.123456789, y: 0.75, comment: ' 调整人物位置 ' },
+ ])).toEqual({
+ ok: true,
+ annotations: [
+ { id: 'point-1', x: 0.123457, y: 0.75, comment: '调整人物位置' },
+ ],
+ })
+ expect(validateWorkReviewAnnotations(undefined)).toEqual({ ok: true, annotations: [] })
+ })
+
+ test.each([
+ [[{ id: 'point-1', x: -0.1, y: 0.5, comment: '越界' }], '图片批注位置无效'],
+ [[{ id: 'point-1', x: 0.5, y: '0.5', comment: '类型错误' }], '图片批注位置无效'],
+ [[{ id: 'point-1', x: 0.5, y: 0.5, comment: ' ' }], '请填写每个标注点的修改意见'],
+ [[
+ { id: 'point-1', x: 0.2, y: 0.2, comment: 'A' },
+ { id: 'point-1', x: 0.4, y: 0.4, comment: 'B' },
+ ], '图片批注编号无效或重复'],
+ ])('rejects invalid image annotations', (annotations, message) => {
+ const result = validateWorkReviewAnnotations(annotations)
+ expect(result.ok).toBe(false)
+ if (!result.ok) expect(result.error).toBe(message)
+ })
})
diff --git a/lib/__tests__/work-review-reviewer-workspace.test.tsx b/lib/__tests__/work-review-reviewer-workspace.test.tsx
new file mode 100644
index 00000000..fb10442b
--- /dev/null
+++ b/lib/__tests__/work-review-reviewer-workspace.test.tsx
@@ -0,0 +1,105 @@
+/** @jest-environment jsdom */
+
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { WorkReviewReviewerWorkspace } from '@/components/work-review/WorkReviewReviewerWorkspace'
+import type { WorkReviewProject } from '@/types/work-review'
+
+const project: WorkReviewProject = {
+ id: 'project-1',
+ title: '测试作品',
+ description: null,
+ workDate: '2026-08-01',
+ status: 'pending_review',
+ latestVersion: 1,
+ submitter: { id: 'submitter-1', name: '提交人' },
+ manager: { id: 'manager-1', name: '评审人' },
+ finalReviewer: { id: 'final-1', name: '元泽' },
+ createdAt: '2026-08-01T00:00:00.000Z',
+ updatedAt: '2026-08-01T00:00:00.000Z',
+ versions: [{
+ id: 'version-1',
+ version: 1,
+ submissionNote: null,
+ status: 'pending_review',
+ submittedAt: '2026-08-01T00:00:00.000Z',
+ completedAt: null,
+ imageUrls: [],
+ imageGroups: [{
+ imageId: 'image-1',
+ sourceName: '作品长图',
+ previewUrl: '/preview.webp',
+ previewWidth: 1000,
+ previewHeight: 2000,
+ width: 1000,
+ height: 2000,
+ slices: [{ url: '/slice.webp', width: 1000, height: 2000 }],
+ }],
+ referenceImageUrls: [],
+ referenceImageGroups: [],
+ reviews: [],
+ }],
+ permissions: {
+ canResubmit: false,
+ pendingReviewRoles: ['manager'],
+ },
+}
+
+describe('WorkReviewReviewerWorkspace', () => {
+ test('adds a normalized point annotation and submits the current review for revision', async () => {
+ window.PointerEvent = MouseEvent as typeof PointerEvent
+ const user = userEvent.setup()
+ const onSubmitReview = jest.fn().mockResolvedValue(undefined)
+ render(
)
+
+ await user.click(screen.getAllByRole('button', { name: '+ 添加标注' })[0])
+ const canvas = screen.getAllByRole('group', { name: /作品长图,可添加位置批注/ })[0]
+ jest.spyOn(canvas, 'getBoundingClientRect').mockReturnValue({
+ x: 0,
+ y: 0,
+ top: 0,
+ left: 0,
+ right: 1000,
+ bottom: 2000,
+ width: 1000,
+ height: 2000,
+ toJSON: () => ({}),
+ })
+ fireEvent.pointerDown(canvas, { button: 0, clientX: 250, clientY: 500 })
+ fireEvent.pointerUp(canvas, { button: 0, clientX: 250, clientY: 500 })
+
+ const comment = screen.getByRole('textbox', { name: /图 1 · 标注 1 修改意见/ })
+ await user.type(comment, '人物位置向左移动')
+ await user.click(screen.getByRole('button', { name: '完成' }))
+ await user.click(screen.getByRole('button', { name: '提交给修改人' }))
+
+ await waitFor(() => expect(onSubmitReview).toHaveBeenCalledTimes(1))
+ expect(onSubmitReview.mock.calls[0][1]).toMatchObject({
+ reviewerRole: 'manager',
+ imageComments: [{
+ imageIndex: 0,
+ decision: 'revision_required',
+ annotations: [{ x: 0.25, y: 0.25, comment: '人物位置向左移动' }],
+ }],
+ })
+ })
+
+ test('approves directly without requiring a modification annotation', async () => {
+ const user = userEvent.setup()
+ const onSubmitReview = jest.fn().mockResolvedValue(undefined)
+ render(
)
+
+ await user.click(screen.getByRole('button', { name: '通过' }))
+
+ await waitFor(() => expect(onSubmitReview).toHaveBeenCalledTimes(1))
+ expect(onSubmitReview.mock.calls[0][1]).toMatchObject({
+ reviewerRole: 'manager',
+ imageComments: [{
+ imageIndex: 0,
+ decision: 'approved',
+ comment: '通过',
+ annotations: [],
+ }],
+ })
+ })
+})
diff --git a/lib/work-review-policy.ts b/lib/work-review-policy.ts
index 675c5d72..b9671d43 100644
--- a/lib/work-review-policy.ts
+++ b/lib/work-review-policy.ts
@@ -1,6 +1,60 @@
export type WorkReviewDecision = 'approved' | 'revision_required'
export type WorkReviewReviewerRole = 'manager' | 'final_reviewer'
+export type NormalizedWorkReviewAnnotation = {
+ id: string
+ x: number
+ y: number
+ comment: string
+}
+
+export type WorkReviewAnnotationValidationResult =
+ | { ok: true; annotations: NormalizedWorkReviewAnnotation[] }
+ | { ok: false; error: string }
+
+const WORK_REVIEW_ANNOTATION_LIMIT = 50
+const WORK_REVIEW_ANNOTATION_COMMENT_LIMIT = 1000
+
+export function validateWorkReviewAnnotations(value: unknown): WorkReviewAnnotationValidationResult {
+ if (value == null) return { ok: true, annotations: [] }
+ if (!Array.isArray(value)) return { ok: false, error: '图片批注格式无效' }
+ if (value.length > WORK_REVIEW_ANNOTATION_LIMIT) {
+ return { ok: false, error: `单张图片最多添加 ${WORK_REVIEW_ANNOTATION_LIMIT} 个批注` }
+ }
+
+ const ids = new Set
()
+ const annotations: NormalizedWorkReviewAnnotation[] = []
+ for (const raw of value) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
+ return { ok: false, error: '图片批注格式无效' }
+ }
+ const item = raw as Record
+ const id = String(item.id ?? '').trim()
+ const x = item.x
+ const y = item.y
+ const comment = String(item.comment ?? '').trim()
+ if (!id || id.length > 64 || ids.has(id)) {
+ return { ok: false, error: '图片批注编号无效或重复' }
+ }
+ if (typeof x !== 'number' || !Number.isFinite(x) || x < 0 || x > 1
+ || typeof y !== 'number' || !Number.isFinite(y) || y < 0 || y > 1) {
+ return { ok: false, error: '图片批注位置无效' }
+ }
+ if (!comment) return { ok: false, error: '请填写每个标注点的修改意见' }
+ if (comment.length > WORK_REVIEW_ANNOTATION_COMMENT_LIMIT) {
+ return { ok: false, error: `单个标注点的修改意见不能超过 ${WORK_REVIEW_ANNOTATION_COMMENT_LIMIT} 个字` }
+ }
+ ids.add(id)
+ annotations.push({
+ id,
+ x: Math.round(x * 1_000_000) / 1_000_000,
+ y: Math.round(y * 1_000_000) / 1_000_000,
+ comment,
+ })
+ }
+ return { ok: true, annotations }
+}
+
type WorkReviewEmployeeIdentity = {
id?: unknown
dingtalkUserId?: unknown
diff --git a/lib/work-review-service.ts b/lib/work-review-service.ts
index 7f3dacb4..41124771 100644
--- a/lib/work-review-service.ts
+++ b/lib/work-review-service.ts
@@ -42,6 +42,7 @@ import {
getWorkReviewReviewerSelectionError,
isSameWorkReviewEmployeeAlias,
isSameWorkReviewEmployeeIdentity,
+ validateWorkReviewAnnotations,
} from '@/lib/work-review-policy'
const REVIEW_ROLES = {
@@ -970,7 +971,13 @@ function readImageComments(value: unknown, imageGroups: PerformanceSurveyStoredI
byIndex.set(imageIndex, item)
}
- return imageGroups.map((group, imageIndex): ImageCommentInput => {
+ let annotationCount = 0
+ return imageGroups.map((group, imageIndex): ImageCommentInput & { annotations: Array<{
+ id: string
+ x: number
+ y: number
+ comment: string
+ }> } => {
const item = byIndex.get(imageIndex)
if (!item) throw new WorkReviewApiError(`请填写图片「${group.sourceName}」的评审建议`)
const decision = clean(item.decision)
@@ -980,12 +987,17 @@ function readImageComments(value: unknown, imageGroups: PerformanceSurveyStoredI
const comment = clean(item.comment)
if (!comment) throw new WorkReviewApiError(`请填写图片「${group.sourceName}」的评审建议`)
if (comment.length > 2000) throw new WorkReviewApiError('单张图片的评审建议不能超过 2000 个字')
+ const annotationResult = validateWorkReviewAnnotations(item.annotations)
+ if (!annotationResult.ok) throw new WorkReviewApiError(annotationResult.error)
+ annotationCount += annotationResult.annotations.length
+ if (annotationCount > 200) throw new WorkReviewApiError('单次评审最多添加 200 个批注')
return {
imageId: group.imageId || `image-${imageIndex + 1}`,
imageIndex,
sourceName: group.sourceName,
decision,
comment,
+ annotations: annotationResult.annotations,
}
})
}
diff --git a/types/work-review.ts b/types/work-review.ts
index 679b8d59..d02d00cf 100644
--- a/types/work-review.ts
+++ b/types/work-review.ts
@@ -4,6 +4,13 @@ export type WorkReviewRole = 'manager' | 'final_reviewer'
export type WorkReviewDecision = 'approved' | 'revision_required'
+export type WorkReviewImageAnnotation = {
+ id: string
+ x: number
+ y: number
+ comment: string
+}
+
export type WorkReviewImageSlice = {
url: string
width: number
@@ -30,6 +37,7 @@ export type WorkReviewImageComment = {
sourceName?: string
decision: WorkReviewDecision
comment: string
+ annotations?: WorkReviewImageAnnotation[]
}
export type WorkReviewReview = {
@@ -152,6 +160,7 @@ export type WorkReviewReviewInput = {
imageIndex: number
decision: WorkReviewDecision
comment: string
+ annotations?: WorkReviewImageAnnotation[]
}>
generalComment: string
}