dsh-spec-collab 0.2.0 → 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/README.md +35 -0
- package/docs/experience-review-checklist-2026-08-24.md +115 -0
- package/lib/client.js +1391 -388
- package/lib/index.js +408 -50
- package/lib/types/client/SpecWorkbench.d.ts +69 -0
- 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 +21 -0
- package/lib/types/client/review-anchors.d.ts.map +1 -0
- package/lib/types/client/workflow.d.ts +1 -0
- package/lib/types/client/workflow.d.ts.map +1 -1
- package/lib/types/engine.d.ts.map +1 -1
- package/lib/types/index.d.ts +4 -0
- package/lib/types/index.d.ts.map +1 -1
- package/lib/types/prompts.d.ts +18 -0
- package/lib/types/prompts.d.ts.map +1 -0
- package/lib/types/protocol.d.ts +7 -0
- package/lib/types/protocol.d.ts.map +1 -1
- package/lib/types/review-context.d.ts +10 -1
- package/lib/types/review-context.d.ts.map +1 -1
- package/lib/types/review-runtime.d.ts +4 -1
- package/lib/types/review-runtime.d.ts.map +1 -1
- package/lib/types/workspace-context.d.ts +2 -0
- package/lib/types/workspace-context.d.ts.map +1 -0
- package/package.json +1 -1
- package/src/client/SpecWorkbench.tsx +456 -47
- package/src/client/mount.tsx +31 -5
- package/src/client/review-anchors.ts +134 -0
- package/src/client/workbench.module.css +234 -45
- package/src/client/workflow.ts +7 -7
- package/src/engine.ts +46 -3
- package/src/index.ts +21 -3
- package/src/prompts.ts +100 -0
- package/src/protocol.ts +4 -2
- package/src/review-context.ts +25 -7
- package/src/review-runtime.ts +53 -34
- package/src/tools.ts +3 -3
- package/src/workspace-context.ts +114 -0
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import { useEffect, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from 'react'
|
|
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, 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 { commentTargetElements, reviewBlockSelector, reviewSourceSnippets, reviewTargetElements } from './review-anchors.ts'
|
|
9
10
|
import { friendlyActionError, workflowState, type TaskView, type WorkflowCommand, type WorkflowState } from './workflow.ts'
|
|
10
11
|
import css from './workbench.module.css'
|
|
11
12
|
|
|
@@ -23,7 +24,48 @@ const markdownShortcutsPlugin = () => ({ wysiwygPlugins: [() => inputRules({ rul
|
|
|
23
24
|
] })] })
|
|
24
25
|
type PrimaryMode = 'tasks' | 'discussion' | 'records'
|
|
25
26
|
type RecordView = 'decisions' | 'versions'
|
|
26
|
-
type CommentAnchor = { quote: string; prefix: string; suffix: string; heading?: string }
|
|
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
|
|
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
|
+
}
|
|
27
69
|
function newParticipant(): ParticipantSnapshot { return { participantId: browserUuid(), nickname: '', role: 'product', kind: 'human' } }
|
|
28
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() }
|
|
29
71
|
function stageLabel(stage: RequirementStage): string { return ({ 'product-review': '产品审核', 'product-confirmation': '产品确认', 'joint-review': '产研共审', ready: 'Ready' })[stage] }
|
|
@@ -62,6 +104,10 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
62
104
|
const [taskView, setTaskView] = useState<TaskView>('review')
|
|
63
105
|
const [recordView, setRecordView] = useState<RecordView>('decisions')
|
|
64
106
|
const [mobilePane, setMobilePane] = useState<'spec' | 'collab'>('spec')
|
|
107
|
+
const [reviewOpenRequest, setReviewOpenRequest] = useState<ReviewOpenRequest>()
|
|
108
|
+
const reviewOpenRequestId = useRef(0)
|
|
109
|
+
const [documentFocus, setDocumentFocus] = useState<DocumentAnchorFocus>()
|
|
110
|
+
const [documentFocusRequest, setDocumentFocusRequest] = useState(0)
|
|
65
111
|
const [draft, setDraft] = useState('')
|
|
66
112
|
const [summary, setSummary] = useState('')
|
|
67
113
|
const [notice, setNotice] = useState('')
|
|
@@ -70,22 +116,34 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
70
116
|
const [mergeDraft, setMergeDraft] = useState('')
|
|
71
117
|
const [myItems, setMyItems] = useState<MyActionItem[]>([])
|
|
72
118
|
const [commentText, setCommentText] = useState('')
|
|
73
|
-
const [
|
|
74
|
-
const [
|
|
119
|
+
const [draftSelection, setDraftSelection] = useState<EditorSelection>()
|
|
120
|
+
const [inlineReview, setInlineReview] = useState<InlineReviewTarget>()
|
|
75
121
|
const visibleRequirements = requirements.filter(item => Boolean(item.archivedAt) === showArchived)
|
|
76
122
|
const selected = requirements.find(item => item.id === selectedId) ?? visibleRequirements[0]
|
|
77
123
|
const manageTarget = requirements.find(item => item.id === manageTargetId)
|
|
78
124
|
const boundRole = participantBindings.find(item => item.participantId === participant.participantId)?.role
|
|
79
125
|
const currentMyItems = selected ? myItems.filter(item => item.requirementId === selected.id) : []
|
|
80
126
|
const currentReviews = selected?.reviewItems.filter(item => item.commit === selected.currentCommit && !['resolved', 'invalidated', 'non-blocking-verify'].includes(item.status)) ?? []
|
|
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
|
|
81
133
|
const pendingPatches = selected?.patches.filter(item => item.baseCommit === selected.currentCommit && item.status === 'pending') ?? []
|
|
82
134
|
const openDiscussions = selected?.comments.filter(item => item.commit === selected.currentCommit && item.status === 'open').length ?? 0
|
|
83
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
|
|
84
141
|
const workflow = selected ? workflowState(selected, participant.role) : undefined
|
|
85
142
|
|
|
86
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)) } }
|
|
87
144
|
useEffect(() => { void refresh(); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))); return api.events(() => { void refresh() }) }, [])
|
|
88
145
|
useEffect(() => { if (selected) setDraft(selected.version.markdown) }, [selected?.id, selected?.currentCommit])
|
|
146
|
+
useEffect(() => { setDocumentFocus(undefined); setDraftSelection(undefined); setCommentText(''); setInlineReview(undefined) }, [selected?.id, selected?.currentCommit])
|
|
89
147
|
useEffect(() => { localStorage.setItem('dsh-spec-collab.participant', JSON.stringify(participant)) }, [participant])
|
|
90
148
|
useEffect(() => { localStorage.setItem('dsh-spec-collab.documents-width', String(documentsWidth)) }, [documentsWidth])
|
|
91
149
|
useEffect(() => { localStorage.setItem('dsh-spec-collab.review-width', String(reviewWidth)) }, [reviewWidth])
|
|
@@ -116,9 +174,61 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
116
174
|
const requestReview = async (reviewKind: ReviewKind): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'review.request', participant: actor, requirementId: selected.id, reviewKind })) }
|
|
117
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' })) }
|
|
118
176
|
const advance = async (): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'stage.advance', participant: actor, requirementId: selected.id })) }
|
|
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)
|
|
183
|
+
}
|
|
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 => {
|
|
191
|
+
setPrimaryMode('tasks')
|
|
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')
|
|
211
|
+
setReviewOpen(true)
|
|
212
|
+
setMobilePane(pane)
|
|
213
|
+
focusCommentItem(objectId)
|
|
214
|
+
scrollToCollabObject(objectId)
|
|
215
|
+
}
|
|
216
|
+
const locateReviewItem = (objectId: string, sourceKey?: string): void => {
|
|
217
|
+
openReviewItem(objectId, undefined, sourceKey)
|
|
218
|
+
}
|
|
219
|
+
const locateCommentItem = (objectId: string): void => {
|
|
220
|
+
focusCommentItem(objectId)
|
|
221
|
+
setMobilePane('spec')
|
|
222
|
+
}
|
|
119
223
|
const executeWorkflow = async (command: WorkflowCommand): Promise<void> => {
|
|
120
224
|
if (!selected || command.kind === 'none') return
|
|
121
|
-
if (command.kind === 'open') {
|
|
225
|
+
if (command.kind === 'open') {
|
|
226
|
+
setPrimaryMode('tasks')
|
|
227
|
+
setTaskView(command.view)
|
|
228
|
+
setMobilePane('collab')
|
|
229
|
+
if (command.view === 'review' && command.objectId) openReviewItem(command.objectId)
|
|
230
|
+
return
|
|
231
|
+
}
|
|
122
232
|
if (command.kind === 'bind-workspace') { setBindWorkspaceOpen(true); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))); return }
|
|
123
233
|
if (command.kind === 'request-review') { setTaskView('review'); await requestReview(command.reviewKind); return }
|
|
124
234
|
if (command.kind === 'advance') { await advance(); return }
|
|
@@ -127,11 +237,29 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
127
237
|
await act(actor => ({ kind: 'ready.generate', participant: actor, requirementId: selected.id }))
|
|
128
238
|
}
|
|
129
239
|
const openMyItem = (item: MyActionItem): void => {
|
|
130
|
-
if (item.target.tab === '
|
|
240
|
+
if (item.target.tab === 'review') { openReviewItem(item.target.objectId); return }
|
|
241
|
+
if (item.target.tab === 'discussion') { openCommentItem(item.target.objectId); return }
|
|
131
242
|
else if (item.target.tab === 'decisions') { setPrimaryMode('records'); setRecordView('decisions') }
|
|
132
243
|
else { setPrimaryMode('tasks'); setTaskView(item.target.tab === 'patches' ? 'patches' : item.target.tab === 'ready' ? 'ready' : 'review') }
|
|
133
244
|
setMobilePane('collab')
|
|
134
|
-
|
|
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')
|
|
135
263
|
}
|
|
136
264
|
const resizePane = (side: 'documents' | 'review', event: ReactPointerEvent<HTMLDivElement>): void => {
|
|
137
265
|
event.preventDefault()
|
|
@@ -148,14 +276,24 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
148
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) } }
|
|
149
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) } }
|
|
150
278
|
|
|
151
|
-
const
|
|
152
|
-
if (!
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
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 正在结合正文和工作区上下文分析') }
|
|
157
296
|
}
|
|
158
|
-
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 正在自动分析理解、证据与关联影响') } }
|
|
159
297
|
|
|
160
298
|
return <div className={css.workbench}>
|
|
161
299
|
<header className={css.header}>
|
|
@@ -181,8 +319,9 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
181
319
|
<div className={`${css.resizer} ${documentsOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整需求栏宽度" aria-orientation="vertical" onPointerDown={event => resizePane('documents', event)}/>
|
|
182
320
|
<main className={css.editorPane}>
|
|
183
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>
|
|
184
|
-
{draftSelection && <
|
|
185
|
-
{
|
|
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></>}
|
|
186
325
|
</main>
|
|
187
326
|
<div className={`${css.resizer} ${reviewOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整协作栏宽度" aria-orientation="vertical" onPointerDown={event => resizePane('review', event)}/>
|
|
188
327
|
<aside className={`${css.review} ${reviewOpen ? '' : css.paneClosed}`} aria-label="需求协作">
|
|
@@ -191,9 +330,9 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
191
330
|
{workflow && <WorkflowFocus state={workflow} pendingForMe={currentMyItems.length} onExecute={() => void executeWorkflow(workflow.command)}/>}
|
|
192
331
|
{currentMyItems.length > 0 && <TaskQueue items={currentMyItems} open={openMyItem}/>}
|
|
193
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>
|
|
194
|
-
<div className={css.threadList}>{taskView === 'review' && <ReviewPanel requirement={selected}
|
|
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>
|
|
195
334
|
</>}
|
|
196
|
-
{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>}
|
|
197
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></>}
|
|
198
337
|
{!selected && <div className={css.emptyAside}><strong>等待创建需求</strong><p>创建后,下一步操作会显示在这里。</p></div>}
|
|
199
338
|
</aside>
|
|
@@ -228,21 +367,149 @@ function TaskQueue({ items, open }: { items: MyActionItem[]; open: (item: MyActi
|
|
|
228
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>
|
|
229
368
|
}
|
|
230
369
|
|
|
231
|
-
|
|
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 }) {
|
|
415
|
+
const shell = useRef<HTMLDivElement>(null)
|
|
232
416
|
const host = useRef<HTMLDivElement>(null)
|
|
233
417
|
const instance = useRef<ToastEditor>()
|
|
234
418
|
const interacted = useRef(false)
|
|
235
419
|
const syncing = useRef(false)
|
|
236
420
|
const onChangeRef = useRef(onChange)
|
|
237
421
|
const onSelectionRef = useRef(onSelection)
|
|
422
|
+
const onOpenReviewRef = useRef(onOpenReview)
|
|
423
|
+
const onReviewLocatedRef = useRef(onReviewLocated)
|
|
424
|
+
const onOpenCommentRef = useRef(onOpenComment)
|
|
425
|
+
const reviewItemsRef = useRef(reviewItems)
|
|
426
|
+
const commentsRef = useRef(comments)
|
|
427
|
+
const documentFocusRef = useRef(documentFocus)
|
|
428
|
+
const syncAnnotationsRef = useRef<() => void>(() => {})
|
|
429
|
+
const [markers, setMarkers] = useState<DocumentMarker[]>([])
|
|
238
430
|
onChangeRef.current = onChange
|
|
239
431
|
onSelectionRef.current = onSelection
|
|
432
|
+
onOpenReviewRef.current = onOpenReview
|
|
433
|
+
onReviewLocatedRef.current = onReviewLocated
|
|
434
|
+
onOpenCommentRef.current = onOpenComment
|
|
435
|
+
reviewItemsRef.current = reviewItems
|
|
436
|
+
commentsRef.current = comments
|
|
437
|
+
documentFocusRef.current = documentFocus
|
|
240
438
|
useEffect(() => {
|
|
241
|
-
if (!host.current) return
|
|
439
|
+
if (!host.current || !shell.current) return
|
|
242
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 })
|
|
243
441
|
const markInteraction = (): void => { interacted.current = true }
|
|
244
|
-
|
|
245
|
-
const
|
|
442
|
+
let frame = 0
|
|
443
|
+
const syncAnnotations = (): void => {
|
|
444
|
+
const editorRoot = visibleEditorContents(host.current)
|
|
445
|
+
const shellElement = shell.current
|
|
446
|
+
if (!editorRoot || !shellElement) return
|
|
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))
|
|
451
|
+
const shellRect = shellElement.getBoundingClientRect()
|
|
452
|
+
const slots = new Map<HTMLElement, number>()
|
|
453
|
+
const nextMarkers: DocumentMarker[] = []
|
|
454
|
+
const focus = documentFocusRef.current
|
|
455
|
+
const addMarker = (target: HTMLElement, marker: Omit<DocumentMarker, 'top' | 'left' | 'highlightTop' | 'highlightLeft' | 'highlightWidth' | 'highlightHeight'>): void => {
|
|
456
|
+
const rect = target.getBoundingClientRect()
|
|
457
|
+
if (rect.bottom < shellRect.top || rect.top > shellRect.bottom) return
|
|
458
|
+
const slot = slots.get(target) ?? 0
|
|
459
|
+
slots.set(target, slot + 1)
|
|
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 })
|
|
491
|
+
})
|
|
492
|
+
setMarkers(nextMarkers)
|
|
493
|
+
}
|
|
494
|
+
const scheduleAnnotations = (): void => { cancelAnimationFrame(frame); frame = requestAnimationFrame(syncAnnotations) }
|
|
495
|
+
syncAnnotationsRef.current = scheduleAnnotations
|
|
496
|
+
const change = (): void => { if (interacted.current && !syncing.current) onChangeRef.current(editor.getMarkdown()); scheduleAnnotations() }
|
|
497
|
+
const selection = (): void => {
|
|
498
|
+
const quote = editor.getSelectedText().trim()
|
|
499
|
+
const domSelection = window.getSelection()
|
|
500
|
+
if (!quote || !domSelection || domSelection.rangeCount === 0 || domSelection.isCollapsed) { onSelectionRef.current(undefined); return }
|
|
501
|
+
const range = domSelection.getRangeAt(0)
|
|
502
|
+
const start = range.startContainer instanceof HTMLElement ? range.startContainer : range.startContainer.parentElement
|
|
503
|
+
const block = start?.closest<HTMLElement>(reviewBlockSelector)
|
|
504
|
+
const blockText = block?.textContent ?? quote
|
|
505
|
+
const quoteIndex = blockText.indexOf(quote)
|
|
506
|
+
const headings = Array.from(visibleEditorContents(host.current)?.querySelectorAll<HTMLElement>('h1, h2, h3, h4') ?? [])
|
|
507
|
+
const anchorNode = block ?? start
|
|
508
|
+
const heading = anchorNode ? headings.filter(candidate => Boolean(candidate.compareDocumentPosition(anchorNode) & Node.DOCUMENT_POSITION_FOLLOWING)).at(-1)?.textContent?.trim() : undefined
|
|
509
|
+
const rect = range.getBoundingClientRect()
|
|
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 })
|
|
512
|
+
}
|
|
246
513
|
editor.on('change', change)
|
|
247
514
|
host.current.addEventListener('beforeinput', markInteraction)
|
|
248
515
|
host.current.addEventListener('paste', markInteraction)
|
|
@@ -250,8 +517,23 @@ function RichMarkdownEditor({ markdown, onChange, onSelection }: { markdown: str
|
|
|
250
517
|
host.current.addEventListener('pointerdown', markInteraction)
|
|
251
518
|
host.current.addEventListener('mouseup', selection)
|
|
252
519
|
host.current.addEventListener('keyup', selection)
|
|
520
|
+
const scroll = (): void => { onSelectionRef.current(undefined); scheduleAnnotations() }
|
|
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()
|
|
529
|
+
window.addEventListener('resize', scheduleAnnotations)
|
|
530
|
+
const resizeObserver = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(scheduleAnnotations)
|
|
531
|
+
resizeObserver?.observe(shell.current)
|
|
532
|
+
const mutationObserver = new MutationObserver(() => { bindAnnotationScrollTargets(); scheduleAnnotations() })
|
|
533
|
+
mutationObserver.observe(host.current, { childList: true, subtree: true })
|
|
253
534
|
instance.current = editor
|
|
254
|
-
|
|
535
|
+
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() }
|
|
255
537
|
}, [])
|
|
256
538
|
useEffect(() => {
|
|
257
539
|
const editor = instance.current
|
|
@@ -259,47 +541,172 @@ function RichMarkdownEditor({ markdown, onChange, onSelection }: { markdown: str
|
|
|
259
541
|
syncing.current = true
|
|
260
542
|
editor.setMarkdown(markdown)
|
|
261
543
|
syncing.current = false
|
|
544
|
+
syncAnnotationsRef.current()
|
|
262
545
|
}, [markdown])
|
|
263
|
-
|
|
546
|
+
useEffect(() => {
|
|
547
|
+
syncAnnotationsRef.current()
|
|
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>
|
|
264
573
|
}
|
|
265
574
|
|
|
266
575
|
type Act = (factory: (actor: ParticipantSnapshot) => CollaborationAction) => Promise<boolean>
|
|
267
576
|
const reviewKindLabel: Record<ReviewKind, string> = { 'product-first': '需求缺口检查', 'product-second': '正文整理检查', 'engineering-precheck': '研发可行性检查', 'change-review': '改动影响检查' }
|
|
268
|
-
const
|
|
577
|
+
const reviewTypeLabel: Record<ReviewItemType, string> = { goal: '目标', evidence: '依据', 'history-conflict': '历史冲突', 'current-implementation': '当前实现', scope: '范围', semantics: '规则语义', completeness: '完整性', acceptance: '验收', risk: '风险' }
|
|
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: '一般' }
|
|
269
579
|
const evidenceStatusLabel: Record<string, string> = { FACT: '已有依据', INFERENCE: '根据现有信息推断', ASSUMPTION: '暂定规则', TO_VERIFY: '待核对' }
|
|
580
|
+
const commentResolutionLabel: Record<CommentResolution, string> = { 'written-back': '已回写正文', decision: '形成决策', rejected: '不采纳', 'open-question': '转开放问题' }
|
|
270
581
|
function MarkdownBody({ text, className = '' }: { text: string; className?: string | undefined }) { return <div className={`${css.markdownBody} ${className}`} dangerouslySetInnerHTML={{ __html: md.render(text) }}/> }
|
|
271
|
-
|
|
582
|
+
type ReviewItemView = RequirementView['reviewItems'][number]
|
|
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 }) {
|
|
584
|
+
const [selectedItemId, setSelectedItemId] = useState<string>()
|
|
272
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)
|
|
273
586
|
const historical = requirement.reviewItems.filter(item => item.commit !== requirement.currentCommit)
|
|
274
587
|
const active = current.filter(item => !['resolved', 'invalidated', 'non-blocking-verify'].includes(item.status))
|
|
275
588
|
const deferred = current.filter(item => item.status === 'non-blocking-verify')
|
|
276
|
-
const
|
|
589
|
+
const unansweredCount = active.filter(item => item.status === 'open').length
|
|
590
|
+
const answeredCount = active.filter(item => item.status === 'answered').length
|
|
591
|
+
const processedCount = current.filter(item => item.status !== 'open').length
|
|
277
592
|
const currentRuns = requirement.aiRuns.filter(run => run.commit === requirement.currentCommit)
|
|
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
|
+
}
|
|
599
|
+
useEffect(() => {
|
|
600
|
+
if (!openRequest) return
|
|
601
|
+
if ([...current, ...historical].some(item => item.id === openRequest.objectId)) openItem(openRequest.objectId)
|
|
602
|
+
onOpenRequestHandled?.(openRequest.requestId)
|
|
603
|
+
}, [openRequest?.requestId])
|
|
278
604
|
return <>
|
|
279
|
-
<div className={css.panelSummary}><div><strong>{
|
|
605
|
+
<div className={css.panelSummary}><div><strong>问题检查清单</strong><span>{unansweredCount > 0 ? `${unansweredCount} 项待回答 · ${active.filter(item => item.severity === 'blocking' && item.status === 'open').length} 项阻塞下一阶段` : answeredCount > 0 ? '回答已齐,下一步让 AI 回读' : active.length > 0 ? `${active.length} 项等待后续处理` : '当前版本已全部处理'}</span></div>{current.length > 0 && <div className={css.checklistMeter}><small>{processedCount}/{current.length}</small><progress aria-label={`已回答或处理 ${processedCount} 项,共 ${current.length} 项`} value={processedCount} max={current.length}/></div>}</div>
|
|
280
606
|
{currentRuns.length > 0 && <details className={css.runHistory}><summary>查看本轮 AI 检查记录({currentRuns.length})</summary>{currentRuns.slice().reverse().map(run => <div className={css.run} key={run.id}><div><strong>{reviewKindLabel[run.kind]}</strong><span>{statusLabel[run.status] ?? run.status}</span></div>{run.maturitySummary && <MarkdownBody text={run.maturitySummary}/>} {run.error && <p className={css.chatError}>{friendlyActionError(run.error)}</p>}{run.sessionId && <AiConversation api={api} requirementId={requirement.id} sessionId={run.sessionId}/>}</div>)}</details>}
|
|
281
607
|
{current.length === 0 && <div className={css.emptyPanel}><strong>等待 AI 完成检查</strong><p>检查结果会按优先级出现在这里。</p></div>}
|
|
282
|
-
{active.
|
|
283
|
-
{deferred.length > 0 && <details className={css.historyGroup}><summary>保留待核对 · {deferred.length}</summary><
|
|
284
|
-
{historical.length > 0 && <details className={css.historyGroup}><summary>历史问题 · {historical.length}</summary><
|
|
608
|
+
{active.length > 0 && <ReviewChecklist items={active} selectedItemId={focusedItemId ?? selectedItemId} open={openItem}/>}
|
|
609
|
+
{deferred.length > 0 && <details className={css.historyGroup}><summary>保留待核对 · {deferred.length}</summary><ReviewChecklist items={deferred} selectedItemId={focusedItemId ?? selectedItemId} open={openItem}/></details>}
|
|
610
|
+
{historical.length > 0 && <details className={css.historyGroup}><summary>历史问题 · {historical.length}</summary><ReviewChecklist items={historical.slice().reverse()} selectedItemId={focusedItemId ?? selectedItemId} open={openItem}/></details>}
|
|
285
611
|
</>
|
|
286
612
|
}
|
|
287
|
-
function
|
|
288
|
-
|
|
289
|
-
const content = <div className={css.reviewCardBody}><div className={css.badges}><b>{statusLabel[item.severity] ?? item.severity}</b><span>{evidenceStatusLabel[item.epistemicStatus] ?? item.epistemicStatus}</span></div><div className={`${css.reviewField} ${css.questionField}`}><span>需要明确</span><MarkdownBody text={item.question}/></div><details className={css.impactDetails}><summary>为什么需要回答</summary><MarkdownBody text={item.impact}/></details><details className={css.evidence}><summary>依据与来源 · {item.evidence.length} 条</summary>{item.evidence.length === 0 ? <p>当前没有可核对的资料,可以先按业务判断回答或标记为待核对。</p> : item.evidence.map((evidence, index) => <div key={`${evidence.source}-${index}`}><code>{evidence.source}{evidence.version ? `@${evidence.version}` : ''}</code><MarkdownBody text={evidence.statement}/></div>)}</details>{!item.response && item.status === 'open' && <ReviewResponseForm requirementId={requirementId} reviewItemId={item.id} {...(item.recommendedOptions ? { options: item.recommendedOptions } : {})} act={act}/>} {item.response && <div className={css.humanResponse}><span>已回复</span><strong>{item.response.participant.nickname}</strong><MarkdownBody text={item.response.body}/></div>}</div>
|
|
290
|
-
return <details id={`spec-object-${item.id}`} className={`${css.reviewDetails} ${ended ? css.endedReview : css.pendingReview}`} open={initiallyOpen && !ended}><summary><span>{item.statement}</span><b>{statusLabel[item.status] ?? item.status}</b></summary>{content}</details>
|
|
613
|
+
function ReviewChecklist({ items, selectedItemId, open }: { items: ReviewItemView[]; selectedItemId?: string | undefined; open: (itemId: string) => void }) {
|
|
614
|
+
return <div className={css.reviewChecklist}>{items.map(item => <ReviewChecklistRow key={item.id} item={item} selected={selectedItemId === item.id} open={open}/>)}</div>
|
|
291
615
|
}
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
const
|
|
616
|
+
function ReviewChecklistRow({ item, selected, open }: { item: ReviewItemView; selected: boolean; open: (itemId: string) => void }) {
|
|
617
|
+
const settled = ['resolved', 'invalidated', 'non-blocking-verify'].includes(item.status)
|
|
618
|
+
const answered = item.status !== 'open'
|
|
619
|
+
const question = item.question.trim() || item.statement.trim()
|
|
620
|
+
return <button id={`spec-object-${item.id}`} className={`${css.reviewChecklistRow} ${item.severity === 'blocking' && !answered ? css.reviewChecklistBlocking : ''} ${answered && !settled ? css.reviewChecklistAnswered : ''} ${settled ? css.reviewChecklistSettled : ''} ${selected ? css.reviewChecklistSelected : ''}`} title={question} aria-haspopup="dialog" aria-current={selected ? 'true' : undefined} onClick={() => open(item.id)}>
|
|
621
|
+
<span className={css.reviewCheckBox} aria-hidden="true">{answered ? '✓' : ''}</span>
|
|
622
|
+
<span className={css.reviewCheckCopy}><span className={css.reviewCheckMeta}><b>{reviewTypeLabel[item.type]}</b><small>{item.evidence.length > 0 ? `${item.evidence.length} 条依据` : evidenceStatusLabel[item.epistemicStatus]}</small></span><strong>{question}</strong></span>
|
|
623
|
+
<span className={css.reviewCheckStatus}>{statusLabel[item.status] ?? item.status}</span><span className={css.reviewCheckArrow} aria-hidden="true">›</span>
|
|
624
|
+
</button>
|
|
625
|
+
}
|
|
626
|
+
const dispositionLabel = { context: '补充明确结论', evidence: '补充依据或案例', accept: '直接采用现有结论', 'accept-modified': '采用,并让 AI 修改正文', reject: '不采用,并记录原因', 'to-verify': '暂时无法确认,保留待核对', 'joint-review': '交给产品和研发共同确认' } as const
|
|
627
|
+
const dispositionGuidance: Record<keyof typeof dispositionLabel, string> = {
|
|
628
|
+
context: '保存你的最终判断,AI 回读时会据此检查正文。',
|
|
629
|
+
evidence: '补充数据、案例或来源,并写清它支持什么结论。',
|
|
630
|
+
accept: '现有结论已经准确,不需要 AI 改写正文。',
|
|
631
|
+
'accept-modified': '保存结论后,下一步由 AI 回读并生成正文修改建议。',
|
|
632
|
+
reject: '说明不采用的原因,避免 AI 再次提出同一方向。',
|
|
633
|
+
'to-verify': '这项不会继续阻塞当前阶段,但会保留在待核对清单。',
|
|
634
|
+
'joint-review': '把问题留到产研共审,由产品和研发共同决定。',
|
|
635
|
+
}
|
|
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 }) {
|
|
295
637
|
const [disposition, setDisposition] = useState<keyof typeof dispositionLabel>('context')
|
|
296
638
|
const [body, setBody] = useState('')
|
|
297
|
-
const
|
|
298
|
-
const
|
|
299
|
-
const
|
|
300
|
-
|
|
639
|
+
const formRef = useRef<HTMLFormElement>(null)
|
|
640
|
+
const recommendations = item.recommendedOptions?.map(option => option.trim()).filter(Boolean).slice(0, 5) ?? []
|
|
641
|
+
const sourceSnippets = reviewSourceSnippets(sourceMarkdown, item)
|
|
642
|
+
const primarySource = sourceSnippets[0]
|
|
643
|
+
const canRespond = !item.response && item.status === 'open'
|
|
644
|
+
useEffect(() => {
|
|
645
|
+
const keydown = (event: KeyboardEvent): void => {
|
|
646
|
+
if (event.key === 'Escape') { event.preventDefault(); close(); return }
|
|
647
|
+
}
|
|
648
|
+
window.addEventListener('keydown', keydown)
|
|
649
|
+
window.setTimeout(() => formRef.current?.querySelector<HTMLElement>('textarea')?.focus(), 0)
|
|
650
|
+
return () => window.removeEventListener('keydown', keydown)
|
|
651
|
+
}, [close])
|
|
652
|
+
const choose = (option: string): void => { setBody(option); setDisposition('accept-modified') }
|
|
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) }
|
|
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>}
|
|
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>}
|
|
708
|
+
</div>
|
|
301
709
|
}
|
|
302
|
-
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 }) { return <>{selection && <section className={css.newThread}><blockquote>{selection.quote}</blockquote><label>评论内容(必填)<textarea required value={text} onChange={event => setText(event.target.value)} placeholder="输入实质评论;提交后智能助手自动分析"/></label><div><button onClick={cancel}>取消</button><button disabled={!text.trim()} onClick={() => void submit()}>提交并邀请智能助手</button></div></section>}{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>)}</> }
|
|
303
710
|
function AiConversation({ api, requirementId, sessionId }: { api: SpecApi; requirementId: string; sessionId: string }) {
|
|
304
711
|
const [open, setOpen] = useState(false)
|
|
305
712
|
const [messages, setMessages] = useState<Array<{ role: 'user' | 'assistant'; text: string }>>([])
|
|
@@ -331,9 +738,11 @@ function PatchPanel({ requirement, act }: { requirement: RequirementView; act: A
|
|
|
331
738
|
}
|
|
332
739
|
function DecisionPanel({ requirement, act }: { requirement: RequirementView; act: Act }) {
|
|
333
740
|
const [open, setOpen] = useState(false)
|
|
334
|
-
const [form, setForm] = useState({ question: '', decision: '', rationale: '' })
|
|
335
|
-
const
|
|
336
|
-
|
|
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>}</>
|
|
337
746
|
}
|
|
338
747
|
function VersionPanel({ requirement, api }: { requirement: RequirementView; api: SpecApi }) {
|
|
339
748
|
const [historical, setHistorical] = useState<RequirementVersion>()
|