dsh-spec-collab 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/experience-review-checklist-2026-08-24.md +115 -0
- package/lib/client.js +1056 -537
- package/lib/index.js +56 -4
- package/lib/types/client/SpecWorkbench.d.ts +53 -1
- package/lib/types/client/SpecWorkbench.d.ts.map +1 -1
- package/lib/types/client/mount.d.ts.map +1 -1
- package/lib/types/client/review-anchors.d.ts +5 -2
- package/lib/types/client/review-anchors.d.ts.map +1 -1
- package/lib/types/engine.d.ts.map +1 -1
- package/lib/types/protocol.d.ts +2 -0
- package/lib/types/protocol.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/client/SpecWorkbench.tsx +338 -119
- package/src/client/mount.tsx +31 -5
- package/src/client/review-anchors.ts +65 -18
- package/src/client/workbench.module.css +138 -25
- package/src/engine.ts +46 -3
- package/src/protocol.ts +2 -2
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from 'react'
|
|
2
2
|
import MarkdownIt from 'markdown-it'
|
|
3
3
|
import ToastEditor from '@toast-ui/editor'
|
|
4
4
|
import '@toast-ui/editor/dist/i18n/zh-cn'
|
|
5
5
|
import { InputRule, inputRules } from 'prosemirror-inputrules'
|
|
6
|
-
import type { CollaborationAction, CommentResolution, MyActionItem, ParticipantRole, ParticipantSnapshot, RequirementStage, RequirementVersion, RequirementView, ReviewItemType, ReviewKind, ReviewWorkspaceSummary, SaveConflict } from '../protocol.ts'
|
|
6
|
+
import type { CollaborationAction, CommentResolution, CommentThread, MyActionItem, ParticipantRole, ParticipantSnapshot, RequirementStage, RequirementVersion, RequirementView, ReviewItemType, ReviewKind, ReviewWorkspaceSummary, SaveConflict } from '../protocol.ts'
|
|
7
7
|
import type { SpecApi } from './api.ts'
|
|
8
8
|
import { browserUuid } from './browser-uuid.ts'
|
|
9
|
-
import { reviewBlockSelector, reviewSourceSnippets, reviewTargetElements } from './review-anchors.ts'
|
|
9
|
+
import { commentTargetElements, reviewBlockSelector, reviewSourceSnippets, reviewTargetElements } from './review-anchors.ts'
|
|
10
10
|
import { friendlyActionError, workflowState, type TaskView, type WorkflowCommand, type WorkflowState } from './workflow.ts'
|
|
11
11
|
import css from './workbench.module.css'
|
|
12
12
|
|
|
@@ -24,9 +24,48 @@ const markdownShortcutsPlugin = () => ({ wysiwygPlugins: [() => inputRules({ rul
|
|
|
24
24
|
] })] })
|
|
25
25
|
type PrimaryMode = 'tasks' | 'discussion' | 'records'
|
|
26
26
|
type RecordView = 'decisions' | 'versions'
|
|
27
|
-
type CommentAnchor = { quote: string; prefix: string; suffix: string; heading?: string }
|
|
28
|
-
type
|
|
27
|
+
export type CommentAnchor = { quote: string; prefix: string; suffix: string; heading?: string }
|
|
28
|
+
export type InlinePopoverPosition = { rect: { top: number; left: number }; placement: 'above' | 'below'; maxHeight?: number }
|
|
29
|
+
export type EditorSelection = CommentAnchor & InlinePopoverPosition
|
|
29
30
|
type ReviewOpenRequest = { objectId: string; requestId: number }
|
|
31
|
+
type InlineReviewTarget = { itemId: string; sourceKey?: string } & Partial<InlinePopoverPosition>
|
|
32
|
+
type DocumentAnchorFocus = { kind: 'review'; objectId: string; sourceKey?: string } | { kind: 'comment'; objectId: string }
|
|
33
|
+
const inlineReviewPopoverSize = { width: 520, height: 620 } as const
|
|
34
|
+
function inlinePopoverPositionFromRect(rect: Pick<DOMRect, 'top' | 'bottom' | 'left'>, size: { width: number; height: number }): InlinePopoverPosition {
|
|
35
|
+
const padding = 12
|
|
36
|
+
const gap = 10
|
|
37
|
+
const viewportMaxHeight = Math.max(160, window.innerHeight - padding * 2)
|
|
38
|
+
const desiredHeight = Math.min(size.height, viewportMaxHeight)
|
|
39
|
+
const spaceBelow = Math.max(0, window.innerHeight - rect.bottom - gap - padding)
|
|
40
|
+
const spaceAbove = Math.max(0, rect.top - gap - padding)
|
|
41
|
+
const usefulBelowHeight = Math.min(desiredHeight, size.height > 360 ? 280 : 180)
|
|
42
|
+
const placement: InlinePopoverPosition['placement'] = spaceBelow >= usefulBelowHeight || spaceBelow >= spaceAbove ? 'below' : 'above'
|
|
43
|
+
const available = placement === 'below' ? spaceBelow : spaceAbove
|
|
44
|
+
const maxHeight = Math.max(160, Math.min(desiredHeight, available || viewportMaxHeight))
|
|
45
|
+
const rawTop = placement === 'below' ? rect.bottom + gap : rect.top - maxHeight - gap
|
|
46
|
+
const top = Math.min(Math.max(padding, rawTop), Math.max(padding, window.innerHeight - maxHeight - padding))
|
|
47
|
+
const left = Math.min(Math.max(padding, rect.left), Math.max(padding, window.innerWidth - size.width - padding))
|
|
48
|
+
return { rect: { top, left }, placement, maxHeight }
|
|
49
|
+
}
|
|
50
|
+
function visibleEditorContents(root: HTMLElement | null | undefined): HTMLElement | undefined {
|
|
51
|
+
const candidates = Array.from(root?.querySelectorAll<HTMLElement>('.toastui-editor-contents') ?? [])
|
|
52
|
+
const visible = candidates.filter(element => {
|
|
53
|
+
const rect = element.getBoundingClientRect()
|
|
54
|
+
const style = window.getComputedStyle(element)
|
|
55
|
+
return rect.width > 0 && rect.height > 0 && style.display !== 'none' && style.visibility !== 'hidden'
|
|
56
|
+
})
|
|
57
|
+
return visible.find(element => element.classList.contains('ProseMirror')) ?? visible[0] ?? candidates.find(element => element.classList.contains('ProseMirror')) ?? candidates.at(-1)
|
|
58
|
+
}
|
|
59
|
+
export function annotationScrollTargets(root: HTMLElement | null | undefined): HTMLElement[] {
|
|
60
|
+
if (!root) return []
|
|
61
|
+
const targets: HTMLElement[] = []
|
|
62
|
+
const add = (element: HTMLElement | null | undefined): void => {
|
|
63
|
+
if (element && !targets.includes(element)) targets.push(element)
|
|
64
|
+
}
|
|
65
|
+
add(visibleEditorContents(root))
|
|
66
|
+
root.querySelectorAll<HTMLElement>('.ProseMirror.toastui-editor-contents, .toastui-editor-ww-container, .toastui-editor-main').forEach(add)
|
|
67
|
+
return targets
|
|
68
|
+
}
|
|
30
69
|
function newParticipant(): ParticipantSnapshot { return { participantId: browserUuid(), nickname: '', role: 'product', kind: 'human' } }
|
|
31
70
|
function loadParticipant(): ParticipantSnapshot { try { const value = JSON.parse(localStorage.getItem('dsh-spec-collab.participant') ?? '') as ParticipantSnapshot; if (value.participantId) return { ...value, kind: 'human' } } catch {} return newParticipant() }
|
|
32
71
|
function stageLabel(stage: RequirementStage): string { return ({ 'product-review': '产品审核', 'product-confirmation': '产品确认', 'joint-review': '产研共审', ready: 'Ready' })[stage] }
|
|
@@ -67,8 +106,8 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
67
106
|
const [mobilePane, setMobilePane] = useState<'spec' | 'collab'>('spec')
|
|
68
107
|
const [reviewOpenRequest, setReviewOpenRequest] = useState<ReviewOpenRequest>()
|
|
69
108
|
const reviewOpenRequestId = useRef(0)
|
|
70
|
-
const [
|
|
71
|
-
const [
|
|
109
|
+
const [documentFocus, setDocumentFocus] = useState<DocumentAnchorFocus>()
|
|
110
|
+
const [documentFocusRequest, setDocumentFocusRequest] = useState(0)
|
|
72
111
|
const [draft, setDraft] = useState('')
|
|
73
112
|
const [summary, setSummary] = useState('')
|
|
74
113
|
const [notice, setNotice] = useState('')
|
|
@@ -77,8 +116,8 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
77
116
|
const [mergeDraft, setMergeDraft] = useState('')
|
|
78
117
|
const [myItems, setMyItems] = useState<MyActionItem[]>([])
|
|
79
118
|
const [commentText, setCommentText] = useState('')
|
|
80
|
-
const [selection, setSelection] = useState<CommentAnchor>()
|
|
81
119
|
const [draftSelection, setDraftSelection] = useState<EditorSelection>()
|
|
120
|
+
const [inlineReview, setInlineReview] = useState<InlineReviewTarget>()
|
|
82
121
|
const visibleRequirements = requirements.filter(item => Boolean(item.archivedAt) === showArchived)
|
|
83
122
|
const selected = requirements.find(item => item.id === selectedId) ?? visibleRequirements[0]
|
|
84
123
|
const manageTarget = requirements.find(item => item.id === manageTargetId)
|
|
@@ -86,15 +125,25 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
86
125
|
const currentMyItems = selected ? myItems.filter(item => item.requirementId === selected.id) : []
|
|
87
126
|
const currentReviews = selected?.reviewItems.filter(item => item.commit === selected.currentCommit && !['resolved', 'invalidated', 'non-blocking-verify'].includes(item.status)) ?? []
|
|
88
127
|
const documentReviews = useMemo(() => selected?.reviewItems.filter(item => item.commit === selected.currentCommit && !['resolved', 'invalidated'].includes(item.status)).slice().sort((left, right) => Number(right.status !== 'non-blocking-verify') - Number(left.status !== 'non-blocking-verify') || Number(right.severity === 'blocking') - Number(left.severity === 'blocking') || right.updatedAt - left.updatedAt) ?? [], [selected?.reviewItems, selected?.currentCommit])
|
|
128
|
+
const documentComments = useMemo(() => selected?.comments.filter(item => item.commit === selected.currentCommit && !['invalidated', 'orphaned'].includes(item.status)).slice().sort((left, right) => Number(right.status === 'open') - Number(left.status === 'open') || right.updatedAt - left.updatedAt) ?? [], [selected?.comments, selected?.currentCommit])
|
|
129
|
+
const focusedReviewId = documentFocus?.kind === 'review' ? documentFocus.objectId : undefined
|
|
130
|
+
const focusedCommentId = documentFocus?.kind === 'comment' ? documentFocus.objectId : undefined
|
|
131
|
+
const inlineReviewItem = selected?.reviewItems.find(item => item.id === inlineReview?.itemId)
|
|
132
|
+
const nextInlineReview = selected && inlineReviewItem ? currentReviews.find(item => item.status === 'open' && item.id !== inlineReviewItem.id) : undefined
|
|
89
133
|
const pendingPatches = selected?.patches.filter(item => item.baseCommit === selected.currentCommit && item.status === 'pending') ?? []
|
|
90
134
|
const openDiscussions = selected?.comments.filter(item => item.commit === selected.currentCommit && item.status === 'open').length ?? 0
|
|
91
135
|
const failedChecks = selected?.readiness.filter(item => !item.passed).length ?? 0
|
|
136
|
+
const openReviewCount = currentReviews.filter(item => item.status === 'open').length
|
|
137
|
+
const blockingReviewCount = currentReviews.filter(item => item.status === 'open' && item.severity === 'blocking').length
|
|
138
|
+
const activeDecisionCount = selected?.decisions.filter(item => item.commit === selected.currentCommit && item.status === 'active').length ?? 0
|
|
139
|
+
const invalidatedDecisionCount = selected?.decisions.filter(item => item.status === 'invalidated').length ?? 0
|
|
140
|
+
const runningAiCount = selected?.aiRuns.filter(item => item.commit === selected.currentCommit && ['queued', 'running'].includes(item.status)).length ?? 0
|
|
92
141
|
const workflow = selected ? workflowState(selected, participant.role) : undefined
|
|
93
142
|
|
|
94
143
|
const refresh = async (): Promise<void> => { try { const state = await api.state(); setRequirements(state.requirements); setParticipantBindings(state.participants); const binding = state.participants.find(item => item.participantId === participant.participantId); if (binding && binding.role !== participant.role) setParticipant(current => ({ ...current, role: binding.role })); setSelectedId(current => current && state.requirements.some(item => item.id === current) ? current : state.requirements[0]?.id) } catch (error) { setNotice(error instanceof Error ? error.message : String(error)) } }
|
|
95
144
|
useEffect(() => { void refresh(); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))); return api.events(() => { void refresh() }) }, [])
|
|
96
145
|
useEffect(() => { if (selected) setDraft(selected.version.markdown) }, [selected?.id, selected?.currentCommit])
|
|
97
|
-
useEffect(() => {
|
|
146
|
+
useEffect(() => { setDocumentFocus(undefined); setDraftSelection(undefined); setCommentText(''); setInlineReview(undefined) }, [selected?.id, selected?.currentCommit])
|
|
98
147
|
useEffect(() => { localStorage.setItem('dsh-spec-collab.participant', JSON.stringify(participant)) }, [participant])
|
|
99
148
|
useEffect(() => { localStorage.setItem('dsh-spec-collab.documents-width', String(documentsWidth)) }, [documentsWidth])
|
|
100
149
|
useEffect(() => { localStorage.setItem('dsh-spec-collab.review-width', String(reviewWidth)) }, [reviewWidth])
|
|
@@ -125,20 +174,50 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
125
174
|
const requestReview = async (reviewKind: ReviewKind): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'review.request', participant: actor, requirementId: selected.id, reviewKind })) }
|
|
126
175
|
const confirm = async (role: ParticipantRole): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'confirmation.create', participant: actor, requirementId: selected.id, role, scope: 'version' })) }
|
|
127
176
|
const advance = async (): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'stage.advance', participant: actor, requirementId: selected.id })) }
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
|
|
177
|
+
const scrollToCollabObject = (objectId: string): void => {
|
|
178
|
+
window.setTimeout(() => document.getElementById(`spec-object-${objectId}`)?.scrollIntoView({ block: 'center' }), 100)
|
|
179
|
+
}
|
|
180
|
+
const focusDocumentAnchor = (focus: DocumentAnchorFocus): void => {
|
|
181
|
+
setDocumentFocus(focus)
|
|
182
|
+
setDocumentFocusRequest(value => value + 1)
|
|
131
183
|
}
|
|
132
|
-
const
|
|
184
|
+
const focusReviewItem = (objectId: string, sourceKey?: string): void => {
|
|
185
|
+
focusDocumentAnchor({ kind: 'review', objectId, ...(sourceKey ? { sourceKey } : {}) })
|
|
186
|
+
}
|
|
187
|
+
const focusCommentItem = (objectId: string): void => {
|
|
188
|
+
focusDocumentAnchor({ kind: 'comment', objectId })
|
|
189
|
+
}
|
|
190
|
+
const openReviewItem = (objectId: string, position?: InlinePopoverPosition, sourceKey?: string, pane: 'spec' | 'collab' = 'spec'): void => {
|
|
133
191
|
setPrimaryMode('tasks')
|
|
134
192
|
setTaskView('review')
|
|
193
|
+
if (pane === 'collab') setReviewOpen(true)
|
|
194
|
+
setMobilePane('spec')
|
|
195
|
+
setDraftSelection(undefined)
|
|
196
|
+
setCommentText('')
|
|
197
|
+
focusReviewItem(objectId, sourceKey)
|
|
198
|
+
setInlineReview({ itemId: objectId, ...(sourceKey ? { sourceKey } : {}), ...(position ? { rect: position.rect, placement: position.placement, ...(position.maxHeight ? { maxHeight: position.maxHeight } : {}) } : {}) })
|
|
199
|
+
if (!position) {
|
|
200
|
+
window.setTimeout(() => {
|
|
201
|
+
const fallbackPosition = inlinePopoverPositionFromRect({ top: 144, bottom: 154, left: Math.max(12, window.innerWidth / 2 - inlineReviewPopoverSize.width / 2) }, inlineReviewPopoverSize)
|
|
202
|
+
setInlineReview(current => current?.itemId === objectId && !current.rect ? { ...current, rect: fallbackPosition.rect, placement: fallbackPosition.placement, ...(fallbackPosition.maxHeight ? { maxHeight: fallbackPosition.maxHeight } : {}) } : current)
|
|
203
|
+
}, 420)
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const updateInlineReviewPosition = (objectId: string, position: InlinePopoverPosition, sourceKey?: string): void => {
|
|
207
|
+
setInlineReview(current => current?.itemId === objectId ? { itemId: objectId, ...(sourceKey ? { sourceKey } : current.sourceKey ? { sourceKey: current.sourceKey } : {}), rect: position.rect, placement: position.placement, ...(position.maxHeight ? { maxHeight: position.maxHeight } : {}) } : current)
|
|
208
|
+
}
|
|
209
|
+
const openCommentItem = (objectId: string, pane: 'spec' | 'collab' = 'collab'): void => {
|
|
210
|
+
setPrimaryMode('discussion')
|
|
135
211
|
setReviewOpen(true)
|
|
136
212
|
setMobilePane(pane)
|
|
137
|
-
|
|
138
|
-
|
|
213
|
+
focusCommentItem(objectId)
|
|
214
|
+
scrollToCollabObject(objectId)
|
|
139
215
|
}
|
|
140
|
-
const locateReviewItem = (objectId: string): void => {
|
|
141
|
-
|
|
216
|
+
const locateReviewItem = (objectId: string, sourceKey?: string): void => {
|
|
217
|
+
openReviewItem(objectId, undefined, sourceKey)
|
|
218
|
+
}
|
|
219
|
+
const locateCommentItem = (objectId: string): void => {
|
|
220
|
+
focusCommentItem(objectId)
|
|
142
221
|
setMobilePane('spec')
|
|
143
222
|
}
|
|
144
223
|
const executeWorkflow = async (command: WorkflowCommand): Promise<void> => {
|
|
@@ -159,11 +238,28 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
159
238
|
}
|
|
160
239
|
const openMyItem = (item: MyActionItem): void => {
|
|
161
240
|
if (item.target.tab === 'review') { openReviewItem(item.target.objectId); return }
|
|
162
|
-
if (item.target.tab === 'discussion')
|
|
241
|
+
if (item.target.tab === 'discussion') { openCommentItem(item.target.objectId); return }
|
|
163
242
|
else if (item.target.tab === 'decisions') { setPrimaryMode('records'); setRecordView('decisions') }
|
|
164
243
|
else { setPrimaryMode('tasks'); setTaskView(item.target.tab === 'patches' ? 'patches' : item.target.tab === 'ready' ? 'ready' : 'review') }
|
|
165
244
|
setMobilePane('collab')
|
|
166
|
-
|
|
245
|
+
scrollToCollabObject(item.target.objectId)
|
|
246
|
+
}
|
|
247
|
+
const openTaskView = (view: TaskView): void => {
|
|
248
|
+
setPrimaryMode('tasks')
|
|
249
|
+
setTaskView(view)
|
|
250
|
+
setReviewOpen(true)
|
|
251
|
+
setMobilePane('collab')
|
|
252
|
+
}
|
|
253
|
+
const openDiscussionView = (): void => {
|
|
254
|
+
setPrimaryMode('discussion')
|
|
255
|
+
setReviewOpen(true)
|
|
256
|
+
setMobilePane('collab')
|
|
257
|
+
}
|
|
258
|
+
const openRecordView = (view: RecordView): void => {
|
|
259
|
+
setPrimaryMode('records')
|
|
260
|
+
setRecordView(view)
|
|
261
|
+
setReviewOpen(true)
|
|
262
|
+
setMobilePane('collab')
|
|
167
263
|
}
|
|
168
264
|
const resizePane = (side: 'documents' | 'review', event: ReactPointerEvent<HTMLDivElement>): void => {
|
|
169
265
|
event.preventDefault()
|
|
@@ -180,15 +276,24 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
180
276
|
const archiveRequirement = async (target: RequirementView): Promise<void> => { const archived = !target.archivedAt; if (await act(actor => ({ kind: 'requirement.archive', participant: actor, requirementId: target.id, archived }))) { setManageMenuId(undefined); setSelectedId(visibleRequirements.find(item => item.id !== target.id)?.id) } }
|
|
181
277
|
const deleteRequirement = async (): Promise<void> => { if (!manageTarget) return; if (await act(actor => ({ kind: 'requirement.delete', participant: actor, requirementId: manageTarget.id }))) { setDeleteOpen(false); setManageMenuId(undefined); setManageTargetId(undefined) } }
|
|
182
278
|
|
|
183
|
-
const
|
|
184
|
-
if (!
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
279
|
+
const updateDraftSelection = (value?: EditorSelection): void => {
|
|
280
|
+
if (!value) {
|
|
281
|
+
setDraftSelection(current => commentText.trim() ? current : undefined)
|
|
282
|
+
return
|
|
283
|
+
}
|
|
284
|
+
const sameAnchor = draftSelection?.quote === value.quote && draftSelection.prefix === value.prefix && draftSelection.suffix === value.suffix && draftSelection.heading === value.heading
|
|
285
|
+
if (!sameAnchor) setCommentText('')
|
|
286
|
+
setDraftSelection(value)
|
|
287
|
+
setInlineReview(undefined)
|
|
288
|
+
setDocumentFocus(undefined)
|
|
289
|
+
}
|
|
290
|
+
const cancelCommentDraft = (): void => { setDraftSelection(undefined); setCommentText('') }
|
|
291
|
+
const addComment = async (): Promise<void> => {
|
|
292
|
+
if (!selected || !draftSelection || !commentText.trim()) return
|
|
293
|
+
const anchor: CommentAnchor = { quote: draftSelection.quote, prefix: draftSelection.prefix, suffix: draftSelection.suffix, ...(draftSelection.heading ? { heading: draftSelection.heading } : {}) }
|
|
294
|
+
const ok = await act(actor => ({ kind: 'comment.create', participant: actor, requirementId: selected.id, commit: selected.currentCommit, anchor, body: commentText.trim() }))
|
|
295
|
+
if (ok) { setDraftSelection(undefined); setCommentText(''); setNotice('讨论已提交,AI 正在结合正文和工作区上下文分析') }
|
|
190
296
|
}
|
|
191
|
-
const addComment = async (): Promise<void> => { if (!selected || !selection) return; const ok = await act(actor => ({ kind: 'comment.create', participant: actor, requirementId: selected.id, commit: selected.currentCommit, anchor: selection, body: commentText })); if (ok) { setSelection(undefined); setCommentText(''); setNotice('讨论已提交,AI 正在结合正文和工作区上下文分析') } }
|
|
192
297
|
|
|
193
298
|
return <div className={css.workbench}>
|
|
194
299
|
<header className={css.header}>
|
|
@@ -214,8 +319,9 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
214
319
|
<div className={`${css.resizer} ${documentsOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整需求栏宽度" aria-orientation="vertical" onPointerDown={event => resizePane('documents', event)}/>
|
|
215
320
|
<main className={css.editorPane}>
|
|
216
321
|
<div className={css.toolbar}><div className={css.editorTitle}>{!documentsOpen && <button className={css.iconButton} aria-label="展开需求栏" title="展开需求栏" onClick={() => setDocumentsOpen(true)}>›</button>}<div><span>正式需求</span><strong>需求正文</strong></div></div><div><span className={draft !== selected?.version.markdown ? css.unsaved : css.editorMeta}>{draft !== selected?.version.markdown ? '有未保存改动' : '所有改动已保存'}</span><input className={css.summaryInput} required aria-label="说明本次改动" value={summary} onChange={event => setSummary(event.target.value)} placeholder="简要说明本次改动"/><button className={css.saveButton} disabled={busy || !selected || draft === selected.version.markdown || !summary.trim()} onClick={() => void save()}>保存版本</button>{!reviewOpen && <button className={css.iconButton} aria-label="展开下一步面板" title="展开下一步面板" onClick={() => setReviewOpen(true)}>‹</button>}</div></div>
|
|
217
|
-
{draftSelection && <
|
|
218
|
-
{
|
|
322
|
+
{draftSelection && <InlineCommentComposer selection={draftSelection} text={commentText} setText={setCommentText} busy={busy} cancel={cancelCommentDraft} submit={addComment}/>}
|
|
323
|
+
{inlineReviewItem && inlineReview?.rect && inlineReview.placement && <InlineReviewComposer item={inlineReviewItem} sourceMarkdown={selected?.version.markdown ?? ''} requirementId={selected?.id ?? ''} position={{ rect: inlineReview.rect, placement: inlineReview.placement, ...(inlineReview.maxHeight ? { maxHeight: inlineReview.maxHeight } : {}) }} nextItemId={nextInlineReview?.id} busy={busy} act={act} close={() => setInlineReview(undefined)} locateSource={sourceKey => locateReviewItem(inlineReviewItem.id, sourceKey)} complete={continueToNext => { if (continueToNext && nextInlineReview) openReviewItem(nextInlineReview.id); else setInlineReview(undefined) }}/>}
|
|
324
|
+
{!selected ? <div className={css.emptyMain}><div><span>从问题到共识</span><h2>创建第一份需求</h2><p>写下用户问题和期望结果,AI 会协助补齐范围、规则与验收标准。</p><button className={css.execute} onClick={() => { setCreateOpen(true); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))) }}>新建需求</button></div></div> : <><DocumentCollabBar activeMode={primaryMode} activeTaskView={taskView} activeRecordView={recordView} stats={{ openReviews: openReviewCount, blockingReviews: blockingReviewCount, openDiscussions, pendingPatches: pendingPatches.length, activeDecisions: activeDecisionCount, invalidatedDecisions: invalidatedDecisionCount, runningAi: runningAiCount, dirty: draft !== selected.version.markdown }} onOpenReviews={() => openTaskView('review')} onOpenDiscussion={openDiscussionView} onOpenPatches={() => openTaskView('patches')} onOpenDecisions={() => openRecordView('decisions')}/><div className={css.editorBody}><RichMarkdownEditor key={`${selected.id}:${selected.currentCommit}`} markdown={draft} reviewItems={documentReviews} comments={documentComments} documentFocus={documentFocus} focusRequest={documentFocusRequest} onChange={setDraft} onSelection={updateDraftSelection} onOpenReview={openReviewItem} onReviewLocated={updateInlineReviewPosition} onOpenComment={openCommentItem}/></div></>}
|
|
219
325
|
</main>
|
|
220
326
|
<div className={`${css.resizer} ${reviewOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整协作栏宽度" aria-orientation="vertical" onPointerDown={event => resizePane('review', event)}/>
|
|
221
327
|
<aside className={`${css.review} ${reviewOpen ? '' : css.paneClosed}`} aria-label="需求协作">
|
|
@@ -226,7 +332,7 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
226
332
|
<div className={css.contextNav} role="tablist" aria-label="待处理内容"><button role="tab" aria-selected={taskView === 'review'} className={taskView === 'review' ? css.activeContext : ''} onClick={() => setTaskView('review')}>问题{currentReviews.length > 0 && <span>{currentReviews.length}</span>}</button><button role="tab" aria-selected={taskView === 'patches'} className={taskView === 'patches' ? css.activeContext : ''} onClick={() => setTaskView('patches')}>AI 建议{pendingPatches.length > 0 && <span>{pendingPatches.length}</span>}</button><button role="tab" aria-selected={taskView === 'ready'} className={taskView === 'ready' ? css.activeContext : ''} onClick={() => setTaskView('ready')}>完成条件{failedChecks > 0 && <span>{failedChecks}</span>}</button></div>
|
|
227
333
|
<div className={css.threadList}>{taskView === 'review' && <ReviewPanel requirement={selected} act={act} api={api} focusedItemId={focusedReviewId} openRequest={reviewOpenRequest} onSelectReview={focusReviewItem} onLocateSource={locateReviewItem} onOpenRequestHandled={requestId => setReviewOpenRequest(current => current?.requestId === requestId ? undefined : current)}/>} {taskView === 'patches' && <PatchPanel requirement={selected} act={act}/>} {taskView === 'ready' && <ReadyPanel requirement={selected} act={act}/>}</div>
|
|
228
334
|
</>}
|
|
229
|
-
{selected && primaryMode === 'discussion' && <div className={css.threadList}><DiscussionPanel requirement={selected}
|
|
335
|
+
{selected && primaryMode === 'discussion' && <div className={css.threadList}><DiscussionPanel requirement={selected} focusedCommentId={focusedCommentId} onSelectComment={focusCommentItem} onLocateComment={locateCommentItem} act={act} api={api}/></div>}
|
|
230
336
|
{selected && primaryMode === 'records' && <><div className={css.contextNav} role="tablist" aria-label="需求记录"><button role="tab" aria-selected={recordView === 'decisions'} className={recordView === 'decisions' ? css.activeContext : ''} onClick={() => setRecordView('decisions')}>关键决策</button><button role="tab" aria-selected={recordView === 'versions'} className={recordView === 'versions' ? css.activeContext : ''} onClick={() => setRecordView('versions')}>版本历史</button></div><div className={css.threadList}>{recordView === 'decisions' && <DecisionPanel requirement={selected} act={act}/>} {recordView === 'versions' && <VersionPanel requirement={selected} api={api}/>}</div></>}
|
|
231
337
|
{!selected && <div className={css.emptyAside}><strong>等待创建需求</strong><p>创建后,下一步操作会显示在这里。</p></div>}
|
|
232
338
|
</aside>
|
|
@@ -261,8 +367,51 @@ function TaskQueue({ items, open }: { items: MyActionItem[]; open: (item: MyActi
|
|
|
261
367
|
return <details className={css.taskQueue}><summary><span>与你相关的事项</span><b>{items.length}</b></summary><div>{sorted.map(item => <button key={item.id} onClick={() => open(item)}><span>{item.blocking ? '优先' : '普通'}</span><div><strong>{taskTypeLabel[item.type]}</strong><small>{new Date(item.updatedAt).toLocaleString()}</small></div><i aria-hidden="true">›</i></button>)}</div></details>
|
|
262
368
|
}
|
|
263
369
|
|
|
264
|
-
type
|
|
265
|
-
function
|
|
370
|
+
type DocumentCollabStats = { openReviews: number; blockingReviews: number; openDiscussions: number; pendingPatches: number; activeDecisions: number; invalidatedDecisions: number; runningAi: number; dirty: boolean }
|
|
371
|
+
function DocumentCollabBar({ activeMode, activeTaskView, activeRecordView, stats, onOpenReviews, onOpenDiscussion, onOpenPatches, onOpenDecisions }: { activeMode: PrimaryMode; activeTaskView: TaskView; activeRecordView: RecordView; stats: DocumentCollabStats; onOpenReviews: () => void; onOpenDiscussion: () => void; onOpenPatches: () => void; onOpenDecisions: () => void }) {
|
|
372
|
+
const reviewActive = activeMode === 'tasks' && activeTaskView === 'review'
|
|
373
|
+
const patchActive = activeMode === 'tasks' && activeTaskView === 'patches'
|
|
374
|
+
const discussionActive = activeMode === 'discussion'
|
|
375
|
+
const decisionsActive = activeMode === 'records' && activeRecordView === 'decisions'
|
|
376
|
+
return <section className={css.editorCollabBar} aria-label="正文协作状态">
|
|
377
|
+
<div className={css.collabBarState}>
|
|
378
|
+
<span className={stats.dirty ? css.collabStateDirty : css.collabStateSaved}>{stats.dirty ? '草稿未保存' : '当前正文'}</span>
|
|
379
|
+
{stats.runningAi > 0 && <span className={css.collabStateRunning}><i className={css.runningDot}/>AI 分析中 · {stats.runningAi}</span>}
|
|
380
|
+
</div>
|
|
381
|
+
<div className={css.collabBarActions}>
|
|
382
|
+
<button type="button" className={`${css.collabMetric} ${reviewActive ? css.collabMetricActive : ''} ${stats.blockingReviews > 0 ? css.collabMetricWarn : ''}`} aria-pressed={reviewActive} onClick={onOpenReviews}><b>{stats.openReviews}</b><span>待回答问题</span>{stats.blockingReviews > 0 && <small>{stats.blockingReviews} 阻塞</small>}</button>
|
|
383
|
+
<button type="button" className={`${css.collabMetric} ${discussionActive ? css.collabMetricActive : ''}`} aria-pressed={discussionActive} onClick={onOpenDiscussion}><b>{stats.openDiscussions}</b><span>打开讨论</span></button>
|
|
384
|
+
<button type="button" className={`${css.collabMetric} ${patchActive ? css.collabMetricActive : ''}`} aria-pressed={patchActive} onClick={onOpenPatches}><b>{stats.pendingPatches}</b><span>AI 建议</span></button>
|
|
385
|
+
<button type="button" className={`${css.collabMetric} ${decisionsActive ? css.collabMetricActive : ''} ${stats.invalidatedDecisions > 0 ? css.collabMetricWarn : ''}`} aria-pressed={decisionsActive} onClick={onOpenDecisions}><b>{stats.activeDecisions}</b><span>生效决策</span>{stats.invalidatedDecisions > 0 && <small>{stats.invalidatedDecisions} 作废</small>}</button>
|
|
386
|
+
</div>
|
|
387
|
+
</section>
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
export function InlineCommentComposer({ selection, text, setText, busy, cancel, submit }: { selection: EditorSelection; text: string; setText: (value: string) => void; busy: boolean; cancel: () => void; submit: () => Promise<void> }) {
|
|
391
|
+
const quote = selection.quote.replace(/\s+/g, ' ').trim()
|
|
392
|
+
const excerpt = quote.length > 72 ? `${quote.slice(0, 72)}…` : quote
|
|
393
|
+
const canSubmit = !busy && Boolean(text.trim())
|
|
394
|
+
return <form className={`${css.selectionPrompt} ${selection.placement === 'above' ? css.selectionPromptAbove : css.selectionPromptBelow}`} role="dialog" aria-label="围绕选中正文发起讨论" style={{ top: selection.rect.top, left: selection.rect.left }} onSubmit={event => { event.preventDefault(); if (canSubmit) void submit() }} onKeyDown={event => {
|
|
395
|
+
if (event.key === 'Escape') { event.preventDefault(); cancel() }
|
|
396
|
+
if ((event.metaKey || event.ctrlKey) && event.key === 'Enter' && canSubmit) { event.preventDefault(); void submit() }
|
|
397
|
+
}}>
|
|
398
|
+
<div className={css.selectionPromptHead}>
|
|
399
|
+
<div><b>{selection.heading?.trim() || '正文片段'}</b><small>{excerpt}</small></div>
|
|
400
|
+
<button type="button" className={css.selectionPromptClose} aria-label="取消文字选择" title="取消" onClick={cancel}>×</button>
|
|
401
|
+
</div>
|
|
402
|
+
<textarea required autoFocus aria-label="讨论内容" value={text} onChange={event => setText(event.target.value)} placeholder="直接写下问题或补充意见"/>
|
|
403
|
+
<div className={css.selectionPromptActions}>
|
|
404
|
+
<small>提交后 AI 会结合正文和工作区上下文分析。</small>
|
|
405
|
+
<div className={css.selectionPromptButtons}>
|
|
406
|
+
<button type="button" className={css.selectionPromptCancel} onClick={cancel}>取消</button>
|
|
407
|
+
<button type="submit" className={css.selectionPromptSubmit} disabled={!canSubmit}>{busy ? '提交中' : '提交'}</button>
|
|
408
|
+
</div>
|
|
409
|
+
</div>
|
|
410
|
+
</form>
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
type DocumentMarker = { kind: 'review' | 'comment'; objectId: string; label: string; title: string; top: number; left: number; highlightTop: number; highlightLeft: number; highlightWidth: number; highlightHeight: number; blocking: boolean; selected: boolean }
|
|
414
|
+
function RichMarkdownEditor({ markdown, reviewItems, comments, documentFocus, focusRequest, onChange, onSelection, onOpenReview, onReviewLocated, onOpenComment }: { markdown: string; reviewItems: ReviewItemView[]; comments: CommentThread[]; documentFocus?: DocumentAnchorFocus | undefined; focusRequest: number; onChange: (markdown: string) => void; onSelection: (selection?: EditorSelection) => void; onOpenReview: (itemId: string, position?: InlinePopoverPosition, sourceKey?: string) => void; onReviewLocated: (itemId: string, position: InlinePopoverPosition, sourceKey?: string) => void; onOpenComment: (commentId: string) => void }) {
|
|
266
415
|
const shell = useRef<HTMLDivElement>(null)
|
|
267
416
|
const host = useRef<HTMLDivElement>(null)
|
|
268
417
|
const instance = useRef<ToastEditor>()
|
|
@@ -271,39 +420,74 @@ function RichMarkdownEditor({ markdown, reviewItems, selectedReviewId, focusRequ
|
|
|
271
420
|
const onChangeRef = useRef(onChange)
|
|
272
421
|
const onSelectionRef = useRef(onSelection)
|
|
273
422
|
const onOpenReviewRef = useRef(onOpenReview)
|
|
423
|
+
const onReviewLocatedRef = useRef(onReviewLocated)
|
|
424
|
+
const onOpenCommentRef = useRef(onOpenComment)
|
|
274
425
|
const reviewItemsRef = useRef(reviewItems)
|
|
275
|
-
const
|
|
426
|
+
const commentsRef = useRef(comments)
|
|
427
|
+
const documentFocusRef = useRef(documentFocus)
|
|
276
428
|
const syncAnnotationsRef = useRef<() => void>(() => {})
|
|
277
|
-
const [markers, setMarkers] = useState<
|
|
429
|
+
const [markers, setMarkers] = useState<DocumentMarker[]>([])
|
|
278
430
|
onChangeRef.current = onChange
|
|
279
431
|
onSelectionRef.current = onSelection
|
|
280
432
|
onOpenReviewRef.current = onOpenReview
|
|
433
|
+
onReviewLocatedRef.current = onReviewLocated
|
|
434
|
+
onOpenCommentRef.current = onOpenComment
|
|
281
435
|
reviewItemsRef.current = reviewItems
|
|
282
|
-
|
|
436
|
+
commentsRef.current = comments
|
|
437
|
+
documentFocusRef.current = documentFocus
|
|
283
438
|
useEffect(() => {
|
|
284
439
|
if (!host.current || !shell.current) return
|
|
285
440
|
const editor = new ToastEditor({ el: host.current, initialValue: markdown, initialEditType: 'wysiwyg', hideModeSwitch: true, toolbarItems: [], plugins: [markdownShortcutsPlugin], height: '100%', language: 'zh-CN', usageStatistics: false, autofocus: false })
|
|
286
441
|
const markInteraction = (): void => { interacted.current = true }
|
|
287
442
|
let frame = 0
|
|
288
443
|
const syncAnnotations = (): void => {
|
|
289
|
-
const editorRoot = host.current
|
|
444
|
+
const editorRoot = visibleEditorContents(host.current)
|
|
290
445
|
const shellElement = shell.current
|
|
291
446
|
if (!editorRoot || !shellElement) return
|
|
292
|
-
const
|
|
293
|
-
|
|
447
|
+
const reviewSourceClass = css.reviewSourceSelected!
|
|
448
|
+
const commentSourceClass = css.commentSourceSelected!
|
|
449
|
+
editorRoot.querySelectorAll<HTMLElement>('[data-annotation-kind]').forEach(element => { element.removeAttribute('data-annotation-kind'); element.removeAttribute('data-annotation-selected') })
|
|
450
|
+
editorRoot.querySelectorAll<HTMLElement>(`.${reviewSourceClass}, .${commentSourceClass}`).forEach(element => element.classList.remove(reviewSourceClass, commentSourceClass))
|
|
294
451
|
const shellRect = shellElement.getBoundingClientRect()
|
|
295
452
|
const slots = new Map<HTMLElement, number>()
|
|
296
|
-
const nextMarkers:
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
if (item.id === selectedReviewIdRef.current) targets.forEach(target => target.classList.add(selectedSourceClass))
|
|
300
|
-
const target = targets[0]
|
|
301
|
-
if (!target) return
|
|
453
|
+
const nextMarkers: DocumentMarker[] = []
|
|
454
|
+
const focus = documentFocusRef.current
|
|
455
|
+
const addMarker = (target: HTMLElement, marker: Omit<DocumentMarker, 'top' | 'left' | 'highlightTop' | 'highlightLeft' | 'highlightWidth' | 'highlightHeight'>): void => {
|
|
302
456
|
const rect = target.getBoundingClientRect()
|
|
303
457
|
if (rect.bottom < shellRect.top || rect.top > shellRect.bottom) return
|
|
304
458
|
const slot = slots.get(target) ?? 0
|
|
305
459
|
slots.set(target, slot + 1)
|
|
306
|
-
|
|
460
|
+
const highlightLeft = Math.max(0, rect.left - shellRect.left - 5)
|
|
461
|
+
const highlightTop = rect.top - shellRect.top - 3
|
|
462
|
+
nextMarkers.push({
|
|
463
|
+
...marker,
|
|
464
|
+
top: rect.top - shellRect.top + Math.min(8, rect.height / 2) + slot * 25,
|
|
465
|
+
left: Math.max(4, rect.left - shellRect.left - 30),
|
|
466
|
+
highlightTop,
|
|
467
|
+
highlightLeft,
|
|
468
|
+
highlightWidth: Math.max(28, Math.min(shellRect.width - highlightLeft - 8, rect.width + 10)),
|
|
469
|
+
highlightHeight: Math.max(26, Math.min(shellRect.height - Math.max(0, highlightTop) - 4, rect.height + 6)),
|
|
470
|
+
})
|
|
471
|
+
}
|
|
472
|
+
reviewItemsRef.current.forEach(item => {
|
|
473
|
+
const selected = focus?.kind === 'review' && focus.objectId === item.id
|
|
474
|
+
const targets = reviewTargetElements(editorRoot, item, selected ? focus.sourceKey : undefined)
|
|
475
|
+
const target = targets[0]
|
|
476
|
+
if (!target) return
|
|
477
|
+
target.dataset.annotationKind = target.dataset.annotationKind === 'comment' ? 'mixed' : 'review'
|
|
478
|
+
if (selected) target.classList.add(reviewSourceClass)
|
|
479
|
+
if (selected) target.dataset.annotationSelected = 'review'
|
|
480
|
+
addMarker(target, { kind: 'review', objectId: item.id, label: item.severity === 'blocking' ? '!' : '?', title: item.question.trim() || item.statement.trim(), blocking: item.severity === 'blocking', selected })
|
|
481
|
+
})
|
|
482
|
+
commentsRef.current.forEach(comment => {
|
|
483
|
+
const selected = focus?.kind === 'comment' && focus.objectId === comment.id
|
|
484
|
+
const targets = commentTargetElements(editorRoot, comment.anchor)
|
|
485
|
+
const target = targets[0]
|
|
486
|
+
if (!target) return
|
|
487
|
+
target.dataset.annotationKind = target.dataset.annotationKind === 'review' ? 'mixed' : 'comment'
|
|
488
|
+
if (selected) target.classList.add(commentSourceClass)
|
|
489
|
+
if (selected) target.dataset.annotationSelected = 'comment'
|
|
490
|
+
addMarker(target, { kind: 'comment', objectId: comment.id, label: '评', title: comment.body.trim() || comment.anchor.quote.trim(), blocking: false, selected })
|
|
307
491
|
})
|
|
308
492
|
setMarkers(nextMarkers)
|
|
309
493
|
}
|
|
@@ -319,14 +503,12 @@ function RichMarkdownEditor({ markdown, reviewItems, selectedReviewId, focusRequ
|
|
|
319
503
|
const block = start?.closest<HTMLElement>(reviewBlockSelector)
|
|
320
504
|
const blockText = block?.textContent ?? quote
|
|
321
505
|
const quoteIndex = blockText.indexOf(quote)
|
|
322
|
-
const headings = Array.from(host.current?.querySelectorAll<HTMLElement>('
|
|
506
|
+
const headings = Array.from(visibleEditorContents(host.current)?.querySelectorAll<HTMLElement>('h1, h2, h3, h4') ?? [])
|
|
323
507
|
const anchorNode = block ?? start
|
|
324
508
|
const heading = anchorNode ? headings.filter(candidate => Boolean(candidate.compareDocumentPosition(anchorNode) & Node.DOCUMENT_POSITION_FOLLOWING)).at(-1)?.textContent?.trim() : undefined
|
|
325
509
|
const rect = range.getBoundingClientRect()
|
|
326
|
-
const
|
|
327
|
-
|
|
328
|
-
const top = below + 48 < window.innerHeight ? below : Math.max(8, rect.top - 46)
|
|
329
|
-
onSelectionRef.current({ quote, prefix: quoteIndex < 0 ? '' : blockText.slice(Math.max(0, quoteIndex - 80), quoteIndex), suffix: quoteIndex < 0 ? '' : blockText.slice(quoteIndex + quote.length, quoteIndex + quote.length + 80), ...(heading ? { heading } : {}), rect: { top, left } })
|
|
510
|
+
const position = inlinePopoverPositionFromRect(rect, { width: 360, height: 230 })
|
|
511
|
+
onSelectionRef.current({ quote, prefix: quoteIndex < 0 ? '' : blockText.slice(Math.max(0, quoteIndex - 80), quoteIndex), suffix: quoteIndex < 0 ? '' : blockText.slice(quoteIndex + quote.length, quoteIndex + quote.length + 80), ...(heading ? { heading } : {}), ...position })
|
|
330
512
|
}
|
|
331
513
|
editor.on('change', change)
|
|
332
514
|
host.current.addEventListener('beforeinput', markInteraction)
|
|
@@ -335,17 +517,23 @@ function RichMarkdownEditor({ markdown, reviewItems, selectedReviewId, focusRequ
|
|
|
335
517
|
host.current.addEventListener('pointerdown', markInteraction)
|
|
336
518
|
host.current.addEventListener('mouseup', selection)
|
|
337
519
|
host.current.addEventListener('keyup', selection)
|
|
338
|
-
const scrollContainer = host.current.querySelector<HTMLElement>('.toastui-editor-ww-container')
|
|
339
520
|
const scroll = (): void => { onSelectionRef.current(undefined); scheduleAnnotations() }
|
|
340
|
-
|
|
521
|
+
const scrollTargets = new Set<HTMLElement>()
|
|
522
|
+
const bindScrollTarget = (element: HTMLElement): void => {
|
|
523
|
+
if (scrollTargets.has(element)) return
|
|
524
|
+
scrollTargets.add(element)
|
|
525
|
+
element.addEventListener('scroll', scroll, { passive: true })
|
|
526
|
+
}
|
|
527
|
+
const bindAnnotationScrollTargets = (): void => annotationScrollTargets(host.current).forEach(bindScrollTarget)
|
|
528
|
+
bindAnnotationScrollTargets()
|
|
341
529
|
window.addEventListener('resize', scheduleAnnotations)
|
|
342
530
|
const resizeObserver = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(scheduleAnnotations)
|
|
343
531
|
resizeObserver?.observe(shell.current)
|
|
344
|
-
const mutationObserver = new MutationObserver(scheduleAnnotations)
|
|
532
|
+
const mutationObserver = new MutationObserver(() => { bindAnnotationScrollTargets(); scheduleAnnotations() })
|
|
345
533
|
mutationObserver.observe(host.current, { childList: true, subtree: true })
|
|
346
534
|
instance.current = editor
|
|
347
535
|
scheduleAnnotations()
|
|
348
|
-
return () => { cancelAnimationFrame(frame); mutationObserver.disconnect(); resizeObserver?.disconnect(); window.removeEventListener('resize', scheduleAnnotations);
|
|
536
|
+
return () => { cancelAnimationFrame(frame); mutationObserver.disconnect(); resizeObserver?.disconnect(); window.removeEventListener('resize', scheduleAnnotations); scrollTargets.forEach(element => element.removeEventListener('scroll', scroll)); host.current?.removeEventListener('beforeinput', markInteraction); host.current?.removeEventListener('paste', markInteraction); host.current?.removeEventListener('drop', markInteraction); host.current?.removeEventListener('pointerdown', markInteraction); host.current?.removeEventListener('mouseup', selection); host.current?.removeEventListener('keyup', selection); editor.destroy() }
|
|
349
537
|
}, [])
|
|
350
538
|
useEffect(() => {
|
|
351
539
|
const editor = instance.current
|
|
@@ -357,14 +545,31 @@ function RichMarkdownEditor({ markdown, reviewItems, selectedReviewId, focusRequ
|
|
|
357
545
|
}, [markdown])
|
|
358
546
|
useEffect(() => {
|
|
359
547
|
syncAnnotationsRef.current()
|
|
360
|
-
if (!
|
|
361
|
-
const
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
548
|
+
if (!documentFocus || focusRequest === 0) return
|
|
549
|
+
const findTarget = (): HTMLElement | undefined => {
|
|
550
|
+
const editorRoot = visibleEditorContents(host.current)
|
|
551
|
+
if (!editorRoot) return undefined
|
|
552
|
+
if (documentFocus.kind === 'review') {
|
|
553
|
+
const item = reviewItems.find(candidate => candidate.id === documentFocus.objectId)
|
|
554
|
+
return item ? reviewTargetElements(editorRoot, item, documentFocus.sourceKey)[0] : undefined
|
|
555
|
+
}
|
|
556
|
+
const comment = comments.find(candidate => candidate.id === documentFocus.objectId)
|
|
557
|
+
return comment ? commentTargetElements(editorRoot, comment.anchor)[0] : undefined
|
|
558
|
+
}
|
|
559
|
+
const findReviewMarker = (): HTMLElement | undefined => Array.from(shell.current?.querySelectorAll<HTMLElement>('[data-review-object-id]') ?? []).find(element => element.dataset.reviewObjectId === documentFocus.objectId)
|
|
560
|
+
const target = findTarget()
|
|
561
|
+
target?.scrollIntoView(documentFocus.kind === 'review' ? { block: 'center' } : { behavior: 'smooth', block: 'center' })
|
|
562
|
+
const updateLocatedReview = (): void => {
|
|
563
|
+
syncAnnotationsRef.current()
|
|
564
|
+
if (documentFocus.kind !== 'review') return
|
|
565
|
+
const anchor = findReviewMarker() ?? findTarget()
|
|
566
|
+
if (anchor) onReviewLocatedRef.current(documentFocus.objectId, inlinePopoverPositionFromRect(anchor.getBoundingClientRect(), inlineReviewPopoverSize), documentFocus.sourceKey)
|
|
567
|
+
}
|
|
568
|
+
if (documentFocus.kind === 'review') window.requestAnimationFrame(() => window.requestAnimationFrame(updateLocatedReview))
|
|
569
|
+
else window.setTimeout(updateLocatedReview, 220)
|
|
570
|
+
}, [reviewItems, comments, documentFocus, focusRequest])
|
|
571
|
+
return <div className={css.richEditorShell} ref={shell}><div className={css.richEditor} ref={host}/><div className={css.reviewAnchorLayer} aria-label="正文协作锚点">{markers.map(marker => <span key={`highlight-${marker.kind}-${marker.objectId}`} className={`${css.documentAnchorHighlight} ${marker.kind === 'comment' ? css.documentCommentHighlight : css.documentReviewHighlight} ${marker.blocking ? css.documentReviewHighlightBlocking : ''} ${marker.selected ? css.documentAnchorHighlightSelected : ''}`} style={{ top: marker.highlightTop, left: marker.highlightLeft, width: marker.highlightWidth, height: marker.highlightHeight }} aria-hidden="true"/>)}
|
|
572
|
+
{markers.map(marker => <button key={`${marker.kind}-${marker.objectId}`} type="button" className={`${marker.kind === 'comment' ? css.documentCommentAnchor : css.documentReviewAnchor} ${marker.blocking ? css.documentReviewAnchorBlocking : ''} ${marker.selected ? css.documentAnchorSelected : ''}`} style={{ top: marker.top, left: marker.left }} title={marker.title} aria-label={marker.kind === 'comment' ? `打开评论:${marker.title}` : `打开问题:${marker.title}`} data-review-object-id={marker.kind === 'review' ? marker.objectId : undefined} data-comment-object-id={marker.kind === 'comment' ? marker.objectId : undefined} onMouseDown={event => event.preventDefault()} onClick={event => marker.kind === 'comment' ? onOpenCommentRef.current(marker.objectId) : onOpenReviewRef.current(marker.objectId, inlinePopoverPositionFromRect(event.currentTarget.getBoundingClientRect(), inlineReviewPopoverSize))}>{marker.label}</button>)}</div></div>
|
|
368
573
|
}
|
|
369
574
|
|
|
370
575
|
type Act = (factory: (actor: ParticipantSnapshot) => CollaborationAction) => Promise<boolean>
|
|
@@ -372,11 +577,11 @@ const reviewKindLabel: Record<ReviewKind, string> = { 'product-first': '需求
|
|
|
372
577
|
const reviewTypeLabel: Record<ReviewItemType, string> = { goal: '目标', evidence: '依据', 'history-conflict': '历史冲突', 'current-implementation': '当前实现', scope: '范围', semantics: '规则语义', completeness: '完整性', acceptance: '验收', risk: '风险' }
|
|
373
578
|
const statusLabel: Record<string, string> = { queued: '排队中', running: '分析中', completed: '已完成', failed: '失败', open: '待处理', answered: '已回答待整理', 'joint-review': '待产研共议', 'non-blocking-verify': '保留待核对', resolved: '已解决', invalidated: '已失效', pending: '待确认', accepted: '已接受', rejected: '未采用', stale: '已过期', blocking: '阻塞', major: '重要', minor: '一般' }
|
|
374
579
|
const evidenceStatusLabel: Record<string, string> = { FACT: '已有依据', INFERENCE: '根据现有信息推断', ASSUMPTION: '暂定规则', TO_VERIFY: '待核对' }
|
|
580
|
+
const commentResolutionLabel: Record<CommentResolution, string> = { 'written-back': '已回写正文', decision: '形成决策', rejected: '不采纳', 'open-question': '转开放问题' }
|
|
375
581
|
function MarkdownBody({ text, className = '' }: { text: string; className?: string | undefined }) { return <div className={`${css.markdownBody} ${className}`} dangerouslySetInnerHTML={{ __html: md.render(text) }}/> }
|
|
376
582
|
type ReviewItemView = RequirementView['reviewItems'][number]
|
|
377
|
-
export function ReviewPanel({ requirement, act, api, focusedItemId, openRequest, onSelectReview, onLocateSource, onOpenRequestHandled }: { requirement: RequirementView; act: Act; api: SpecApi; focusedItemId?: string | undefined; openRequest?: ReviewOpenRequest | undefined; onSelectReview?: (itemId: string) => void; onLocateSource?: (itemId: string) => void; onOpenRequestHandled?: (requestId: number) => void }) {
|
|
583
|
+
export function ReviewPanel({ requirement, act, api, focusedItemId, openRequest, onSelectReview, onLocateSource, onOpenRequestHandled }: { requirement: RequirementView; act: Act; api: SpecApi; focusedItemId?: string | undefined; openRequest?: ReviewOpenRequest | undefined; onSelectReview?: (itemId: string) => void; onLocateSource?: (itemId: string, sourceKey?: string) => void; onOpenRequestHandled?: (requestId: number) => void }) {
|
|
378
584
|
const [selectedItemId, setSelectedItemId] = useState<string>()
|
|
379
|
-
const closeSelectedItem = useCallback(() => setSelectedItemId(undefined), [])
|
|
380
585
|
const current = requirement.reviewItems.filter(item => item.commit === requirement.currentCommit).slice().sort((left, right) => Number(right.severity === 'blocking') - Number(left.severity === 'blocking') || right.updatedAt - left.updatedAt)
|
|
381
586
|
const historical = requirement.reviewItems.filter(item => item.commit !== requirement.currentCommit)
|
|
382
587
|
const active = current.filter(item => !['resolved', 'invalidated', 'non-blocking-verify'].includes(item.status))
|
|
@@ -384,10 +589,13 @@ export function ReviewPanel({ requirement, act, api, focusedItemId, openRequest,
|
|
|
384
589
|
const unansweredCount = active.filter(item => item.status === 'open').length
|
|
385
590
|
const answeredCount = active.filter(item => item.status === 'answered').length
|
|
386
591
|
const processedCount = current.filter(item => item.status !== 'open').length
|
|
387
|
-
const selectedItem = [...current, ...historical].find(item => item.id === selectedItemId)
|
|
388
|
-
const nextAnswerable = active.find(item => item.status === 'open' && item.id !== selectedItemId)
|
|
389
592
|
const currentRuns = requirement.aiRuns.filter(run => run.commit === requirement.currentCommit)
|
|
390
|
-
const openItem = (itemId: string): void => {
|
|
593
|
+
const openItem = (itemId: string): void => {
|
|
594
|
+
setSelectedItemId(itemId)
|
|
595
|
+
const sourceKey = [...current, ...historical].find(item => item.id === itemId)?.sourceAnchors?.[0] ? `quote-0` : undefined
|
|
596
|
+
onSelectReview?.(itemId)
|
|
597
|
+
onLocateSource?.(itemId, sourceKey)
|
|
598
|
+
}
|
|
391
599
|
useEffect(() => {
|
|
392
600
|
if (!openRequest) return
|
|
393
601
|
if ([...current, ...historical].some(item => item.id === openRequest.objectId)) openItem(openRequest.objectId)
|
|
@@ -400,7 +608,6 @@ export function ReviewPanel({ requirement, act, api, focusedItemId, openRequest,
|
|
|
400
608
|
{active.length > 0 && <ReviewChecklist items={active} selectedItemId={focusedItemId ?? selectedItemId} open={openItem}/>}
|
|
401
609
|
{deferred.length > 0 && <details className={css.historyGroup}><summary>保留待核对 · {deferred.length}</summary><ReviewChecklist items={deferred} selectedItemId={focusedItemId ?? selectedItemId} open={openItem}/></details>}
|
|
402
610
|
{historical.length > 0 && <details className={css.historyGroup}><summary>历史问题 · {historical.length}</summary><ReviewChecklist items={historical.slice().reverse()} selectedItemId={focusedItemId ?? selectedItemId} open={openItem}/></details>}
|
|
403
|
-
{selectedItem && <ReviewDecisionDialog key={selectedItem.id} item={selectedItem} sourceMarkdown={requirement.version?.markdown ?? ''} requirementId={requirement.id} nextItemId={nextAnswerable?.id} act={act} close={closeSelectedItem} locateSource={() => { closeSelectedItem(); onLocateSource?.(selectedItem.id) }} complete={continueToNext => { if (continueToNext && nextAnswerable) openItem(nextAnswerable.id); else closeSelectedItem() }}/>}
|
|
404
611
|
</>
|
|
405
612
|
}
|
|
406
613
|
function ReviewChecklist({ items, selectedItemId, open }: { items: ReviewItemView[]; selectedItemId?: string | undefined; open: (itemId: string) => void }) {
|
|
@@ -426,70 +633,80 @@ const dispositionGuidance: Record<keyof typeof dispositionLabel, string> = {
|
|
|
426
633
|
'to-verify': '这项不会继续阻塞当前阶段,但会保留在待核对清单。',
|
|
427
634
|
'joint-review': '把问题留到产研共审,由产品和研发共同决定。',
|
|
428
635
|
}
|
|
429
|
-
function
|
|
636
|
+
export function InlineReviewComposer({ item, sourceMarkdown, requirementId, position, nextItemId, busy, act, close, locateSource, complete }: { item: ReviewItemView; sourceMarkdown: string; requirementId: string; position: InlinePopoverPosition; nextItemId?: string | undefined; busy: boolean; act: Act; close: () => void; locateSource: (sourceKey?: string) => void; complete: (continueToNext: boolean) => void }) {
|
|
430
637
|
const [disposition, setDisposition] = useState<keyof typeof dispositionLabel>('context')
|
|
431
638
|
const [body, setBody] = useState('')
|
|
432
|
-
const
|
|
433
|
-
const returnFocusRef = useRef<HTMLElement | null>(typeof document !== 'undefined' && document.activeElement instanceof HTMLElement ? document.activeElement : null)
|
|
639
|
+
const formRef = useRef<HTMLFormElement>(null)
|
|
434
640
|
const recommendations = item.recommendedOptions?.map(option => option.trim()).filter(Boolean).slice(0, 5) ?? []
|
|
435
641
|
const sourceSnippets = reviewSourceSnippets(sourceMarkdown, item)
|
|
642
|
+
const primarySource = sourceSnippets[0]
|
|
436
643
|
const canRespond = !item.response && item.status === 'open'
|
|
437
644
|
useEffect(() => {
|
|
438
|
-
const dialog = dialogRef.current
|
|
439
|
-
const focusableSelector = 'button:not(:disabled), select:not(:disabled), textarea:not(:disabled), input:not(:disabled), [href], [tabindex]:not([tabindex="-1"])'
|
|
440
|
-
const focusable = (): HTMLElement[] => dialog ? Array.from(dialog.querySelectorAll<HTMLElement>(focusableSelector)) : []
|
|
441
|
-
if (dialog && !dialog.contains(document.activeElement)) (dialog.querySelector<HTMLElement>('textarea') ?? focusable()[0])?.focus()
|
|
442
645
|
const keydown = (event: KeyboardEvent): void => {
|
|
443
646
|
if (event.key === 'Escape') { event.preventDefault(); close(); return }
|
|
444
|
-
if (event.key !== 'Tab') return
|
|
445
|
-
const controls = focusable()
|
|
446
|
-
if (controls.length === 0) { event.preventDefault(); return }
|
|
447
|
-
const first = controls[0]!
|
|
448
|
-
const last = controls[controls.length - 1]!
|
|
449
|
-
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus() }
|
|
450
|
-
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus() }
|
|
451
647
|
}
|
|
452
648
|
window.addEventListener('keydown', keydown)
|
|
453
|
-
|
|
649
|
+
window.setTimeout(() => formRef.current?.querySelector<HTMLElement>('textarea')?.focus(), 0)
|
|
650
|
+
return () => window.removeEventListener('keydown', keydown)
|
|
454
651
|
}, [close])
|
|
455
652
|
const choose = (option: string): void => { setBody(option); setDisposition('accept-modified') }
|
|
456
653
|
const submit = async (continueToNext: boolean): Promise<void> => { const answer = body.trim() || (disposition === 'joint-review' ? '转产研共同决策' : ''); if (answer && await act(actor => ({ kind: 'review.respond', participant: actor, requirementId, reviewItemId: item.id, disposition, body: answer }))) complete(continueToNext) }
|
|
457
|
-
const canSubmit = Boolean(body.trim()) || disposition === 'joint-review'
|
|
458
|
-
return <
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
654
|
+
const canSubmit = !busy && (Boolean(body.trim()) || disposition === 'joint-review')
|
|
655
|
+
return <form ref={formRef} className={`${css.inlineReviewPrompt} ${position.placement === 'above' ? css.selectionPromptAbove : css.selectionPromptBelow}`} role="dialog" aria-label="回答待处理问题" style={{ top: position.rect.top, left: position.rect.left, maxHeight: position.maxHeight }} onSubmit={event => { event.preventDefault(); if (canSubmit) void submit(Boolean(nextItemId)) }} onKeyDown={event => {
|
|
656
|
+
if ((event.metaKey || event.ctrlKey) && event.key === 'Enter' && canSubmit) { event.preventDefault(); void submit(Boolean(nextItemId)) }
|
|
657
|
+
}}>
|
|
658
|
+
<header className={css.inlineReviewHead}>
|
|
659
|
+
<div><div className={css.decisionTags}><b>{statusLabel[item.severity] ?? item.severity}</b><span>{reviewTypeLabel[item.type]}</span><span>{evidenceStatusLabel[item.epistemicStatus] ?? item.epistemicStatus}</span></div><strong>{item.statement}</strong></div>
|
|
660
|
+
<button type="button" aria-label="关闭问题窗口" title="关闭" onClick={close}>×</button>
|
|
661
|
+
</header>
|
|
662
|
+
<section className={css.inlineReviewQuestion}><span>待回答</span><MarkdownBody text={item.question}/></section>
|
|
663
|
+
{primarySource && <button type="button" className={css.inlineReviewSource} onClick={() => locateSource(primarySource.targetKey)}><span>{primarySource.label}{primarySource.line ? ` · 第 ${primarySource.line} 行` : ''}</span><q>{primarySource.markdown.replace(/\s+/g, ' ').slice(0, 96)}{primarySource.markdown.length > 96 ? '…' : ''}</q></button>}
|
|
664
|
+
{item.response ? <div className={css.decisionResponse}><span>已回复</span><strong>{item.response.participant.nickname}</strong><small>{dispositionLabel[item.response.disposition]}</small><MarkdownBody text={item.response.body}/></div> : canRespond ? <>
|
|
665
|
+
{recommendations.length > 0 && <fieldset className={`${css.decisionOptions} ${css.inlineDecisionOptions}`}><legend>可采用的回答</legend>{recommendations.map((option, index) => <button type="button" key={option} className={body === option ? css.selectedDecisionOption : ''} aria-pressed={body === option} onClick={() => choose(option)}><span>{option}</span><b>{body === option ? '已选择' : String(index + 1).padStart(2, '0')}</b></button>)}</fieldset>}
|
|
666
|
+
<div className={`${css.decisionForm} ${css.inlineDecisionForm}`}><label>保存后如何处理<select required value={disposition} onChange={event => setDisposition(event.target.value as keyof typeof dispositionLabel)}>{Object.entries(dispositionLabel).map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select></label><p className={css.decisionModeHint}>{dispositionGuidance[disposition]}</p><label>最终结论<textarea required value={body} onChange={event => setBody(event.target.value)} placeholder={disposition === 'evidence' ? '粘贴数据、案例或来源链接,并说明它支持什么结论' : disposition === 'joint-review' ? '可选:补充希望产品和研发重点讨论的边界' : '写清最终判断、适用范围、例外情况和取舍理由'}/></label></div>
|
|
667
|
+
<details className={css.inlineReviewDetails}><summary>影响与依据</summary><section><h3>为什么需要明确</h3><MarkdownBody text={item.impact}/></section><section><h3>依据与来源 · {item.evidence.length}</h3>{item.evidence.length === 0 ? <p className={css.decisionEmpty}>当前没有可核对的资料,可以按业务判断回答,或选择保留待核对。</p> : <div className={css.decisionEvidenceList}>{item.evidence.map((evidence, index) => <div className={css.decisionEvidence} key={`${evidence.source}-${index}`}><code>{evidence.source}{evidence.version ? `@${evidence.version}` : ''}</code><MarkdownBody text={evidence.statement}/></div>)}</div>}</section>{(item.affectedSections.length > 0 || item.affectedAcceptanceIds.length > 0) && <section><h3>可能影响</h3><p>{[...item.affectedSections, ...item.affectedAcceptanceIds].join(' · ')}</p></section>}</details>
|
|
668
|
+
<div className={css.inlineReviewActions}><button type="button" onClick={close}>取消</button><div>{nextItemId && <button type="button" disabled={!canSubmit} onClick={() => void submit(false)}>保存并留在此处</button>}<button type="submit" className={css.execute} disabled={!canSubmit}>{busy ? '保存中' : nextItemId ? '保存并下一题' : '保存回答'}</button></div></div>
|
|
669
|
+
</> : <div className={css.decisionResponse}><span>{statusLabel[item.status] ?? item.status}</span><strong>这条记录当前不可回复</strong><p>你仍可以查看完整问题、影响和来源。</p></div>}
|
|
670
|
+
</form>
|
|
671
|
+
}
|
|
672
|
+
export function DiscussionPanel({ requirement, focusedCommentId, onSelectComment, onLocateComment, act, api }: { requirement: RequirementView; selection?: { quote: string } | undefined; text?: string; setText?: (value: string) => void; cancel?: () => void; submit?: () => Promise<void>; focusedCommentId?: string | undefined; onSelectComment?: (commentId: string) => void; onLocateComment?: (commentId: string) => void; act: Act; api: SpecApi }) {
|
|
673
|
+
const locateComment = (commentId: string): void => {
|
|
674
|
+
onSelectComment?.(commentId)
|
|
675
|
+
onLocateComment?.(commentId)
|
|
676
|
+
}
|
|
677
|
+
const comments = requirement.comments.slice().sort((left, right) => Number(right.status === 'open') - Number(left.status === 'open') || right.updatedAt - left.updatedAt)
|
|
678
|
+
const currentComments = comments.filter(comment => comment.commit === requirement.currentCommit)
|
|
679
|
+
const openComments = currentComments.filter(comment => comment.status === 'open')
|
|
680
|
+
const closedComments = currentComments.filter(comment => comment.status !== 'open')
|
|
681
|
+
const historicalComments = comments.filter(comment => comment.commit !== requirement.currentCommit)
|
|
682
|
+
const renderThread = (comment: CommentThread) => {
|
|
683
|
+
const selected = focusedCommentId === comment.id
|
|
684
|
+
const currentVersion = comment.commit === requirement.currentCommit
|
|
685
|
+
const resolvedText = comment.resolution ? commentResolutionLabel[comment.resolution] : undefined
|
|
686
|
+
return <section id={`spec-object-${comment.id}`} className={`${css.commentThread} ${selected ? css.commentThreadSelected : ''} ${comment.status !== 'open' ? css.commentThreadClosed : ''}`} key={comment.id} aria-current={selected ? 'true' : undefined}>
|
|
687
|
+
<header className={css.commentThreadHead}>
|
|
688
|
+
<div className={css.commentGlyph} aria-hidden="true">评</div>
|
|
689
|
+
<div className={css.commentThreadMeta}>
|
|
690
|
+
<strong>{comment.author.nickname}</strong>
|
|
691
|
+
<div className={css.threadPills}><span>{currentVersion ? '当前正文' : '历史正文'}</span><span>{statusLabel[comment.status] ?? comment.status}</span><span>AI {statusLabel[comment.aiStatus] ?? comment.aiStatus}</span>{resolvedText && <span>{resolvedText}</span>}</div>
|
|
692
|
+
</div>
|
|
693
|
+
<button type="button" className={css.locateSourceButton} onClick={() => locateComment(comment.id)}>定位正文</button>
|
|
694
|
+
</header>
|
|
695
|
+
<button type="button" className={css.commentSourceButton} onClick={() => locateComment(comment.id)}><span>{comment.anchor.heading?.trim() || '原文片段'}</span><q>{comment.anchor.quote}</q></button>
|
|
696
|
+
<MarkdownBody text={comment.body} className={css.commentBody}/>
|
|
697
|
+
{comment.aiSessionId && <AiConversation api={api} requirementId={requirement.id} sessionId={comment.aiSessionId}/>}
|
|
698
|
+
{comment.replies.length > 0 && <div className={css.replyStack}>{comment.replies.map(reply => <div className={css.reply} key={reply.id}><strong>{reply.author.nickname}{reply.author.kind === 'ai' ? ' · 智能助手' : ''}</strong><MarkdownBody text={reply.body}/></div>)}</div>}
|
|
699
|
+
{comment.status === 'open' && <div className={css.commentActions}>{(['written-back', 'decision', 'rejected', 'open-question'] as CommentResolution[]).map(resolution => <button key={resolution} onClick={() => void act(actor => ({ kind: 'comment.resolve', participant: actor, requirementId: requirement.id, commentId: comment.id, resolution }))}>{commentResolutionLabel[resolution]}</button>)}</div>}
|
|
478
700
|
</section>
|
|
701
|
+
}
|
|
702
|
+
return <div className={css.discussionPanel}>
|
|
703
|
+
<div className={css.discussionSummary}><div><strong>正文讨论</strong><span>{openComments.length > 0 ? `${openComments.length} 个当前正文问题待收口` : '当前正文没有待处理讨论'}</span></div><b>{comments.length}</b></div>
|
|
704
|
+
{openComments.length === 0 && <div className={css.emptyPanel}><strong>没有打开的正文讨论</strong><p>在正文中选中片段,会就地出现讨论气泡。</p></div>}
|
|
705
|
+
{openComments.map(renderThread)}
|
|
706
|
+
{closedComments.length > 0 && <details className={css.historyGroup}><summary>当前正文已处理 · {closedComments.length}</summary><div className={css.threadStack}>{closedComments.map(renderThread)}</div></details>}
|
|
707
|
+
{historicalComments.length > 0 && <details className={css.historyGroup}><summary>历史正文讨论 · {historicalComments.length}</summary><div className={css.threadStack}>{historicalComments.map(renderThread)}</div></details>}
|
|
479
708
|
</div>
|
|
480
709
|
}
|
|
481
|
-
function DiscussionPanel({ requirement, selection, text, setText, cancel, submit, act, api }: { requirement: RequirementView; selection: { quote: string } | undefined; text: string; setText: (value: string) => void; cancel: () => void; submit: () => Promise<void>; participant: ParticipantSnapshot; act: Act; api: SpecApi }) {
|
|
482
|
-
return <>
|
|
483
|
-
{selection && <section className={css.newThread}>
|
|
484
|
-
<header><span>正文讨论</span><strong>围绕选中内容提问</strong></header>
|
|
485
|
-
<blockquote>{selection.quote}</blockquote>
|
|
486
|
-
<label>你想确认什么?<textarea required autoFocus value={text} onChange={event => setText(event.target.value)} placeholder="例如:这里的适用范围是否包含移动端?"/></label>
|
|
487
|
-
<small>提交后,AI 会结合当前正文和已关联的工作区上下文给出分析。</small>
|
|
488
|
-
<div><button onClick={cancel}>取消</button><button className={css.execute} disabled={!text.trim()} onClick={() => void submit()}>提交并让 AI 分析</button></div>
|
|
489
|
-
</section>}
|
|
490
|
-
{requirement.comments.slice().reverse().map(comment => <section id={`spec-object-${comment.id}`} key={comment.id}><blockquote>{comment.anchor.quote}</blockquote><strong>{comment.author.nickname}</strong><MarkdownBody text={comment.body}/><small>智能分析:{comment.aiStatus}{comment.aiSessionId ? ` · ${comment.aiSessionId.slice(0, 8)}` : ''}</small>{comment.aiSessionId && <AiConversation api={api} requirementId={requirement.id} sessionId={comment.aiSessionId}/>} {comment.replies.map(reply => <div className={css.reply} key={reply.id}><strong>{reply.author.nickname}{reply.author.kind === 'ai' ? ' · 智能助手' : ''}</strong><MarkdownBody text={reply.body}/></div>)}{comment.status === 'open' && <div>{(['written-back', 'decision', 'rejected', 'open-question'] as CommentResolution[]).map(resolution => <button key={resolution} onClick={() => void act(actor => ({ kind: 'comment.resolve', participant: actor, requirementId: requirement.id, commentId: comment.id, resolution }))}>{({ 'written-back': '已回写正文', decision: '形成决策', rejected: '不采纳', 'open-question': '转为开放问题' })[resolution]}</button>)}</div>}</section>)}
|
|
491
|
-
</>
|
|
492
|
-
}
|
|
493
710
|
function AiConversation({ api, requirementId, sessionId }: { api: SpecApi; requirementId: string; sessionId: string }) {
|
|
494
711
|
const [open, setOpen] = useState(false)
|
|
495
712
|
const [messages, setMessages] = useState<Array<{ role: 'user' | 'assistant'; text: string }>>([])
|
|
@@ -521,9 +738,11 @@ function PatchPanel({ requirement, act }: { requirement: RequirementView; act: A
|
|
|
521
738
|
}
|
|
522
739
|
function DecisionPanel({ requirement, act }: { requirement: RequirementView; act: Act }) {
|
|
523
740
|
const [open, setOpen] = useState(false)
|
|
524
|
-
const [form, setForm] = useState({ question: '', decision: '', rationale: '' })
|
|
525
|
-
const
|
|
526
|
-
|
|
741
|
+
const [form, setForm] = useState({ question: '', decision: '', rationale: '', sections: '', acceptanceIds: '' })
|
|
742
|
+
const affectedSections = form.sections.split(',').map(value => value.trim()).filter(Boolean)
|
|
743
|
+
const affectedAcceptanceIds = form.acceptanceIds.split(',').map(value => value.trim()).filter(Boolean)
|
|
744
|
+
const submit = async (): Promise<void> => { if (await act(actor => ({ kind: 'decision.create', participant: actor, requirementId: requirement.id, question: form.question, options: [], decision: form.decision, rationale: form.rationale, affectedSections, affectedAcceptanceIds }))) { setOpen(false); setForm({ question: '', decision: '', rationale: '', sections: '', acceptanceIds: '' }) } }
|
|
745
|
+
return <>{requirement.decisions.map(item => <section id={`spec-object-${item.id}`} key={item.id}><MarkdownBody text={item.question} className={css.reviewTitle}/><MarkdownBody text={item.decision}/><small>{item.rationale} · {item.confirmer.nickname} · {item.status === 'active' ? '生效中' : '已作废'}</small></section>)}{open ? <div className={css.decisionForm}><label>待决策问题(必填)<textarea required autoFocus value={form.question} onChange={event => setForm({ ...form, question: event.target.value })}/></label><label>确认结论(必填)<textarea required value={form.decision} onChange={event => setForm({ ...form, decision: event.target.value })}/></label><label>决策理由(选填)<textarea value={form.rationale} onChange={event => setForm({ ...form, rationale: event.target.value })}/></label><label>受影响章节(与 AC 至少填写一项,逗号分隔)<input value={form.sections} onChange={event => setForm({ ...form, sections: event.target.value })} placeholder="业务术语与规则"/></label><label>受影响 AC IDs(与章节至少填写一项,逗号分隔)<input value={form.acceptanceIds} onChange={event => setForm({ ...form, acceptanceIds: event.target.value })} placeholder="AC-RETRY-001"/></label><div className={css.cardActions}><button onClick={() => setOpen(false)}>取消</button><button className={css.execute} disabled={!form.question.trim() || !form.decision.trim() || (affectedSections.length === 0 && affectedAcceptanceIds.length === 0)} onClick={() => void submit()}>保存决策</button></div></div> : <button className={css.panelAction} onClick={() => setOpen(true)}>记录新决策</button>}</>
|
|
527
746
|
}
|
|
528
747
|
function VersionPanel({ requirement, api }: { requirement: RequirementView; api: SpecApi }) {
|
|
529
748
|
const [historical, setHistorical] = useState<RequirementVersion>()
|