dsh-spec-collab 0.2.0 → 0.2.1
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/lib/client.js +790 -306
- package/lib/index.js +352 -46
- package/lib/types/client/SpecWorkbench.d.ts +17 -0
- package/lib/types/client/SpecWorkbench.d.ts.map +1 -1
- package/lib/types/client/review-anchors.d.ts +18 -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/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 +5 -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 +223 -33
- package/src/client/review-anchors.ts +87 -0
- package/src/client/workbench.module.css +112 -36
- package/src/client/workflow.ts +7 -7
- package/src/index.ts +21 -3
- package/src/prompts.ts +100 -0
- package/src/protocol.ts +2 -0
- 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 { useCallback, 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, 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
10
|
import { friendlyActionError, workflowState, type TaskView, type WorkflowCommand, type WorkflowState } from './workflow.ts'
|
|
10
11
|
import css from './workbench.module.css'
|
|
11
12
|
|
|
@@ -24,6 +25,8 @@ const markdownShortcutsPlugin = () => ({ wysiwygPlugins: [() => inputRules({ rul
|
|
|
24
25
|
type PrimaryMode = 'tasks' | 'discussion' | 'records'
|
|
25
26
|
type RecordView = 'decisions' | 'versions'
|
|
26
27
|
type CommentAnchor = { quote: string; prefix: string; suffix: string; heading?: string }
|
|
28
|
+
type EditorSelection = CommentAnchor & { rect: { top: number; left: number } }
|
|
29
|
+
type ReviewOpenRequest = { objectId: string; requestId: number }
|
|
27
30
|
function newParticipant(): ParticipantSnapshot { return { participantId: browserUuid(), nickname: '', role: 'product', kind: 'human' } }
|
|
28
31
|
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
32
|
function stageLabel(stage: RequirementStage): string { return ({ 'product-review': '产品审核', 'product-confirmation': '产品确认', 'joint-review': '产研共审', ready: 'Ready' })[stage] }
|
|
@@ -62,6 +65,10 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
62
65
|
const [taskView, setTaskView] = useState<TaskView>('review')
|
|
63
66
|
const [recordView, setRecordView] = useState<RecordView>('decisions')
|
|
64
67
|
const [mobilePane, setMobilePane] = useState<'spec' | 'collab'>('spec')
|
|
68
|
+
const [reviewOpenRequest, setReviewOpenRequest] = useState<ReviewOpenRequest>()
|
|
69
|
+
const reviewOpenRequestId = useRef(0)
|
|
70
|
+
const [focusedReviewId, setFocusedReviewId] = useState<string>()
|
|
71
|
+
const [reviewSourceFocusRequest, setReviewSourceFocusRequest] = useState(0)
|
|
65
72
|
const [draft, setDraft] = useState('')
|
|
66
73
|
const [summary, setSummary] = useState('')
|
|
67
74
|
const [notice, setNotice] = useState('')
|
|
@@ -71,13 +78,14 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
71
78
|
const [myItems, setMyItems] = useState<MyActionItem[]>([])
|
|
72
79
|
const [commentText, setCommentText] = useState('')
|
|
73
80
|
const [selection, setSelection] = useState<CommentAnchor>()
|
|
74
|
-
const [draftSelection, setDraftSelection] = useState<
|
|
81
|
+
const [draftSelection, setDraftSelection] = useState<EditorSelection>()
|
|
75
82
|
const visibleRequirements = requirements.filter(item => Boolean(item.archivedAt) === showArchived)
|
|
76
83
|
const selected = requirements.find(item => item.id === selectedId) ?? visibleRequirements[0]
|
|
77
84
|
const manageTarget = requirements.find(item => item.id === manageTargetId)
|
|
78
85
|
const boundRole = participantBindings.find(item => item.participantId === participant.participantId)?.role
|
|
79
86
|
const currentMyItems = selected ? myItems.filter(item => item.requirementId === selected.id) : []
|
|
80
87
|
const currentReviews = selected?.reviewItems.filter(item => item.commit === selected.currentCommit && !['resolved', 'invalidated', 'non-blocking-verify'].includes(item.status)) ?? []
|
|
88
|
+
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])
|
|
81
89
|
const pendingPatches = selected?.patches.filter(item => item.baseCommit === selected.currentCommit && item.status === 'pending') ?? []
|
|
82
90
|
const openDiscussions = selected?.comments.filter(item => item.commit === selected.currentCommit && item.status === 'open').length ?? 0
|
|
83
91
|
const failedChecks = selected?.readiness.filter(item => !item.passed).length ?? 0
|
|
@@ -86,6 +94,7 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
86
94
|
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
95
|
useEffect(() => { void refresh(); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))); return api.events(() => { void refresh() }) }, [])
|
|
88
96
|
useEffect(() => { if (selected) setDraft(selected.version.markdown) }, [selected?.id, selected?.currentCommit])
|
|
97
|
+
useEffect(() => { setFocusedReviewId(undefined); setDraftSelection(undefined) }, [selected?.id, selected?.currentCommit])
|
|
89
98
|
useEffect(() => { localStorage.setItem('dsh-spec-collab.participant', JSON.stringify(participant)) }, [participant])
|
|
90
99
|
useEffect(() => { localStorage.setItem('dsh-spec-collab.documents-width', String(documentsWidth)) }, [documentsWidth])
|
|
91
100
|
useEffect(() => { localStorage.setItem('dsh-spec-collab.review-width', String(reviewWidth)) }, [reviewWidth])
|
|
@@ -116,9 +125,31 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
116
125
|
const requestReview = async (reviewKind: ReviewKind): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'review.request', participant: actor, requirementId: selected.id, reviewKind })) }
|
|
117
126
|
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
127
|
const advance = async (): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'stage.advance', participant: actor, requirementId: selected.id })) }
|
|
128
|
+
const focusReviewItem = (objectId: string): void => {
|
|
129
|
+
setFocusedReviewId(objectId)
|
|
130
|
+
setReviewSourceFocusRequest(value => value + 1)
|
|
131
|
+
}
|
|
132
|
+
const openReviewItem = (objectId: string, pane: 'spec' | 'collab' = 'collab'): void => {
|
|
133
|
+
setPrimaryMode('tasks')
|
|
134
|
+
setTaskView('review')
|
|
135
|
+
setReviewOpen(true)
|
|
136
|
+
setMobilePane(pane)
|
|
137
|
+
focusReviewItem(objectId)
|
|
138
|
+
setReviewOpenRequest({ objectId, requestId: ++reviewOpenRequestId.current })
|
|
139
|
+
}
|
|
140
|
+
const locateReviewItem = (objectId: string): void => {
|
|
141
|
+
focusReviewItem(objectId)
|
|
142
|
+
setMobilePane('spec')
|
|
143
|
+
}
|
|
119
144
|
const executeWorkflow = async (command: WorkflowCommand): Promise<void> => {
|
|
120
145
|
if (!selected || command.kind === 'none') return
|
|
121
|
-
if (command.kind === 'open') {
|
|
146
|
+
if (command.kind === 'open') {
|
|
147
|
+
setPrimaryMode('tasks')
|
|
148
|
+
setTaskView(command.view)
|
|
149
|
+
setMobilePane('collab')
|
|
150
|
+
if (command.view === 'review' && command.objectId) openReviewItem(command.objectId)
|
|
151
|
+
return
|
|
152
|
+
}
|
|
122
153
|
if (command.kind === 'bind-workspace') { setBindWorkspaceOpen(true); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))); return }
|
|
123
154
|
if (command.kind === 'request-review') { setTaskView('review'); await requestReview(command.reviewKind); return }
|
|
124
155
|
if (command.kind === 'advance') { await advance(); return }
|
|
@@ -127,6 +158,7 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
127
158
|
await act(actor => ({ kind: 'ready.generate', participant: actor, requirementId: selected.id }))
|
|
128
159
|
}
|
|
129
160
|
const openMyItem = (item: MyActionItem): void => {
|
|
161
|
+
if (item.target.tab === 'review') { openReviewItem(item.target.objectId); return }
|
|
130
162
|
if (item.target.tab === 'discussion') setPrimaryMode('discussion')
|
|
131
163
|
else if (item.target.tab === 'decisions') { setPrimaryMode('records'); setRecordView('decisions') }
|
|
132
164
|
else { setPrimaryMode('tasks'); setTaskView(item.target.tab === 'patches' ? 'patches' : item.target.tab === 'ready' ? 'ready' : 'review') }
|
|
@@ -153,9 +185,10 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
153
185
|
setSelection(draftSelection)
|
|
154
186
|
setDraftSelection(undefined)
|
|
155
187
|
setPrimaryMode('discussion')
|
|
188
|
+
setReviewOpen(true)
|
|
156
189
|
setMobilePane('collab')
|
|
157
190
|
}
|
|
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('
|
|
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 正在结合正文和工作区上下文分析') } }
|
|
159
192
|
|
|
160
193
|
return <div className={css.workbench}>
|
|
161
194
|
<header className={css.header}>
|
|
@@ -181,8 +214,8 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
181
214
|
<div className={`${css.resizer} ${documentsOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整需求栏宽度" aria-orientation="vertical" onPointerDown={event => resizePane('documents', event)}/>
|
|
182
215
|
<main className={css.editorPane}>
|
|
183
216
|
<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 && <div className={css.
|
|
185
|
-
{!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> : <div className={css.editorBody}><RichMarkdownEditor key={`${selected.id}:${selected.currentCommit}`} markdown={draft} onChange={setDraft} onSelection={
|
|
217
|
+
{draftSelection && <div className={css.selectionPrompt} role="toolbar" aria-label="选中文字操作" style={{ top: draftSelection.rect.top, left: draftSelection.rect.left }}><span>“{draftSelection.quote.replace(/\s+/g, ' ').slice(0, 42)}{draftSelection.quote.length > 42 ? '…' : ''}”</span><button className={css.commentAction} onClick={captureSelection}>就这段提问</button><button aria-label="取消文字选择" title="取消" onClick={() => setDraftSelection(undefined)}>×</button></div>}
|
|
218
|
+
{!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> : <div className={css.editorBody}><RichMarkdownEditor key={`${selected.id}:${selected.currentCommit}`} markdown={draft} reviewItems={documentReviews} selectedReviewId={focusedReviewId} focusRequest={reviewSourceFocusRequest} onChange={setDraft} onSelection={value => { setDraftSelection(value); if (value) setFocusedReviewId(undefined) }} onOpenReview={openReviewItem}/></div>}
|
|
186
219
|
</main>
|
|
187
220
|
<div className={`${css.resizer} ${reviewOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整协作栏宽度" aria-orientation="vertical" onPointerDown={event => resizePane('review', event)}/>
|
|
188
221
|
<aside className={`${css.review} ${reviewOpen ? '' : css.paneClosed}`} aria-label="需求协作">
|
|
@@ -191,7 +224,7 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
191
224
|
{workflow && <WorkflowFocus state={workflow} pendingForMe={currentMyItems.length} onExecute={() => void executeWorkflow(workflow.command)}/>}
|
|
192
225
|
{currentMyItems.length > 0 && <TaskQueue items={currentMyItems} open={openMyItem}/>}
|
|
193
226
|
<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}
|
|
227
|
+
<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
228
|
</>}
|
|
196
229
|
{selected && primaryMode === 'discussion' && <div className={css.threadList}><DiscussionPanel requirement={selected} selection={selection} text={commentText} setText={setCommentText} cancel={() => setSelection(undefined)} submit={addComment} participant={participant} act={act} api={api}/></div>}
|
|
197
230
|
{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></>}
|
|
@@ -228,21 +261,73 @@ function TaskQueue({ items, open }: { items: MyActionItem[]; open: (item: MyActi
|
|
|
228
261
|
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
262
|
}
|
|
230
263
|
|
|
231
|
-
|
|
264
|
+
type ReviewDocumentMarker = { itemId: string; title: string; top: number; left: number; blocking: boolean }
|
|
265
|
+
function RichMarkdownEditor({ markdown, reviewItems, selectedReviewId, focusRequest, onChange, onSelection, onOpenReview }: { markdown: string; reviewItems: ReviewItemView[]; selectedReviewId?: string | undefined; focusRequest: number; onChange: (markdown: string) => void; onSelection: (selection?: EditorSelection) => void; onOpenReview: (itemId: string) => void }) {
|
|
266
|
+
const shell = useRef<HTMLDivElement>(null)
|
|
232
267
|
const host = useRef<HTMLDivElement>(null)
|
|
233
268
|
const instance = useRef<ToastEditor>()
|
|
234
269
|
const interacted = useRef(false)
|
|
235
270
|
const syncing = useRef(false)
|
|
236
271
|
const onChangeRef = useRef(onChange)
|
|
237
272
|
const onSelectionRef = useRef(onSelection)
|
|
273
|
+
const onOpenReviewRef = useRef(onOpenReview)
|
|
274
|
+
const reviewItemsRef = useRef(reviewItems)
|
|
275
|
+
const selectedReviewIdRef = useRef(selectedReviewId)
|
|
276
|
+
const syncAnnotationsRef = useRef<() => void>(() => {})
|
|
277
|
+
const [markers, setMarkers] = useState<ReviewDocumentMarker[]>([])
|
|
238
278
|
onChangeRef.current = onChange
|
|
239
279
|
onSelectionRef.current = onSelection
|
|
280
|
+
onOpenReviewRef.current = onOpenReview
|
|
281
|
+
reviewItemsRef.current = reviewItems
|
|
282
|
+
selectedReviewIdRef.current = selectedReviewId
|
|
240
283
|
useEffect(() => {
|
|
241
|
-
if (!host.current) return
|
|
284
|
+
if (!host.current || !shell.current) return
|
|
242
285
|
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
286
|
const markInteraction = (): void => { interacted.current = true }
|
|
244
|
-
|
|
245
|
-
const
|
|
287
|
+
let frame = 0
|
|
288
|
+
const syncAnnotations = (): void => {
|
|
289
|
+
const editorRoot = host.current?.querySelector<HTMLElement>('.toastui-editor-contents')
|
|
290
|
+
const shellElement = shell.current
|
|
291
|
+
if (!editorRoot || !shellElement) return
|
|
292
|
+
const selectedSourceClass = css.reviewSourceSelected!
|
|
293
|
+
editorRoot.querySelectorAll<HTMLElement>(`.${selectedSourceClass}`).forEach(element => element.classList.remove(selectedSourceClass))
|
|
294
|
+
const shellRect = shellElement.getBoundingClientRect()
|
|
295
|
+
const slots = new Map<HTMLElement, number>()
|
|
296
|
+
const nextMarkers: ReviewDocumentMarker[] = []
|
|
297
|
+
reviewItemsRef.current.forEach(item => {
|
|
298
|
+
const targets = reviewTargetElements(editorRoot, item)
|
|
299
|
+
if (item.id === selectedReviewIdRef.current) targets.forEach(target => target.classList.add(selectedSourceClass))
|
|
300
|
+
const target = targets[0]
|
|
301
|
+
if (!target) return
|
|
302
|
+
const rect = target.getBoundingClientRect()
|
|
303
|
+
if (rect.bottom < shellRect.top || rect.top > shellRect.bottom) return
|
|
304
|
+
const slot = slots.get(target) ?? 0
|
|
305
|
+
slots.set(target, slot + 1)
|
|
306
|
+
nextMarkers.push({ itemId: item.id, title: item.question.trim() || item.statement.trim(), top: rect.top - shellRect.top + Math.min(8, rect.height / 2) + slot * 25, left: Math.max(4, rect.left - shellRect.left - 30), blocking: item.severity === 'blocking' })
|
|
307
|
+
})
|
|
308
|
+
setMarkers(nextMarkers)
|
|
309
|
+
}
|
|
310
|
+
const scheduleAnnotations = (): void => { cancelAnimationFrame(frame); frame = requestAnimationFrame(syncAnnotations) }
|
|
311
|
+
syncAnnotationsRef.current = scheduleAnnotations
|
|
312
|
+
const change = (): void => { if (interacted.current && !syncing.current) onChangeRef.current(editor.getMarkdown()); scheduleAnnotations() }
|
|
313
|
+
const selection = (): void => {
|
|
314
|
+
const quote = editor.getSelectedText().trim()
|
|
315
|
+
const domSelection = window.getSelection()
|
|
316
|
+
if (!quote || !domSelection || domSelection.rangeCount === 0 || domSelection.isCollapsed) { onSelectionRef.current(undefined); return }
|
|
317
|
+
const range = domSelection.getRangeAt(0)
|
|
318
|
+
const start = range.startContainer instanceof HTMLElement ? range.startContainer : range.startContainer.parentElement
|
|
319
|
+
const block = start?.closest<HTMLElement>(reviewBlockSelector)
|
|
320
|
+
const blockText = block?.textContent ?? quote
|
|
321
|
+
const quoteIndex = blockText.indexOf(quote)
|
|
322
|
+
const headings = Array.from(host.current?.querySelectorAll<HTMLElement>('.toastui-editor-contents h1, .toastui-editor-contents h2, .toastui-editor-contents h3, .toastui-editor-contents h4') ?? [])
|
|
323
|
+
const anchorNode = block ?? start
|
|
324
|
+
const heading = anchorNode ? headings.filter(candidate => Boolean(candidate.compareDocumentPosition(anchorNode) & Node.DOCUMENT_POSITION_FOLLOWING)).at(-1)?.textContent?.trim() : undefined
|
|
325
|
+
const rect = range.getBoundingClientRect()
|
|
326
|
+
const left = Math.min(Math.max(12, rect.left), Math.max(12, window.innerWidth - 390))
|
|
327
|
+
const below = rect.bottom + 9
|
|
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 } })
|
|
330
|
+
}
|
|
246
331
|
editor.on('change', change)
|
|
247
332
|
host.current.addEventListener('beforeinput', markInteraction)
|
|
248
333
|
host.current.addEventListener('paste', markInteraction)
|
|
@@ -250,8 +335,17 @@ function RichMarkdownEditor({ markdown, onChange, onSelection }: { markdown: str
|
|
|
250
335
|
host.current.addEventListener('pointerdown', markInteraction)
|
|
251
336
|
host.current.addEventListener('mouseup', selection)
|
|
252
337
|
host.current.addEventListener('keyup', selection)
|
|
338
|
+
const scrollContainer = host.current.querySelector<HTMLElement>('.toastui-editor-ww-container')
|
|
339
|
+
const scroll = (): void => { onSelectionRef.current(undefined); scheduleAnnotations() }
|
|
340
|
+
scrollContainer?.addEventListener('scroll', scroll, { passive: true })
|
|
341
|
+
window.addEventListener('resize', scheduleAnnotations)
|
|
342
|
+
const resizeObserver = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(scheduleAnnotations)
|
|
343
|
+
resizeObserver?.observe(shell.current)
|
|
344
|
+
const mutationObserver = new MutationObserver(scheduleAnnotations)
|
|
345
|
+
mutationObserver.observe(host.current, { childList: true, subtree: true })
|
|
253
346
|
instance.current = editor
|
|
254
|
-
|
|
347
|
+
scheduleAnnotations()
|
|
348
|
+
return () => { cancelAnimationFrame(frame); mutationObserver.disconnect(); resizeObserver?.disconnect(); window.removeEventListener('resize', scheduleAnnotations); scrollContainer?.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
349
|
}, [])
|
|
256
350
|
useEffect(() => {
|
|
257
351
|
const editor = instance.current
|
|
@@ -259,47 +353,143 @@ function RichMarkdownEditor({ markdown, onChange, onSelection }: { markdown: str
|
|
|
259
353
|
syncing.current = true
|
|
260
354
|
editor.setMarkdown(markdown)
|
|
261
355
|
syncing.current = false
|
|
356
|
+
syncAnnotationsRef.current()
|
|
262
357
|
}, [markdown])
|
|
263
|
-
|
|
358
|
+
useEffect(() => {
|
|
359
|
+
syncAnnotationsRef.current()
|
|
360
|
+
if (!selectedReviewId || focusRequest === 0) return
|
|
361
|
+
const editorRoot = host.current?.querySelector<HTMLElement>('.toastui-editor-contents')
|
|
362
|
+
const item = reviewItems.find(candidate => candidate.id === selectedReviewId)
|
|
363
|
+
const target = editorRoot && item ? reviewTargetElements(editorRoot, item)[0] : undefined
|
|
364
|
+
target?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
|
365
|
+
window.setTimeout(() => syncAnnotationsRef.current(), 220)
|
|
366
|
+
}, [reviewItems, selectedReviewId, focusRequest])
|
|
367
|
+
return <div className={css.richEditorShell} ref={shell}><div className={css.richEditor} ref={host}/><div className={css.reviewAnchorLayer} aria-label="正文问题锚点">{markers.map(marker => <button key={marker.itemId} type="button" className={`${css.documentReviewAnchor} ${marker.blocking ? css.documentReviewAnchorBlocking : ''} ${marker.itemId === selectedReviewId ? css.documentReviewAnchorSelected : ''}`} style={{ top: marker.top, left: marker.left }} title={marker.title} aria-label={`打开问题:${marker.title}`} onMouseDown={event => event.preventDefault()} onClick={() => onOpenReviewRef.current(marker.itemId)}>?</button>)}</div></div>
|
|
264
368
|
}
|
|
265
369
|
|
|
266
370
|
type Act = (factory: (actor: ParticipantSnapshot) => CollaborationAction) => Promise<boolean>
|
|
267
371
|
const reviewKindLabel: Record<ReviewKind, string> = { 'product-first': '需求缺口检查', 'product-second': '正文整理检查', 'engineering-precheck': '研发可行性检查', 'change-review': '改动影响检查' }
|
|
268
|
-
const
|
|
372
|
+
const reviewTypeLabel: Record<ReviewItemType, string> = { goal: '目标', evidence: '依据', 'history-conflict': '历史冲突', 'current-implementation': '当前实现', scope: '范围', semantics: '规则语义', completeness: '完整性', acceptance: '验收', risk: '风险' }
|
|
373
|
+
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
374
|
const evidenceStatusLabel: Record<string, string> = { FACT: '已有依据', INFERENCE: '根据现有信息推断', ASSUMPTION: '暂定规则', TO_VERIFY: '待核对' }
|
|
270
375
|
function MarkdownBody({ text, className = '' }: { text: string; className?: string | undefined }) { return <div className={`${css.markdownBody} ${className}`} dangerouslySetInnerHTML={{ __html: md.render(text) }}/> }
|
|
271
|
-
|
|
376
|
+
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 }) {
|
|
378
|
+
const [selectedItemId, setSelectedItemId] = useState<string>()
|
|
379
|
+
const closeSelectedItem = useCallback(() => setSelectedItemId(undefined), [])
|
|
272
380
|
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
381
|
const historical = requirement.reviewItems.filter(item => item.commit !== requirement.currentCommit)
|
|
274
382
|
const active = current.filter(item => !['resolved', 'invalidated', 'non-blocking-verify'].includes(item.status))
|
|
275
383
|
const deferred = current.filter(item => item.status === 'non-blocking-verify')
|
|
276
|
-
const
|
|
384
|
+
const unansweredCount = active.filter(item => item.status === 'open').length
|
|
385
|
+
const answeredCount = active.filter(item => item.status === 'answered').length
|
|
386
|
+
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)
|
|
277
389
|
const currentRuns = requirement.aiRuns.filter(run => run.commit === requirement.currentCommit)
|
|
390
|
+
const openItem = (itemId: string): void => { setSelectedItemId(itemId); onSelectReview?.(itemId) }
|
|
391
|
+
useEffect(() => {
|
|
392
|
+
if (!openRequest) return
|
|
393
|
+
if ([...current, ...historical].some(item => item.id === openRequest.objectId)) openItem(openRequest.objectId)
|
|
394
|
+
onOpenRequestHandled?.(openRequest.requestId)
|
|
395
|
+
}, [openRequest?.requestId])
|
|
278
396
|
return <>
|
|
279
|
-
<div className={css.panelSummary}><div><strong>{
|
|
397
|
+
<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
398
|
{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
399
|
{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><
|
|
400
|
+
{active.length > 0 && <ReviewChecklist items={active} selectedItemId={focusedItemId ?? selectedItemId} open={openItem}/>}
|
|
401
|
+
{deferred.length > 0 && <details className={css.historyGroup}><summary>保留待核对 · {deferred.length}</summary><ReviewChecklist items={deferred} selectedItemId={focusedItemId ?? selectedItemId} open={openItem}/></details>}
|
|
402
|
+
{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() }}/>}
|
|
285
404
|
</>
|
|
286
405
|
}
|
|
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>
|
|
406
|
+
function ReviewChecklist({ items, selectedItemId, open }: { items: ReviewItemView[]; selectedItemId?: string | undefined; open: (itemId: string) => void }) {
|
|
407
|
+
return <div className={css.reviewChecklist}>{items.map(item => <ReviewChecklistRow key={item.id} item={item} selected={selectedItemId === item.id} open={open}/>)}</div>
|
|
291
408
|
}
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
const
|
|
409
|
+
function ReviewChecklistRow({ item, selected, open }: { item: ReviewItemView; selected: boolean; open: (itemId: string) => void }) {
|
|
410
|
+
const settled = ['resolved', 'invalidated', 'non-blocking-verify'].includes(item.status)
|
|
411
|
+
const answered = item.status !== 'open'
|
|
412
|
+
const question = item.question.trim() || item.statement.trim()
|
|
413
|
+
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)}>
|
|
414
|
+
<span className={css.reviewCheckBox} aria-hidden="true">{answered ? '✓' : ''}</span>
|
|
415
|
+
<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>
|
|
416
|
+
<span className={css.reviewCheckStatus}>{statusLabel[item.status] ?? item.status}</span><span className={css.reviewCheckArrow} aria-hidden="true">›</span>
|
|
417
|
+
</button>
|
|
418
|
+
}
|
|
419
|
+
const dispositionLabel = { context: '补充明确结论', evidence: '补充依据或案例', accept: '直接采用现有结论', 'accept-modified': '采用,并让 AI 修改正文', reject: '不采用,并记录原因', 'to-verify': '暂时无法确认,保留待核对', 'joint-review': '交给产品和研发共同确认' } as const
|
|
420
|
+
const dispositionGuidance: Record<keyof typeof dispositionLabel, string> = {
|
|
421
|
+
context: '保存你的最终判断,AI 回读时会据此检查正文。',
|
|
422
|
+
evidence: '补充数据、案例或来源,并写清它支持什么结论。',
|
|
423
|
+
accept: '现有结论已经准确,不需要 AI 改写正文。',
|
|
424
|
+
'accept-modified': '保存结论后,下一步由 AI 回读并生成正文修改建议。',
|
|
425
|
+
reject: '说明不采用的原因,避免 AI 再次提出同一方向。',
|
|
426
|
+
'to-verify': '这项不会继续阻塞当前阶段,但会保留在待核对清单。',
|
|
427
|
+
'joint-review': '把问题留到产研共审,由产品和研发共同决定。',
|
|
428
|
+
}
|
|
429
|
+
function ReviewDecisionDialog({ item, sourceMarkdown, requirementId, nextItemId, act, close, locateSource, complete }: { item: ReviewItemView; sourceMarkdown: string; requirementId: string; nextItemId?: string | undefined; act: Act; close: () => void; locateSource: () => void; complete: (continueToNext: boolean) => void }) {
|
|
295
430
|
const [disposition, setDisposition] = useState<keyof typeof dispositionLabel>('context')
|
|
296
431
|
const [body, setBody] = useState('')
|
|
297
|
-
const
|
|
298
|
-
const
|
|
299
|
-
const
|
|
300
|
-
|
|
432
|
+
const dialogRef = useRef<HTMLElement>(null)
|
|
433
|
+
const returnFocusRef = useRef<HTMLElement | null>(typeof document !== 'undefined' && document.activeElement instanceof HTMLElement ? document.activeElement : null)
|
|
434
|
+
const recommendations = item.recommendedOptions?.map(option => option.trim()).filter(Boolean).slice(0, 5) ?? []
|
|
435
|
+
const sourceSnippets = reviewSourceSnippets(sourceMarkdown, item)
|
|
436
|
+
const canRespond = !item.response && item.status === 'open'
|
|
437
|
+
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
|
+
const keydown = (event: KeyboardEvent): void => {
|
|
443
|
+
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
|
+
}
|
|
452
|
+
window.addEventListener('keydown', keydown)
|
|
453
|
+
return () => { window.removeEventListener('keydown', keydown); returnFocusRef.current?.focus() }
|
|
454
|
+
}, [close])
|
|
455
|
+
const choose = (option: string): void => { setBody(option); setDisposition('accept-modified') }
|
|
456
|
+
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 <div className={`${css.modal} ${css.reviewDecisionModal}`} onMouseDown={event => { if (event.currentTarget === event.target) close() }}>
|
|
459
|
+
<section ref={dialogRef} className={css.reviewDecisionDialog} role="dialog" aria-modal="true" aria-labelledby={`review-dialog-${item.id}`}>
|
|
460
|
+
<header className={css.reviewDecisionHeader}><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><h2 id={`review-dialog-${item.id}`}>{item.statement}</h2></div><button aria-label="关闭问题窗口" title="关闭" onClick={close}>×</button></header>
|
|
461
|
+
<div className={css.reviewDecisionBody}>
|
|
462
|
+
<main className={css.reviewDecisionContext}>
|
|
463
|
+
<section className={css.decisionQuestion}><span>待澄清问题</span><MarkdownBody text={item.question}/></section>
|
|
464
|
+
{sourceSnippets.length > 0 && <section className={css.decisionSection}><div className={css.decisionSectionHead}><h3>关联正文</h3><button onClick={locateSource}>在正文中查看</button></div><div className={css.decisionSourceList}>{sourceSnippets.map(snippet => <div className={css.decisionSource} key={snippet.key}><span>{snippet.label}{snippet.line ? ` · 第 ${snippet.line} 行` : ''}</span><MarkdownBody text={snippet.markdown}/></div>)}</div></section>}
|
|
465
|
+
<section className={css.decisionSection}><h3>为什么需要明确</h3><MarkdownBody text={item.impact}/></section>
|
|
466
|
+
<section className={css.decisionSection}><div className={css.decisionSectionHead}><h3>依据与来源</h3><span>{item.evidence.length} 条</span></div>{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>
|
|
467
|
+
{(item.affectedSections.length > 0 || item.affectedAcceptanceIds.length > 0) && <section className={css.decisionSection}><h3>可能影响</h3><p>{[...item.affectedSections, ...item.affectedAcceptanceIds].join(' · ')}</p></section>}
|
|
468
|
+
</main>
|
|
469
|
+
<aside className={css.reviewDecisionAside} aria-label="处理这个问题">
|
|
470
|
+
{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 ? <>
|
|
471
|
+
<div className={css.decisionAsideHead}><span>你的回答</span><strong>先选处理结果,再写下最终结论</strong></div>
|
|
472
|
+
{recommendations.length > 0 && <fieldset className={css.decisionOptions}><legend>可直接采用的回答</legend>{recommendations.map((option, index) => <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>}
|
|
473
|
+
<div className={css.decisionForm}><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 autoFocus value={body} onChange={event => setBody(event.target.value)} placeholder={disposition === 'evidence' ? '粘贴数据、案例或来源链接,并说明它支持什么结论' : disposition === 'joint-review' ? '可选:补充希望产品和研发重点讨论的边界' : '写清最终判断、适用范围、例外情况和取舍理由'}/></label></div>
|
|
474
|
+
<div className={css.decisionActions}><button onClick={close}>取消</button><div>{nextItemId && <button disabled={!canSubmit} onClick={() => void submit(false)}>保存并返回清单</button>}<button className={css.execute} disabled={!canSubmit} onClick={() => void submit(Boolean(nextItemId))}>{nextItemId ? '保存并回答下一题' : '保存最后一项回答'}</button></div></div>
|
|
475
|
+
</> : <div className={css.decisionResponse}><span>{statusLabel[item.status] ?? item.status}</span><strong>这条记录当前不可回复</strong><p>你仍可以查看完整问题、影响和来源。</p></div>}
|
|
476
|
+
</aside>
|
|
477
|
+
</div>
|
|
478
|
+
</section>
|
|
479
|
+
</div>
|
|
480
|
+
}
|
|
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
|
+
</>
|
|
301
492
|
}
|
|
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
493
|
function AiConversation({ api, requirementId, sessionId }: { api: SpecApi; requirementId: string; sessionId: string }) {
|
|
304
494
|
const [open, setOpen] = useState(false)
|
|
305
495
|
const [messages, setMessages] = useState<Array<{ role: 'user' | 'assistant'; text: string }>>([])
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import MarkdownIt from 'markdown-it'
|
|
2
|
+
import type { ReviewItem } from '../protocol.ts'
|
|
3
|
+
|
|
4
|
+
const parser = new MarkdownIt({ html: false })
|
|
5
|
+
export const reviewBlockSelector = 'h1, h2, h3, h4, p, li, td, th, blockquote'
|
|
6
|
+
|
|
7
|
+
export interface ReviewSourceSnippet {
|
|
8
|
+
key: string
|
|
9
|
+
label: string
|
|
10
|
+
markdown: string
|
|
11
|
+
line?: number
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface ReviewAnchorTerm {
|
|
15
|
+
kind: 'quote' | 'acceptance' | 'section'
|
|
16
|
+
label: string
|
|
17
|
+
value: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function normalizeReviewText(value: string): string {
|
|
21
|
+
return value.replace(/[`*_>#\[\]()~-]/g, '').replace(/\s+/g, '').toLocaleLowerCase()
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function reviewAnchorTerms(item: ReviewItem): ReviewAnchorTerm[] {
|
|
25
|
+
const terms: ReviewAnchorTerm[] = []
|
|
26
|
+
for (const anchor of item.sourceAnchors ?? []) {
|
|
27
|
+
if (anchor.quote.trim()) terms.push({ kind: 'quote', label: anchor.heading?.trim() || '正文引用', value: anchor.quote.trim() })
|
|
28
|
+
}
|
|
29
|
+
for (const id of item.affectedAcceptanceIds) if (id.trim()) terms.push({ kind: 'acceptance', label: id.trim(), value: id.trim() })
|
|
30
|
+
for (const section of item.affectedSections) if (section.trim()) terms.push({ kind: 'section', label: section.trim(), value: section.trim() })
|
|
31
|
+
return terms
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function reviewTargetElements(root: HTMLElement, item: ReviewItem): HTMLElement[] {
|
|
35
|
+
const blocks = Array.from(root.querySelectorAll<HTMLElement>(reviewBlockSelector))
|
|
36
|
+
const targets: HTMLElement[] = []
|
|
37
|
+
for (const term of reviewAnchorTerms(item)) {
|
|
38
|
+
const candidates = (term.kind === 'section' ? blocks.filter(block => /^H[1-4]$/.test(block.tagName)) : blocks)
|
|
39
|
+
.filter(block => normalizeReviewText(block.textContent ?? '').includes(normalizeReviewText(term.value)))
|
|
40
|
+
.sort((left, right) => (left.textContent?.length ?? 0) - (right.textContent?.length ?? 0))
|
|
41
|
+
const target = candidates[0]
|
|
42
|
+
if (target && !targets.includes(target)) targets.push(target)
|
|
43
|
+
}
|
|
44
|
+
return targets
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function reviewSourceSnippets(markdown: string, item: ReviewItem): ReviewSourceSnippet[] {
|
|
48
|
+
const lines = markdown.split('\n')
|
|
49
|
+
const tokens = parser.parse(markdown, {})
|
|
50
|
+
const snippets: ReviewSourceSnippet[] = []
|
|
51
|
+
const seen = new Set<string>()
|
|
52
|
+
const add = (snippet: ReviewSourceSnippet): void => {
|
|
53
|
+
const key = normalizeReviewText(snippet.markdown)
|
|
54
|
+
if (!key || seen.has(key) || snippets.length >= 4) return
|
|
55
|
+
seen.add(key)
|
|
56
|
+
snippets.push(snippet)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
for (const [index, anchor] of (item.sourceAnchors ?? []).entries()) {
|
|
60
|
+
const quote = anchor.quote.trim()
|
|
61
|
+
if (!quote || !normalizeReviewText(markdown).includes(normalizeReviewText(quote))) continue
|
|
62
|
+
const exactLine = lines.findIndex(line => normalizeReviewText(line).includes(normalizeReviewText(quote)))
|
|
63
|
+
add({ key: `quote-${index}`, label: anchor.heading?.trim() || '正文引用', markdown: quote, ...(exactLine < 0 ? {} : { line: exactLine + 1 }) })
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
for (const acceptanceId of item.affectedAcceptanceIds) {
|
|
67
|
+
const token = tokens.find(candidate => candidate.type === 'inline' && candidate.map && normalizeReviewText(candidate.content).includes(normalizeReviewText(acceptanceId)))
|
|
68
|
+
if (!token?.map) continue
|
|
69
|
+
const [start, end] = token.map
|
|
70
|
+
add({ key: `acceptance-${acceptanceId}`, label: acceptanceId, markdown: lines.slice(start, end).join('\n').trim(), line: start + 1 })
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (snippets.length === 0) {
|
|
74
|
+
for (const section of item.affectedSections) {
|
|
75
|
+
const headingIndex = tokens.findIndex((token, index) => token.type === 'heading_open' && tokens[index + 1]?.type === 'inline' && normalizeReviewText(tokens[index + 1]!.content).includes(normalizeReviewText(section)))
|
|
76
|
+
const heading = tokens[headingIndex]
|
|
77
|
+
if (headingIndex < 0 || !heading?.map) continue
|
|
78
|
+
const level = Number(heading.tag.slice(1))
|
|
79
|
+
const nextHeading = tokens.slice(headingIndex + 1).find(token => token.type === 'heading_open' && Number(token.tag.slice(1)) <= level && token.map)
|
|
80
|
+
const start = heading.map[0]
|
|
81
|
+
const end = Math.min(nextHeading?.map?.[0] ?? lines.length, start + 9)
|
|
82
|
+
add({ key: `section-${section}`, label: section, markdown: lines.slice(start, end).join('\n').trim(), line: start + 1 })
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return snippets
|
|
87
|
+
}
|