dsh-spec-collab 0.2.2 → 0.3.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/CHANGELOG.md +11 -0
- package/README.md +84 -18
- package/docs/assets/demo-01-workspace.png +0 -0
- package/docs/assets/demo-02-ai-review.png +0 -0
- package/docs/assets/demo-03-patches.png +0 -0
- package/docs/assets/demo-04-decisions.png +0 -0
- package/docs/assets/demo-05-ready.png +0 -0
- package/docs/experience-review-checklist-2026-08-24.md +72 -45
- package/docs/insight-import-template.csv +3 -0
- package/docs/insight-import-template.md +19 -0
- package/docs/migration-v3.md +23 -0
- package/docs/usage-walkthrough.md +25 -43
- package/lib/client.js +10854 -1168
- package/lib/index.js +1313 -98
- package/lib/types/client/AccessibleDialog.d.ts +9 -0
- package/lib/types/client/AccessibleDialog.d.ts.map +1 -0
- package/lib/types/client/SpecWorkbench.d.ts +42 -2
- package/lib/types/client/SpecWorkbench.d.ts.map +1 -1
- package/lib/types/client/api.d.ts +26 -3
- package/lib/types/client/api.d.ts.map +1 -1
- package/lib/types/client/drafts.d.ts +8 -0
- package/lib/types/client/drafts.d.ts.map +1 -0
- package/lib/types/client/mount.d.ts.map +1 -1
- package/lib/types/client/review-anchors.d.ts.map +1 -1
- package/lib/types/client/workflow.d.ts.map +1 -1
- package/lib/types/engine.d.ts +37 -3
- package/lib/types/engine.d.ts.map +1 -1
- package/lib/types/git-store.d.ts +6 -0
- package/lib/types/git-store.d.ts.map +1 -1
- package/lib/types/protocol.d.ts +245 -10
- package/lib/types/protocol.d.ts.map +1 -1
- package/lib/types/ready-admission.d.ts +14 -0
- package/lib/types/ready-admission.d.ts.map +1 -0
- package/lib/types/review-runtime.d.ts +6 -0
- package/lib/types/review-runtime.d.ts.map +1 -1
- package/lib/types/routes.d.ts.map +1 -1
- package/lib/types/structured-diff.d.ts +3 -0
- package/lib/types/structured-diff.d.ts.map +1 -0
- package/package.json +14 -4
- package/src/client/AccessibleDialog.tsx +42 -0
- package/src/client/SpecWorkbench.tsx +776 -87
- package/src/client/api.ts +8 -3
- package/src/client/drafts.ts +51 -0
- package/src/client/mount.tsx +11 -6
- package/src/client/review-anchors.ts +1 -0
- package/src/client/workbench.module.css +223 -79
- package/src/client/workflow.ts +8 -9
- package/src/engine.ts +448 -46
- package/src/git-store.ts +87 -18
- package/src/index.ts +1 -1
- package/src/protocol.ts +64 -13
- package/src/ready-admission.ts +29 -0
- package/src/review-runtime.ts +39 -11
- package/src/routes.ts +33 -4
- package/src/structured-diff.ts +75 -0
- package/src/tools.ts +1 -1
- package/docs/assets/spec-collab-walkthrough.mp4 +0 -0
|
@@ -1,16 +1,18 @@
|
|
|
1
|
-
import { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from 'react'
|
|
1
|
+
import { useEffect, useMemo, useRef, useState, type CSSProperties, type FormEvent, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode } 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, CommentThread, MyActionItem, ParticipantRole, ParticipantSnapshot, RequirementStage,
|
|
6
|
+
import type { CollaborationAction, CommentResolution, CommentThread, MyActionItem, Notification, ParticipantRole, ParticipantSnapshot, RequirementStage, RequirementSummary, RequirementView, ReviewItemType, ReviewKind, ReviewWorkspaceSummary, SaveConflict, StructuredDiff } from '../protocol.ts'
|
|
7
7
|
import type { SpecApi } from './api.ts'
|
|
8
8
|
import { browserUuid } from './browser-uuid.ts'
|
|
9
9
|
import { commentTargetElements, reviewBlockSelector, reviewSourceSnippets, reviewTargetElements } from './review-anchors.ts'
|
|
10
10
|
import { friendlyActionError, workflowState, type TaskView, type WorkflowCommand, type WorkflowState } from './workflow.ts'
|
|
11
|
+
import { AccessibleDialog } from './AccessibleDialog.tsx'
|
|
12
|
+
import { deleteDraft, loadDraft, safeHttpUrl, saveDraft, truncateGraphemes } from './drafts.ts'
|
|
11
13
|
import css from './workbench.module.css'
|
|
12
14
|
|
|
13
|
-
const md = new MarkdownIt({ html: false, linkify:
|
|
15
|
+
const md = new MarkdownIt({ html: false, linkify: false })
|
|
14
16
|
const inlineStyleRule = (pattern: RegExp, markName: 'strong' | 'emph' | 'code'): InputRule => new InputRule(pattern, (state, match, start, end) => {
|
|
15
17
|
const text = match[1]
|
|
16
18
|
const mark = state.schema.marks[markName]
|
|
@@ -22,20 +24,49 @@ const markdownShortcutsPlugin = () => ({ wysiwygPlugins: [() => inputRules({ rul
|
|
|
22
24
|
new InputRule(/^```\s$/, (state, _match, start, end) => state.tr.delete(start, end).setBlockType(start, start, state.schema.nodes.codeBlock!)),
|
|
23
25
|
inlineStyleRule(/\*\*([^*]+)\*\*$/, 'strong'), inlineStyleRule(/(?<!\*)\*([^*]+)\*$/, 'emph'), inlineStyleRule(/`([^`]+)`$/, 'code'),
|
|
24
26
|
] })] })
|
|
25
|
-
type PrimaryMode = 'tasks' | 'discussion' | 'records'
|
|
27
|
+
type PrimaryMode = 'tasks' | 'discussion' | 'insights' | 'records'
|
|
26
28
|
type RecordView = 'decisions' | 'versions'
|
|
29
|
+
type DeepLinkTarget = { primaryMode: PrimaryMode; taskView?: TaskView; recordView?: RecordView; focusObjectId?: string; reviewObjectId?: string; commentObjectId?: string; error?: string }
|
|
30
|
+
export function resolveDeepLinkTarget(requirement: RequirementView, view: string, objectId?: string): DeepLinkTarget {
|
|
31
|
+
if (view === 'discussion') return objectId && !requirement.comments.some(item => item.id === objectId) ? { primaryMode: 'discussion', error: '链接指向的评论不存在或已失效' } : { primaryMode: 'discussion', ...(objectId ? { focusObjectId: objectId, commentObjectId: objectId } : {}) }
|
|
32
|
+
if (view === 'insights') return { primaryMode: 'insights', ...(objectId ? { focusObjectId: objectId } : {}) }
|
|
33
|
+
if (view === 'records') {
|
|
34
|
+
if (!objectId) return { primaryMode: 'records' }
|
|
35
|
+
if (requirement.decisions.some(item => item.id === objectId)) return { primaryMode: 'records', recordView: 'decisions', focusObjectId: objectId }
|
|
36
|
+
if (requirement.history.some(item => item.commit === objectId)) return { primaryMode: 'records', recordView: 'versions', focusObjectId: objectId }
|
|
37
|
+
return { primaryMode: 'records', error: '链接指向的决策或版本不存在' }
|
|
38
|
+
}
|
|
39
|
+
if (view !== 'tasks') return { primaryMode: 'tasks', error: '链接指向的协作视图不存在' }
|
|
40
|
+
if (!objectId) return { primaryMode: 'tasks' }
|
|
41
|
+
if (objectId === requirement.id && requirement.stage === 'ready') return { primaryMode: 'tasks', taskView: 'ready' }
|
|
42
|
+
const action = requirement.actionItems.find(item => item.id === objectId)
|
|
43
|
+
const sourceType = action?.sourceType
|
|
44
|
+
const sourceId = action?.sourceId ?? objectId
|
|
45
|
+
if (sourceType === 'comment' || requirement.comments.some(item => item.id === sourceId)) return { primaryMode: 'discussion', focusObjectId: sourceId, commentObjectId: sourceId }
|
|
46
|
+
if (sourceType === 'patch' || requirement.patches.some(item => item.id === sourceId)) return { primaryMode: 'tasks', taskView: 'patches', focusObjectId: sourceId }
|
|
47
|
+
if (sourceType === 'decision' || requirement.decisions.some(item => item.id === sourceId)) return { primaryMode: 'records', recordView: 'decisions', focusObjectId: sourceId }
|
|
48
|
+
if (sourceType === 'review-item' || requirement.reviewItems.some(item => item.id === sourceId)) return { primaryMode: 'tasks', taskView: 'review', focusObjectId: sourceId, reviewObjectId: sourceId }
|
|
49
|
+
return { primaryMode: 'tasks', error: '链接指向的待办对象不存在或已失效' }
|
|
50
|
+
}
|
|
27
51
|
export type CommentAnchor = { quote: string; prefix: string; suffix: string; heading?: string }
|
|
28
52
|
export type InlinePopoverPosition = { rect: { top: number; left: number }; placement: 'above' | 'below'; maxHeight?: number }
|
|
29
53
|
export type EditorSelection = CommentAnchor & InlinePopoverPosition
|
|
30
54
|
type ReviewOpenRequest = { objectId: string; requestId: number }
|
|
31
55
|
type InlineReviewTarget = { itemId: string; sourceKey?: string } & Partial<InlinePopoverPosition>
|
|
32
56
|
type DocumentAnchorFocus = { kind: 'review'; objectId: string; sourceKey?: string } | { kind: 'comment'; objectId: string }
|
|
33
|
-
|
|
57
|
+
type PendingNavigation = { kind: 'select'; requirementId: string } | { kind: 'close' } | { kind: 'toggle-archive' } | { kind: 'deep-link'; hash: string } | { kind: 'archive'; requirementId: string; archived: boolean }
|
|
58
|
+
const inlineReviewPopoverSize = { width: 720, height: 760 } as const
|
|
34
59
|
function inlinePopoverPositionFromRect(rect: Pick<DOMRect, 'top' | 'bottom' | 'left'>, size: { width: number; height: number }): InlinePopoverPosition {
|
|
35
60
|
const padding = 12
|
|
36
61
|
const gap = 10
|
|
37
62
|
const viewportMaxHeight = Math.max(160, window.innerHeight - padding * 2)
|
|
38
63
|
const desiredHeight = Math.min(size.height, viewportMaxHeight)
|
|
64
|
+
const left = Math.min(Math.max(padding, rect.left), Math.max(padding, window.innerWidth - size.width - padding))
|
|
65
|
+
if (size.height >= 600) {
|
|
66
|
+
const placement: InlinePopoverPosition['placement'] = rect.top > window.innerHeight / 2 ? 'above' : 'below'
|
|
67
|
+
const top = Math.max(padding, (window.innerHeight - desiredHeight) / 2)
|
|
68
|
+
return { rect: { top, left }, placement, maxHeight: desiredHeight }
|
|
69
|
+
}
|
|
39
70
|
const spaceBelow = Math.max(0, window.innerHeight - rect.bottom - gap - padding)
|
|
40
71
|
const spaceAbove = Math.max(0, rect.top - gap - padding)
|
|
41
72
|
const usefulBelowHeight = Math.min(desiredHeight, size.height > 360 ? 280 : 180)
|
|
@@ -44,7 +75,6 @@ function inlinePopoverPositionFromRect(rect: Pick<DOMRect, 'top' | 'bottom' | 'l
|
|
|
44
75
|
const maxHeight = Math.max(160, Math.min(desiredHeight, available || viewportMaxHeight))
|
|
45
76
|
const rawTop = placement === 'below' ? rect.bottom + gap : rect.top - maxHeight - gap
|
|
46
77
|
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
78
|
return { rect: { top, left }, placement, maxHeight }
|
|
49
79
|
}
|
|
50
80
|
function visibleEditorContents(root: HTMLElement | null | undefined): HTMLElement | undefined {
|
|
@@ -68,19 +98,28 @@ export function annotationScrollTargets(root: HTMLElement | null | undefined): H
|
|
|
68
98
|
}
|
|
69
99
|
function newParticipant(): ParticipantSnapshot { return { participantId: browserUuid(), nickname: '', role: 'product', kind: 'human' } }
|
|
70
100
|
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() }
|
|
71
|
-
function stageLabel(stage: RequirementStage): string { return ({ 'product-review': '
|
|
72
|
-
function
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
])
|
|
80
|
-
|
|
101
|
+
function stageLabel(stage: RequirementStage): string { return ({ 'product-review': '澄清', 'product-confirmation': '产品确认', 'joint-review': '产研确认', ready: '已就绪' })[stage] }
|
|
102
|
+
function relativeTime(timestamp: number): string { const seconds = Math.max(0, Math.floor((Date.now() - timestamp) / 1000)); if (seconds < 60) return '刚刚'; const minutes = Math.floor(seconds / 60); if (minutes < 60) return `${minutes} 分钟前`; const hours = Math.floor(minutes / 60); if (hours < 24) return `${hours} 小时前`; return `${Math.floor(hours / 24)} 天前` }
|
|
103
|
+
function durationText(milliseconds: number): string { const seconds = Math.max(0, Math.round(milliseconds / 1000)); return seconds < 60 ? `${seconds} 秒` : `${Math.floor(seconds / 60)} 分 ${seconds % 60} 秒` }
|
|
104
|
+
function cleanDisplayText(value: string, max = 84): string { return truncateGraphemes(value.replace(/\uFFFD+/g, ''), max) }
|
|
105
|
+
function downloadText(name: string, text: string): void { const url = URL.createObjectURL(new Blob([text], { type: 'text/markdown;charset=utf-8' })); const anchor = document.createElement('a'); anchor.href = url; anchor.download = name; anchor.click(); URL.revokeObjectURL(url) }
|
|
106
|
+
function handleTabs<T extends string>(event: ReactKeyboardEvent<HTMLElement>, values: readonly T[], current: T, setCurrent: (value: T) => void): void {
|
|
107
|
+
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return
|
|
108
|
+
event.preventDefault(); const index = Math.max(0, values.indexOf(current)); const next = event.key === 'Home' ? 0 : event.key === 'End' ? values.length - 1 : event.key === 'ArrowRight' ? (index + 1) % values.length : (index - 1 + values.length) % values.length
|
|
109
|
+
setCurrent(values[next]!); window.setTimeout(() => (event.currentTarget.querySelectorAll<HTMLElement>('[role="tab"]')[next])?.focus(), 0)
|
|
110
|
+
}
|
|
111
|
+
function requirementParticipantIds(requirement: RequirementSummary): Set<string> { return new Set(requirement.participantIds) }
|
|
112
|
+
export function mentionedParticipantIds(body: string, participants: ParticipantSnapshot[]): string[] {
|
|
113
|
+
return participants.filter(participant => {
|
|
114
|
+
const token = `@${participant.nickname}`; let index = body.indexOf(token)
|
|
115
|
+
while (index >= 0) { const next = body[index + token.length]; if (next === undefined || /[\s,,。!?;;、::))\]}]/u.test(next)) return true; index = body.indexOf(token, index + token.length) }
|
|
116
|
+
return false
|
|
117
|
+
}).map(item => item.participantId)
|
|
81
118
|
}
|
|
82
119
|
export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => void }) {
|
|
83
|
-
const
|
|
120
|
+
const workbenchRef = useRef<HTMLDivElement>(null)
|
|
121
|
+
const [requirements, setRequirements] = useState<RequirementSummary[]>([])
|
|
122
|
+
const [selectedRequirement, setSelectedRequirement] = useState<RequirementView>()
|
|
84
123
|
const [reviewWorkspaces, setReviewWorkspaces] = useState<ReviewWorkspaceSummary[]>([])
|
|
85
124
|
const [participantBindings, setParticipantBindings] = useState<ParticipantSnapshot[]>([])
|
|
86
125
|
const [selectedId, setSelectedId] = useState<string>()
|
|
@@ -97,15 +136,23 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
97
136
|
const [renameTitle, setRenameTitle] = useState('')
|
|
98
137
|
const [documentsOpen, setDocumentsOpen] = useState(true)
|
|
99
138
|
const [reviewOpen, setReviewOpen] = useState(true)
|
|
139
|
+
const [focusMode, setFocusMode] = useState(false)
|
|
140
|
+
const previousPaneState = useRef({ documents: true, review: true })
|
|
141
|
+
const [documentDrawerOpen, setDocumentDrawerOpen] = useState(false)
|
|
100
142
|
const [documentsWidth, setDocumentsWidth] = useState(() => Number(localStorage.getItem('dsh-spec-collab.documents-width')) || 220)
|
|
101
143
|
const [reviewWidth, setReviewWidth] = useState(() => Number(localStorage.getItem('dsh-spec-collab.review-width')) || 430)
|
|
102
144
|
const [createForm, setCreateForm] = useState({ title: '', rawRequirement: '', sources: '', workspaceId: '' })
|
|
103
145
|
const [primaryMode, setPrimaryMode] = useState<PrimaryMode>('tasks')
|
|
104
146
|
const [taskView, setTaskView] = useState<TaskView>('review')
|
|
105
147
|
const [recordView, setRecordView] = useState<RecordView>('decisions')
|
|
148
|
+
const [pendingWorkflow, setPendingWorkflow] = useState<Extract<WorkflowCommand, { kind: 'advance' | 'confirm' | 'generate-ready' }>>()
|
|
149
|
+
const [pendingNavigation, setPendingNavigation] = useState<PendingNavigation>()
|
|
106
150
|
const [mobilePane, setMobilePane] = useState<'spec' | 'collab'>('spec')
|
|
107
151
|
const [reviewOpenRequest, setReviewOpenRequest] = useState<ReviewOpenRequest>()
|
|
108
152
|
const reviewOpenRequestId = useRef(0)
|
|
153
|
+
const [deepLinkObjectId, setDeepLinkObjectId] = useState<string>()
|
|
154
|
+
const resolvedDeepLinkHash = useRef('')
|
|
155
|
+
const approvedDeepLinkHash = useRef('')
|
|
109
156
|
const [documentFocus, setDocumentFocus] = useState<DocumentAnchorFocus>()
|
|
110
157
|
const [documentFocusRequest, setDocumentFocusRequest] = useState(0)
|
|
111
158
|
const [draft, setDraft] = useState('')
|
|
@@ -118,8 +165,29 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
118
165
|
const [commentText, setCommentText] = useState('')
|
|
119
166
|
const [draftSelection, setDraftSelection] = useState<EditorSelection>()
|
|
120
167
|
const [inlineReview, setInlineReview] = useState<InlineReviewTarget>()
|
|
121
|
-
const
|
|
122
|
-
const
|
|
168
|
+
const [requirementQuery, setRequirementQuery] = useState('')
|
|
169
|
+
const [requirementFilters, setRequirementFilters] = useState<{ stage: 'all' | RequirementStage; participantId: string; risk: boolean; unread: boolean; insights: boolean }>({ stage: 'all', participantId: '', risk: false, unread: false, insights: false })
|
|
170
|
+
const [pageCommentOpen, setPageCommentOpen] = useState(false)
|
|
171
|
+
const [pageCommentText, setPageCommentText] = useState('')
|
|
172
|
+
const [notifications, setNotifications] = useState<Notification[]>([])
|
|
173
|
+
const [notificationsOpen, setNotificationsOpen] = useState(false)
|
|
174
|
+
const [myWorkOpen, setMyWorkOpen] = useState(false)
|
|
175
|
+
const [draftSavedAt, setDraftSavedAt] = useState<number>()
|
|
176
|
+
const [draftContextKey, setDraftContextKey] = useState<string>()
|
|
177
|
+
const [undoArchiveId, setUndoArchiveId] = useState<string>()
|
|
178
|
+
const scrollPositions = useRef(new Map<string, number>())
|
|
179
|
+
const normalizedQuery = requirementQuery.trim().toLocaleLowerCase()
|
|
180
|
+
const unreadRequirementIds = new Set(notifications.filter(item => item.readAt === undefined).map(item => item.requirementId))
|
|
181
|
+
const visibleRequirements = requirements.filter(item => Boolean(item.archivedAt) === showArchived
|
|
182
|
+
&& (!normalizedQuery || `${item.id}\n${item.title}`.toLocaleLowerCase().includes(normalizedQuery))
|
|
183
|
+
&& (requirementFilters.stage === 'all' || item.stage === requirementFilters.stage)
|
|
184
|
+
&& (!requirementFilters.participantId || requirementParticipantIds(item).has(requirementFilters.participantId))
|
|
185
|
+
&& (!requirementFilters.risk || item.metrics.riskCount > 0)
|
|
186
|
+
&& (!requirementFilters.unread || unreadRequirementIds.has(item.id))
|
|
187
|
+
&& (!requirementFilters.insights || item.metrics.insightCount > 0))
|
|
188
|
+
.sort((left, right) => right.updatedAt - left.updatedAt)
|
|
189
|
+
const activeRequirementFilterCount = Number(requirementFilters.stage !== 'all') + Number(Boolean(requirementFilters.participantId)) + Number(requirementFilters.risk) + Number(requirementFilters.unread) + Number(requirementFilters.insights)
|
|
190
|
+
const selected = selectedRequirement?.id === selectedId ? selectedRequirement : undefined
|
|
123
191
|
const manageTarget = requirements.find(item => item.id === manageTargetId)
|
|
124
192
|
const boundRole = participantBindings.find(item => item.participantId === participant.participantId)?.role
|
|
125
193
|
const currentMyItems = selected ? myItems.filter(item => item.requirementId === selected.id) : []
|
|
@@ -131,24 +199,100 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
131
199
|
const inlineReviewItem = selected?.reviewItems.find(item => item.id === inlineReview?.itemId)
|
|
132
200
|
const nextInlineReview = selected && inlineReviewItem ? currentReviews.find(item => item.status === 'open' && item.id !== inlineReviewItem.id) : undefined
|
|
133
201
|
const pendingPatches = selected?.patches.filter(item => item.baseCommit === selected.currentCommit && item.status === 'pending') ?? []
|
|
134
|
-
const openDiscussions = selected?.
|
|
202
|
+
const openDiscussions = selected?.metrics.openCommentCount ?? 0
|
|
135
203
|
const failedChecks = selected?.readiness.filter(item => !item.passed).length ?? 0
|
|
136
|
-
const openReviewCount =
|
|
137
|
-
const blockingReviewCount =
|
|
138
|
-
const activeDecisionCount = selected?.
|
|
204
|
+
const openReviewCount = selected?.metrics.openReviewCount ?? 0
|
|
205
|
+
const blockingReviewCount = selected?.metrics.riskCount ?? 0
|
|
206
|
+
const activeDecisionCount = selected?.metrics.activeDecisionCount ?? 0
|
|
139
207
|
const invalidatedDecisionCount = selected?.decisions.filter(item => item.status === 'invalidated').length ?? 0
|
|
140
208
|
const runningAiCount = selected?.aiRuns.filter(item => item.commit === selected.currentCommit && ['queued', 'running'].includes(item.status)).length ?? 0
|
|
141
209
|
const workflow = selected ? workflowState(selected, participant.role) : undefined
|
|
210
|
+
const assertiveNotice = /失败|错误|不存在|冲突|损坏|无法|禁止|失效|未登记|阻止/.test(notice)
|
|
142
211
|
|
|
143
|
-
const
|
|
212
|
+
const registered = participant.nickname.trim().length >= 2
|
|
213
|
+
const participantRef = useRef(participant); participantRef.current = participant
|
|
214
|
+
const selectedIdRef = useRef(selectedId); selectedIdRef.current = selectedId
|
|
215
|
+
const refresh = async (requestedId: string | undefined = selectedIdRef.current): Promise<void> => { try { const state = await api.state(requestedId); const currentParticipant = participantRef.current; const fallbackId = state.requirement?.id ?? state.requirements.find(item => item.archivedAt === undefined)?.id ?? state.requirements[0]?.id; const nextId = requestedId && state.requirements.some(item => item.id === requestedId) ? requestedId : fallbackId; setRequirements(state.requirements); setParticipantBindings(state.participants); setSelectedId(nextId); if (state.requirement?.id === nextId) setSelectedRequirement(state.requirement); else if (!nextId) setSelectedRequirement(undefined); const binding = state.participants.find(item => item.participantId === currentParticipant.participantId); if (binding && binding.role !== currentParticipant.role) setParticipant(current => ({ ...current, role: binding.role })); if (currentParticipant.nickname.trim().length >= 2) void api.notifications(currentParticipant.participantId).then(result => setNotifications(result.items), error => setNotice(error instanceof Error ? error.message : String(error))) } catch (error) { setNotice(error instanceof Error ? error.message : String(error)) } }
|
|
144
216
|
useEffect(() => { void refresh(); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))); return api.events(() => { void refresh() }) }, [])
|
|
145
|
-
useEffect(() => { if (
|
|
217
|
+
useEffect(() => { if (!selectedId || selectedRequirement?.id === selectedId) return; void refresh(selectedId) }, [selectedId, selectedRequirement?.id])
|
|
218
|
+
useEffect(() => {
|
|
219
|
+
let cancelled = false
|
|
220
|
+
setDraftContextKey(undefined)
|
|
221
|
+
if (!selected) { setDraft(''); setSummary(''); return }
|
|
222
|
+
const contextKey = `${selected.id}:${participant.participantId}:${selected.currentCommit}`
|
|
223
|
+
void loadDraft(selected.id, participant.participantId).then(saved => {
|
|
224
|
+
if (cancelled) return
|
|
225
|
+
if (saved && saved.markdown !== selected.version.markdown) { setDraft(saved.markdown); setSummary(saved.summary); setDraftSavedAt(saved.updatedAt); setNotice(saved.baseCommit === selected.currentCommit ? '已恢复本地草稿' : '已恢复旧基线草稿,保存时会进入冲突合并') }
|
|
226
|
+
else { setDraft(selected.version.markdown); setSummary(''); setDraftSavedAt(undefined) }
|
|
227
|
+
setDraftContextKey(contextKey)
|
|
228
|
+
})
|
|
229
|
+
return () => { cancelled = true }
|
|
230
|
+
}, [selected?.id, selected?.currentCommit, participant.participantId])
|
|
146
231
|
useEffect(() => { setDocumentFocus(undefined); setDraftSelection(undefined); setCommentText(''); setInlineReview(undefined) }, [selected?.id, selected?.currentCommit])
|
|
147
232
|
useEffect(() => { localStorage.setItem('dsh-spec-collab.participant', JSON.stringify(participant)) }, [participant])
|
|
148
233
|
useEffect(() => { localStorage.setItem('dsh-spec-collab.documents-width', String(documentsWidth)) }, [documentsWidth])
|
|
149
234
|
useEffect(() => { localStorage.setItem('dsh-spec-collab.review-width', String(reviewWidth)) }, [reviewWidth])
|
|
150
235
|
useEffect(() => { if (!registered) { setMyItems([]); return }; void api.myItems(participant).then(setMyItems, error => setNotice(error instanceof Error ? error.message : String(error))) }, [participant.participantId, participant.role, requirements])
|
|
151
|
-
|
|
236
|
+
useEffect(() => {
|
|
237
|
+
if (!selected || draftContextKey !== `${selected.id}:${participant.participantId}:${selected.currentCommit}` || draft === selected.version.markdown) return
|
|
238
|
+
const timer = window.setTimeout(() => { const updatedAt = Date.now(); void saveDraft({ requirementId: selected.id, participantId: participant.participantId, baseCommit: selected.currentCommit, markdown: draft, summary, updatedAt }).then(() => setDraftSavedAt(updatedAt)) }, 500)
|
|
239
|
+
return () => window.clearTimeout(timer)
|
|
240
|
+
}, [selected?.id, selected?.currentCommit, selected?.version.markdown, participant.participantId, draft, summary, draftContextKey])
|
|
241
|
+
useEffect(() => {
|
|
242
|
+
const beforeUnload = (event: BeforeUnloadEvent): void => { if (selected && draft !== selected.version.markdown) { event.preventDefault(); event.returnValue = '' } }
|
|
243
|
+
window.addEventListener('beforeunload', beforeUnload); return () => window.removeEventListener('beforeunload', beforeUnload)
|
|
244
|
+
}, [selected?.id, selected?.version.markdown, draft])
|
|
245
|
+
useEffect(() => {
|
|
246
|
+
if (!selected) return
|
|
247
|
+
const timer = window.setTimeout(() => { const scroller = workbenchRef.current?.querySelector<HTMLElement>('.toastui-editor-ww-container'); if (scroller) scroller.scrollTop = scrollPositions.current.get(selected.id) ?? 0 }, 80)
|
|
248
|
+
return () => { window.clearTimeout(timer); const scroller = workbenchRef.current?.querySelector<HTMLElement>('.toastui-editor-ww-container'); if (scroller) scrollPositions.current.set(selected.id, scroller.scrollTop) }
|
|
249
|
+
}, [selected?.id])
|
|
250
|
+
useEffect(() => {
|
|
251
|
+
const shortcut = (event: KeyboardEvent): void => {
|
|
252
|
+
if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLocaleLowerCase() === 'f') { event.preventDefault(); toggleFocusMode() }
|
|
253
|
+
else if ((event.metaKey || event.ctrlKey) && event.key.toLocaleLowerCase() === 's') { event.preventDefault(); if (selected && draft !== selected.version.markdown && summary.trim()) void save() }
|
|
254
|
+
}
|
|
255
|
+
window.addEventListener('keydown', shortcut); return () => window.removeEventListener('keydown', shortcut)
|
|
256
|
+
}, [focusMode, documentsOpen, reviewOpen, selected?.id, selected?.version.markdown, draft, summary])
|
|
257
|
+
useEffect(() => {
|
|
258
|
+
const resolve = (): void => {
|
|
259
|
+
if (location.hash === resolvedDeepLinkHash.current) return
|
|
260
|
+
const match = /^#spec-collab\/([^/]+)\/([^/]+)(?:\/([^?]+))?/.exec(location.hash)
|
|
261
|
+
if (!match) return
|
|
262
|
+
const requirementId = decodeURIComponent(match[1]!); const view = match[2]!; const objectId = match[3] ? decodeURIComponent(match[3]) : undefined
|
|
263
|
+
const requirement = requirements.find(item => item.id === requirementId)
|
|
264
|
+
if (!requirement) { if (requirements.length > 0) { resolvedDeepLinkHash.current = location.hash; setNotice('链接指向的需求不存在或已被删除') } return }
|
|
265
|
+
if (selected && selected.id !== requirementId && draft !== selected.version.markdown && approvedDeepLinkHash.current !== location.hash) { setPendingNavigation({ kind: 'deep-link', hash: location.hash }); return }
|
|
266
|
+
if (selected?.id !== requirementId) { setSelectedId(requirementId); return }
|
|
267
|
+
const target = resolveDeepLinkTarget(selected, view, objectId)
|
|
268
|
+
approvedDeepLinkHash.current = ''
|
|
269
|
+
resolvedDeepLinkHash.current = location.hash
|
|
270
|
+
setDocumentDrawerOpen(false); setReviewOpen(true)
|
|
271
|
+
setPrimaryMode(target.primaryMode); setMobilePane('collab')
|
|
272
|
+
if (target.taskView) setTaskView(target.taskView)
|
|
273
|
+
if (target.recordView) setRecordView(target.recordView)
|
|
274
|
+
if (target.commentObjectId) setDocumentFocus({ kind: 'comment', objectId: target.commentObjectId })
|
|
275
|
+
if (target.reviewObjectId) setReviewOpenRequest({ objectId: target.reviewObjectId, requestId: ++reviewOpenRequestId.current })
|
|
276
|
+
setDeepLinkObjectId(target.focusObjectId)
|
|
277
|
+
if (target.error) setNotice(target.error)
|
|
278
|
+
}
|
|
279
|
+
resolve(); window.addEventListener('hashchange', resolve); return () => window.removeEventListener('hashchange', resolve)
|
|
280
|
+
}, [requirements, selected?.id, selected?.version.markdown, draft])
|
|
281
|
+
useEffect(() => {
|
|
282
|
+
if (!deepLinkObjectId) return
|
|
283
|
+
let located = false
|
|
284
|
+
let cleanupTimer = 0
|
|
285
|
+
const timers = [80, 180, 360, 720].map(delay => window.setTimeout(() => {
|
|
286
|
+
if (located) return
|
|
287
|
+
const element = document.getElementById(`spec-object-${deepLinkObjectId}`)
|
|
288
|
+
if (!element) return
|
|
289
|
+
located = true
|
|
290
|
+
element.scrollIntoView({ block: 'center' })
|
|
291
|
+
element.setAttribute('data-dsh-deep-link-focus', '')
|
|
292
|
+
cleanupTimer = window.setTimeout(() => { element.removeAttribute('data-dsh-deep-link-focus'); setDeepLinkObjectId(undefined) }, 2400)
|
|
293
|
+
}, delay))
|
|
294
|
+
return () => { timers.forEach(window.clearTimeout); window.clearTimeout(cleanupTimer) }
|
|
295
|
+
}, [deepLinkObjectId, selected?.id, primaryMode, taskView, recordView])
|
|
152
296
|
|
|
153
297
|
const act = async (factory: (actor: ParticipantSnapshot) => CollaborationAction): Promise<boolean> => {
|
|
154
298
|
if (!registered) { setIdentityOpen(true); setNotice('首次写操作前请登记花名'); return false }
|
|
@@ -159,18 +303,49 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
159
303
|
if (result.conflict) { setSaveConflict(result.conflict); setMergeDraft(result.conflict.draftMarkdown); setNotice('检测到并发修改。请在三方对比中合并后再提交。'); return false }
|
|
160
304
|
setNotice(friendlyActionError(result.error)); return false
|
|
161
305
|
}
|
|
162
|
-
setSaveConflict(undefined)
|
|
306
|
+
setSaveConflict(undefined)
|
|
307
|
+
if (result.deletedRequirementId) { selectedIdRef.current = undefined; setSelectedId(undefined); setSelectedRequirement(undefined); await refresh() }
|
|
308
|
+
else { selectedIdRef.current = result.requirement.id; setSelectedId(result.requirement.id); setSelectedRequirement(result.requirement); await refresh(result.requirement.id) }
|
|
309
|
+
return true
|
|
163
310
|
}
|
|
311
|
+
catch (error) { setNotice(`操作失败:${error instanceof Error ? error.message : String(error)}`); return false }
|
|
164
312
|
finally { setBusy(false) }
|
|
165
313
|
}
|
|
166
314
|
|
|
315
|
+
const performNavigation = (navigation: PendingNavigation): void => {
|
|
316
|
+
if (navigation.kind === 'select') { setSelectedId(navigation.requirementId); setPrimaryMode('tasks'); setDocumentDrawerOpen(false); return }
|
|
317
|
+
if (navigation.kind === 'toggle-archive') { setShowArchived(value => !value); setSelectedId(undefined); setManageMenuId(undefined); return }
|
|
318
|
+
if (navigation.kind === 'deep-link') { approvedDeepLinkHash.current = navigation.hash; window.dispatchEvent(new HashChangeEvent('hashchange')); return }
|
|
319
|
+
if (navigation.kind === 'archive') { void archiveRequirementById(navigation.requirementId, navigation.archived); return }
|
|
320
|
+
if (location.hash.startsWith('#spec-collab/')) { history.replaceState(history.state, '', `${location.pathname}${location.search}`); resolvedDeepLinkHash.current = '' }
|
|
321
|
+
onClose()
|
|
322
|
+
}
|
|
323
|
+
const requestNavigation = (navigation: PendingNavigation): void => {
|
|
324
|
+
if (selected && draft !== selected.version.markdown) { setPendingNavigation(navigation); return }
|
|
325
|
+
performNavigation(navigation)
|
|
326
|
+
}
|
|
327
|
+
const leaveWithDraft = async (discard: boolean): Promise<void> => {
|
|
328
|
+
if (!pendingNavigation) return
|
|
329
|
+
const navigation = pendingNavigation; setPendingNavigation(undefined)
|
|
330
|
+
if (discard && selected) { void deleteDraft(selected.id, participant.participantId); setDraft(selected.version.markdown); setSummary(''); setDraftSavedAt(undefined) }
|
|
331
|
+
else if (selected && draft !== selected.version.markdown) { const updatedAt = Date.now(); await saveDraft({ requirementId: selected.id, participantId: participant.participantId, baseCommit: selected.currentCommit, markdown: draft, summary, updatedAt }); setDraftSavedAt(updatedAt) }
|
|
332
|
+
performNavigation(navigation)
|
|
333
|
+
}
|
|
334
|
+
const selectRequirement = (id: string): void => requestNavigation({ kind: 'select', requirementId: id })
|
|
335
|
+
const closeWorkbench = (): void => requestNavigation({ kind: 'close' })
|
|
336
|
+
useEffect(() => { const requestClose = (event: Event): void => { event.preventDefault(); closeWorkbench() }; document.addEventListener('dsh-spec-collab-request-close', requestClose); return () => document.removeEventListener('dsh-spec-collab-request-close', requestClose) }, [selected?.id, selected?.version.markdown, draft])
|
|
337
|
+
const toggleFocusMode = (): void => {
|
|
338
|
+
if (!focusMode) { previousPaneState.current = { documents: documentsOpen, review: reviewOpen }; setDocumentsOpen(false); setReviewOpen(false); setMobilePane('spec'); setFocusMode(true) }
|
|
339
|
+
else { setDocumentsOpen(previousPaneState.current.documents); setReviewOpen(previousPaneState.current.review); setFocusMode(false) }
|
|
340
|
+
}
|
|
341
|
+
|
|
167
342
|
const create = async (): Promise<void> => {
|
|
168
343
|
const links = createForm.sources.split('\n').map(value => value.trim()).filter(Boolean)
|
|
169
344
|
const ok = await act(actor => ({ kind: 'requirement.create', participant: actor, title: createForm.title, rawRequirement: createForm.rawRequirement, workspaceId: createForm.workspaceId, sources: links.map((label, index) => ({ id: `source-${index + 1}`, sourceType: /^https?:/.test(label) ? 'link' : 'text', label, ...(/^https?:/.test(label) ? { stableId: label } : {}), accessStatus: /^https?:/.test(label) ? 'unverified' : 'available' })) }))
|
|
170
345
|
if (ok) { setCreateOpen(false); setCreateForm({ title: '', rawRequirement: '', sources: '', workspaceId: '' }); setPrimaryMode('tasks'); setTaskView('review') }
|
|
171
346
|
}
|
|
172
347
|
const bindWorkspace = async (): Promise<void> => { if (!selected || !bindWorkspaceId) return; if (await act(actor => ({ kind: 'requirement.bind-workspace', participant: actor, requirementId: selected.id, workspaceId: bindWorkspaceId }))) { setBindWorkspaceOpen(false); setBindWorkspaceId('') } }
|
|
173
|
-
const save = async (): Promise<void> => { if (!selected) return; const ok = await act(actor => ({ kind: 'version.save', participant: actor, requirementId: selected.id, baseCommit: selected.currentCommit, markdown: draft, summary })); if (ok) { setSummary(''); setNotice('
|
|
348
|
+
const save = async (): Promise<void> => { if (!selected) return; const ok = await act(actor => ({ kind: 'version.save', participant: actor, requirementId: selected.id, baseCommit: selected.currentCommit, markdown: draft, summary })); if (ok) { await deleteDraft(selected.id, participant.participantId); setDraftSavedAt(undefined); setSummary(''); setNotice('已保存到版本库,并创建新的 Git commit') } }
|
|
174
349
|
const requestReview = async (reviewKind: ReviewKind): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'review.request', participant: actor, requirementId: selected.id, reviewKind })) }
|
|
175
350
|
const confirm = async (role: ParticipantRole): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'confirmation.create', participant: actor, requirementId: selected.id, role, scope: 'version' })) }
|
|
176
351
|
const advance = async (): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'stage.advance', participant: actor, requirementId: selected.id })) }
|
|
@@ -220,17 +395,26 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
220
395
|
focusCommentItem(objectId)
|
|
221
396
|
setMobilePane('spec')
|
|
222
397
|
}
|
|
398
|
+
const revealReadyPackage = (): void => {
|
|
399
|
+
window.setTimeout(() => workbenchRef.current?.querySelector<HTMLElement>('[data-ready-package]')?.scrollIntoView({ block: 'start' }), 80)
|
|
400
|
+
}
|
|
223
401
|
const executeWorkflow = async (command: WorkflowCommand): Promise<void> => {
|
|
224
402
|
if (!selected || command.kind === 'none') return
|
|
225
403
|
if (command.kind === 'open') {
|
|
226
404
|
setPrimaryMode('tasks')
|
|
227
405
|
setTaskView(command.view)
|
|
228
406
|
setMobilePane('collab')
|
|
407
|
+
if (command.view === 'ready') revealReadyPackage()
|
|
229
408
|
if (command.view === 'review' && command.objectId) openReviewItem(command.objectId)
|
|
230
409
|
return
|
|
231
410
|
}
|
|
232
411
|
if (command.kind === 'bind-workspace') { setBindWorkspaceOpen(true); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))); return }
|
|
233
412
|
if (command.kind === 'request-review') { setTaskView('review'); await requestReview(command.reviewKind); return }
|
|
413
|
+
if (command.kind === 'advance' || command.kind === 'confirm' || command.kind === 'generate-ready') { setPendingWorkflow(command); return }
|
|
414
|
+
}
|
|
415
|
+
const confirmWorkflow = async (): Promise<void> => {
|
|
416
|
+
if (!pendingWorkflow || !selected) return
|
|
417
|
+
const command = pendingWorkflow; setPendingWorkflow(undefined)
|
|
234
418
|
if (command.kind === 'advance') { await advance(); return }
|
|
235
419
|
if (command.kind === 'confirm') { await confirm(command.role); return }
|
|
236
420
|
setTaskView('ready')
|
|
@@ -272,8 +456,20 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
272
456
|
const stop = (): void => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', stop); document.body.style.cursor = '' }
|
|
273
457
|
document.body.style.cursor = 'col-resize'; window.addEventListener('pointermove', move); window.addEventListener('pointerup', stop)
|
|
274
458
|
}
|
|
459
|
+
const resizePaneWithKeyboard = (side: 'documents' | 'review', event: ReactKeyboardEvent<HTMLDivElement>): void => {
|
|
460
|
+
const current = side === 'documents' ? documentsWidth : reviewWidth; const min = side === 'documents' ? 160 : 320; const max = side === 'documents' ? 360 : 600
|
|
461
|
+
let next: number | undefined
|
|
462
|
+
if (event.key === 'Home') next = min
|
|
463
|
+
else if (event.key === 'End') next = max
|
|
464
|
+
else if (event.key === 'ArrowLeft') next = current + (side === 'documents' ? -1 : 1) * (event.shiftKey ? 64 : 16)
|
|
465
|
+
else if (event.key === 'ArrowRight') next = current + (side === 'documents' ? 1 : -1) * (event.shiftKey ? 64 : 16)
|
|
466
|
+
if (next === undefined) return
|
|
467
|
+
event.preventDefault(); const value = Math.max(min, Math.min(max, next)); if (side === 'documents') setDocumentsWidth(value); else setReviewWidth(value)
|
|
468
|
+
}
|
|
275
469
|
const renameRequirement = async (): Promise<void> => { if (!manageTarget) return; if (await act(actor => ({ kind: 'requirement.rename', participant: actor, requirementId: manageTarget.id, title: renameTitle }))) { setRenameOpen(false); setManageTargetId(undefined) } }
|
|
276
|
-
const
|
|
470
|
+
const archiveRequirementById = async (requirementId: string, archived: boolean): Promise<void> => { if (await act(actor => ({ kind: 'requirement.archive', participant: actor, requirementId, archived }))) { setManageMenuId(undefined); setSelectedId(visibleRequirements.find(item => item.id !== requirementId)?.id); if (archived) { setUndoArchiveId(requirementId); setNotice('需求已归档,Git 历史仍然保留'); window.setTimeout(() => setUndoArchiveId(current => current === requirementId ? undefined : current), 8_000) } } }
|
|
471
|
+
const archiveRequirement = async (target: RequirementSummary): Promise<void> => { const navigation: PendingNavigation = { kind: 'archive', requirementId: target.id, archived: !target.archivedAt }; if (selected?.id === target.id && draft !== selected.version.markdown) { setPendingNavigation(navigation); return }; await archiveRequirementById(navigation.requirementId, navigation.archived) }
|
|
472
|
+
const undoArchive = async (): Promise<void> => { if (!undoArchiveId) return; const id = undoArchiveId; if (await act(actor => ({ kind: 'requirement.unarchive', participant: actor, requirementId: id }))) { setUndoArchiveId(undefined); setShowArchived(false); setSelectedId(id); setNotice('已撤销归档') } }
|
|
277
473
|
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) } }
|
|
278
474
|
|
|
279
475
|
const updateDraftSelection = (value?: EditorSelection): void => {
|
|
@@ -291,11 +487,17 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
291
487
|
const addComment = async (): Promise<void> => {
|
|
292
488
|
if (!selected || !draftSelection || !commentText.trim()) return
|
|
293
489
|
const anchor: CommentAnchor = { quote: draftSelection.quote, prefix: draftSelection.prefix, suffix: draftSelection.suffix, ...(draftSelection.heading ? { heading: draftSelection.heading } : {}) }
|
|
294
|
-
const
|
|
490
|
+
const mentions = mentionedParticipantIds(commentText, participantBindings)
|
|
491
|
+
const ok = await act(actor => ({ kind: 'comment.create', participant: actor, requirementId: selected.id, commit: selected.currentCommit, anchor, body: commentText.trim(), mentions }))
|
|
295
492
|
if (ok) { setDraftSelection(undefined); setCommentText(''); setNotice('讨论已提交,AI 正在结合正文和工作区上下文分析') }
|
|
296
493
|
}
|
|
494
|
+
const addPageComment = async (): Promise<void> => {
|
|
495
|
+
if (!selected || !pageCommentText.trim()) return
|
|
496
|
+
const mentions = mentionedParticipantIds(pageCommentText, participantBindings)
|
|
497
|
+
if (await act(actor => ({ kind: 'comment.create', participant: actor, requirementId: selected.id, commit: selected.currentCommit, scope: 'page', body: pageCommentText.trim(), mentions }))) { setPageCommentOpen(false); setPageCommentText(''); setPrimaryMode('discussion'); setReviewOpen(true); setMobilePane('collab'); setNotice('页面总评已提交') }
|
|
498
|
+
}
|
|
297
499
|
|
|
298
|
-
return <div className={css.workbench}>
|
|
500
|
+
return <div ref={workbenchRef} className={`${css.workbench} ${focusMode ? css.focusMode : ''}`}>
|
|
299
501
|
<header className={css.header}>
|
|
300
502
|
<div className={css.titleBlock}>
|
|
301
503
|
<span className={css.productName}>需求共创</span>
|
|
@@ -304,41 +506,51 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
|
|
|
304
506
|
</div>
|
|
305
507
|
{selected && <StageRail stage={selected.stage}/>}
|
|
306
508
|
<div className={css.headerActions}>
|
|
307
|
-
<button className={css.quietButton} aria-label="返回聊天" onClick={
|
|
509
|
+
<button className={css.quietButton} aria-label="返回聊天" onClick={closeWorkbench}><span aria-hidden="true">←</span><span className={css.backLabel}>返回聊天</span></button>
|
|
510
|
+
<button className={css.quietButton} aria-pressed={focusMode} title="聚焦正文(⌘⇧F)" onClick={toggleFocusMode}>{focusMode ? '退出聚焦' : '聚焦正文'}</button>
|
|
511
|
+
{registered && <button className={css.myWorkButton} onClick={() => setMyWorkOpen(true)}>我的工作{myItems.length + notifications.filter(item => item.readAt === undefined).length > 0 && <b>{myItems.length + notifications.filter(item => item.readAt === undefined).length}</b>}</button>}
|
|
512
|
+
{registered && <button className={css.notificationButton} aria-label={`通知,${notifications.filter(item => item.readAt === undefined).length} 条未读`} onClick={() => setNotificationsOpen(true)}>通知{notifications.some(item => item.readAt === undefined) && <b>{notifications.filter(item => item.readAt === undefined).length}</b>}</button>}
|
|
308
513
|
<button className={css.identity} onClick={() => setIdentityOpen(true)}>{registered ? `${participant.nickname} · ${participant.role === 'product' ? '产品' : '研发'}` : '登记身份'}</button>
|
|
309
514
|
</div>
|
|
310
515
|
</header>
|
|
311
|
-
<div className={notice ? css.notice : css.noticeHidden}>{notice}<button aria-label="关闭" onClick={() => setNotice('')}>×</button></div>
|
|
312
|
-
<div className={css.mobileViewSwitch}><button className={mobilePane === 'spec' ? css.activeMode : ''} onClick={() => setMobilePane('spec')}>需求正文</button><button className={mobilePane === 'collab' ? css.activeMode : ''} onClick={() => setMobilePane('collab')}
|
|
516
|
+
<div className={notice ? css.notice : css.noticeHidden} role={assertiveNotice ? 'alert' : 'status'} aria-live={assertiveNotice ? 'assertive' : 'polite'} aria-atomic="true"><span>{notice}</span>{undoArchiveId && <button onClick={() => void undoArchive()}>撤销归档</button>}<button aria-label="关闭" onClick={() => setNotice('')}>×</button></div>
|
|
517
|
+
<div className={css.mobileViewSwitch}><button className={css.mobileDocumentsTrigger} onClick={() => setDocumentDrawerOpen(true)}>需求列表</button><button className={mobilePane === 'spec' ? css.activeMode : ''} onClick={() => setMobilePane('spec')}>需求正文</button><button className={mobilePane === 'collab' ? css.activeMode : ''} onClick={() => setMobilePane('collab')}>协作{currentMyItems.length > 0 ? ` · ${currentMyItems.length}` : ''}</button></div>
|
|
313
518
|
<div className={`${css.grid} ${mobilePane === 'spec' ? css.mobileSpec : css.mobileCollab}`} style={{ '--documents-width': documentsOpen ? `${documentsWidth}px` : '0px', '--documents-handle': documentsOpen ? '6px' : '0px', '--review-width': reviewOpen ? `${reviewWidth}px` : '0px', '--review-handle': reviewOpen ? '6px' : '0px' } as CSSProperties}>
|
|
314
|
-
<aside className={`${css.documents} ${documentsOpen ? '' : css.paneClosed}`} aria-label="需求列表">
|
|
315
|
-
<div className={css.paneHead}><strong>{showArchived ? '已归档' : '需求'}</strong><div className={css.paneActions}><button onClick={() => {
|
|
316
|
-
<
|
|
519
|
+
<aside className={`${css.documents} ${documentsOpen ? '' : css.paneClosed} ${documentDrawerOpen ? css.mobileDocumentsOpen : ''}`} aria-label="需求列表">
|
|
520
|
+
<div className={css.paneHead}><strong>{showArchived ? '已归档' : '需求'}</strong><div className={css.paneActions}><button onClick={() => requestNavigation({ kind: 'toggle-archive' })}>{showArchived ? '返回进行中' : '查看归档'}</button>{!showArchived && <button className={css.createButton} aria-label="新建需求" title="新建需求" onClick={() => { setCreateOpen(true); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))) }}>+</button>}<button className={css.mobileDrawerClose} aria-label="关闭需求列表" onClick={() => setDocumentDrawerOpen(false)}>×</button><button className={css.iconButton} aria-label="收起需求栏" title="收起需求栏" onClick={() => setDocumentsOpen(false)}>‹</button></div></div>
|
|
521
|
+
<div className={css.requirementFilters}>
|
|
522
|
+
<label className={css.requirementSearch}>搜索需求<input type="search" value={requirementQuery} onChange={event => setRequirementQuery(event.target.value)} placeholder="标题或编号"/></label>
|
|
523
|
+
<div><label>阶段<select value={requirementFilters.stage} onChange={event => setRequirementFilters(current => ({ ...current, stage: event.target.value as typeof current.stage }))}><option value="all">全部阶段</option>{stageSteps.map(item => <option key={item.stage} value={item.stage}>{item.label}</option>)}</select></label><label>参与者<select value={requirementFilters.participantId} onChange={event => setRequirementFilters(current => ({ ...current, participantId: event.target.value }))}><option value="">全部参与者</option>{participantBindings.map(person => <option key={person.participantId} value={person.participantId}>{person.nickname}</option>)}</select></label></div>
|
|
524
|
+
<div className={css.filterChecks}><label><input type="checkbox" checked={requirementFilters.risk} onChange={event => setRequirementFilters(current => ({ ...current, risk: event.target.checked }))}/>有风险</label><label><input type="checkbox" checked={requirementFilters.unread} onChange={event => setRequirementFilters(current => ({ ...current, unread: event.target.checked }))}/>有未读</label><label><input type="checkbox" checked={requirementFilters.insights} onChange={event => setRequirementFilters(current => ({ ...current, insights: event.target.checked }))}/>有洞察</label></div>
|
|
525
|
+
{(activeRequirementFilterCount > 0 || normalizedQuery) && <div className={css.activeFilters}><span>{activeRequirementFilterCount + Number(Boolean(normalizedQuery))} 个筛选条件生效</span><button onClick={() => { setRequirementQuery(''); setRequirementFilters({ stage: 'all', participantId: '', risk: false, unread: false, insights: false }) }}>清除全部</button></div>}
|
|
526
|
+
</div>
|
|
527
|
+
<nav>{visibleRequirements.map(item => <div className={css.requirementRow} key={item.id}><button className={`${css.documentButton} ${item.id === selected?.id ? css.selectedDoc : ''}`} onClick={() => selectRequirement(item.id)}><span>{item.title}</span><small><i className={`${css.statusDot} ${css[`stage_${item.stage}`]}`}/>{item.archivedAt ? `归档于 ${new Date(item.archivedAt).toLocaleDateString()}` : `${stageLabel(item.stage)}${item.metrics.pendingActionCount > 0 ? ` · ${item.metrics.pendingActionCount} 项待处理` : ''}`}</small></button><button className={css.rowMenuButton} aria-label={`${item.title} 更多操作`} title="更多操作" onClick={() => { selectRequirement(item.id); setManageMenuId(current => current === item.id ? undefined : item.id) }}>…</button>{manageMenuId === item.id && <div className={css.requirementMenu}><button onClick={() => { setManageTargetId(item.id); setRenameTitle(item.title); setRenameOpen(true); setManageMenuId(undefined) }}>重命名</button><button onClick={() => void archiveRequirement(item)}>{item.archivedAt ? '取消归档' : '归档需求'}</button><button className={css.dangerText} onClick={() => { setManageTargetId(item.id); setDeleteOpen(true); setManageMenuId(undefined) }}>删除需求</button></div>}</div>)}</nav>
|
|
317
528
|
{visibleRequirements.length === 0 && <div className={css.emptyList}><strong>{showArchived ? '还没有归档需求' : '从一个真实问题开始'}</strong><p>{showArchived ? '归档后的需求会出现在这里。' : '输入原始需求,AI 会先帮你找出缺口。'}</p>{!showArchived && <button onClick={() => { setCreateOpen(true); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))) }}>新建需求</button>}</div>}
|
|
318
529
|
</aside>
|
|
319
|
-
<div className={`${css.resizer} ${documentsOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整需求栏宽度" aria-orientation="vertical" onPointerDown={event => resizePane('documents', event)}/>
|
|
530
|
+
<div className={`${css.resizer} ${documentsOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整需求栏宽度" aria-orientation="vertical" aria-valuemin={160} aria-valuemax={360} aria-valuenow={documentsWidth} tabIndex={documentsOpen ? 0 : -1} onKeyDown={event => resizePaneWithKeyboard('documents', event)} onPointerDown={event => resizePane('documents', event)}/>
|
|
320
531
|
<main className={css.editorPane}>
|
|
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
|
|
532
|
+
<div className={css.toolbar}><div className={css.editorTitle}><button className={css.mobileDocumentsTrigger} aria-label="打开需求列表" onClick={() => setDocumentDrawerOpen(true)}>☰</button>{!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 ? `本地草稿${draftSavedAt ? ` · ${relativeTime(draftSavedAt)}` : ''}` : '已保存到版本库'}</span><label className={css.summaryField}>本次改动<input className={css.summaryInput} required value={summary} onChange={event => setSummary(event.target.value)} placeholder="例如:补充退款边界"/></label><button title={!selected ? '请先选择需求' : draft === selected.version.markdown ? '正文没有变化' : !summary.trim() ? '请填写本次改动说明' : '保存到版本库(⌘S)'} className={css.saveButton} disabled={busy || !selected || draft === selected.version.markdown || !summary.trim()} onClick={() => void save()}>保存到版本库</button><button onClick={() => setPageCommentOpen(true)} disabled={!selected}>评论整篇</button>{!reviewOpen && <button className={css.iconButton} aria-label="展开协作面板" title="展开协作面板" onClick={() => setReviewOpen(true)}>‹</button>}</div></div>
|
|
322
533
|
{draftSelection && <InlineCommentComposer selection={draftSelection} text={commentText} setText={setCommentText} busy={busy} cancel={cancelCommentDraft} submit={addComment}/>}
|
|
323
534
|
{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
535
|
{!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></>}
|
|
325
536
|
</main>
|
|
326
|
-
<div className={`${css.resizer} ${reviewOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整协作栏宽度" aria-orientation="vertical" onPointerDown={event => resizePane('review', event)}/>
|
|
537
|
+
<div className={`${css.resizer} ${reviewOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整协作栏宽度" aria-orientation="vertical" aria-valuemin={320} aria-valuemax={600} aria-valuenow={reviewWidth} tabIndex={reviewOpen ? 0 : -1} onKeyDown={event => resizePaneWithKeyboard('review', event)} onPointerDown={event => resizePane('review', event)}/>
|
|
327
538
|
<aside className={`${css.review} ${reviewOpen ? '' : css.paneClosed}`} aria-label="需求协作">
|
|
328
|
-
<div className={css.primaryNav}><div role="tablist" aria-label="协作视图"><button role="tab" aria-selected={primaryMode === 'tasks'} className={primaryMode === 'tasks' ? css.activeMode : ''} onClick={() => setPrimaryMode('tasks')}>下一步{currentMyItems.length > 0 && <span className={css.tabBadge}>{currentMyItems.length}</span>}</button><button role="tab" aria-selected={primaryMode === 'discussion'} className={primaryMode === 'discussion' ? css.activeMode : ''} onClick={() => setPrimaryMode('discussion')}>讨论{openDiscussions > 0 && <span className={css.tabBadge}>{openDiscussions}</span>}</button><button role="tab" aria-selected={primaryMode === 'records'} className={primaryMode === 'records' ? css.activeMode : ''} onClick={() => setPrimaryMode('records')}>记录</button></div><button className={`${css.iconButton} ${css.collapseRight}`} aria-label="
|
|
329
|
-
{selected && primaryMode === 'tasks' &&
|
|
539
|
+
<div className={css.primaryNav}><div role="tablist" aria-label="协作视图" onKeyDown={event => handleTabs(event, ['tasks', 'discussion', 'insights', 'records'], primaryMode, setPrimaryMode)}><button id="collab-tab-tasks" aria-controls="collab-panel-tasks" role="tab" tabIndex={primaryMode === 'tasks' ? 0 : -1} aria-selected={primaryMode === 'tasks'} className={primaryMode === 'tasks' ? css.activeMode : ''} onClick={() => setPrimaryMode('tasks')}>下一步{currentMyItems.length > 0 && <span className={css.tabBadge}>{currentMyItems.length}</span>}</button><button id="collab-tab-discussion" aria-controls="collab-panel-discussion" role="tab" tabIndex={primaryMode === 'discussion' ? 0 : -1} aria-selected={primaryMode === 'discussion'} className={primaryMode === 'discussion' ? css.activeMode : ''} onClick={() => setPrimaryMode('discussion')}>讨论{openDiscussions > 0 && <span className={css.tabBadge}>{openDiscussions}</span>}</button><button id="collab-tab-insights" aria-controls="collab-panel-insights" role="tab" tabIndex={primaryMode === 'insights' ? 0 : -1} aria-selected={primaryMode === 'insights'} className={primaryMode === 'insights' ? css.activeMode : ''} onClick={() => setPrimaryMode('insights')}>洞察{selected && selected.metrics.insightCount > 0 && <span className={css.tabBadge}>{selected.metrics.insightCount}</span>}</button><button id="collab-tab-records" aria-controls="collab-panel-records" role="tab" tabIndex={primaryMode === 'records' ? 0 : -1} aria-selected={primaryMode === 'records'} className={primaryMode === 'records' ? css.activeMode : ''} onClick={() => setPrimaryMode('records')}>记录</button></div><button className={`${css.iconButton} ${css.collapseRight}`} aria-label="收起协作面板" title="收起协作面板" onClick={() => setReviewOpen(false)}>›</button></div>
|
|
540
|
+
{selected && primaryMode === 'tasks' && <div className={css.tabPanel} id="collab-panel-tasks" role="tabpanel" aria-labelledby="collab-tab-tasks">
|
|
330
541
|
{workflow && <WorkflowFocus state={workflow} pendingForMe={currentMyItems.length} onExecute={() => void executeWorkflow(workflow.command)}/>}
|
|
331
|
-
{currentMyItems.length > 0 && <TaskQueue items={currentMyItems} open={openMyItem}/>}
|
|
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>
|
|
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>
|
|
334
|
-
|
|
335
|
-
{selected && primaryMode === 'discussion' && <div className={css.threadList}><DiscussionPanel requirement={selected} focusedCommentId={focusedCommentId} onSelectComment={focusCommentItem} onLocateComment={locateCommentItem} act={act} api={api}/></div>}
|
|
336
|
-
{selected && primaryMode === '
|
|
542
|
+
{currentMyItems.length > 0 && <TaskQueue items={currentMyItems} open={openMyItem} participants={participantBindings} act={act}/>}
|
|
543
|
+
<div className={css.contextNav} role="tablist" aria-label="待处理内容" onKeyDown={event => handleTabs(event, ['review', 'patches', 'ready'], taskView, setTaskView)}><button id="tasks-tab-review" aria-controls="tasks-panel-review" role="tab" tabIndex={taskView === 'review' ? 0 : -1} aria-selected={taskView === 'review'} className={taskView === 'review' ? css.activeContext : ''} onClick={() => setTaskView('review')}>问题{currentReviews.length > 0 && <span>{currentReviews.length}</span>}</button><button id="tasks-tab-patches" aria-controls="tasks-panel-patches" role="tab" tabIndex={taskView === 'patches' ? 0 : -1} aria-selected={taskView === 'patches'} className={taskView === 'patches' ? css.activeContext : ''} onClick={() => setTaskView('patches')}>AI 建议{pendingPatches.length > 0 && <span>{pendingPatches.length}</span>}</button><button id="tasks-tab-ready" aria-controls="tasks-panel-ready" role="tab" tabIndex={taskView === 'ready' ? 0 : -1} aria-selected={taskView === 'ready'} className={taskView === 'ready' ? css.activeContext : ''} onClick={() => setTaskView('ready')}>完成条件{failedChecks > 0 && <span>{failedChecks}</span>}</button></div>
|
|
544
|
+
<div id={`tasks-panel-${taskView}`} role="tabpanel" aria-labelledby={`tasks-tab-${taskView}`} className={css.threadList}>{taskView === 'review' && <ReviewPanel key={selected.id} 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 key={selected.id} requirement={selected} act={act} api={api}/>} {taskView === 'ready' && <ReadyPanel key={selected.id} requirement={selected} act={act}/>}</div>
|
|
545
|
+
</div>}
|
|
546
|
+
{selected && primaryMode === 'discussion' && <div id="collab-panel-discussion" role="tabpanel" aria-labelledby="collab-tab-discussion" className={css.threadList}><DiscussionPanel requirement={selected} notifications={notifications} focusedCommentId={focusedCommentId} onSelectComment={focusCommentItem} onLocateComment={locateCommentItem} act={act} api={api}/></div>}
|
|
547
|
+
{selected && primaryMode === 'insights' && <div id="collab-panel-insights" role="tabpanel" aria-labelledby="collab-tab-insights" className={css.threadList}><InsightPanel key={selected.id} requirement={selected} api={api} act={act}/></div>}
|
|
548
|
+
{selected && primaryMode === 'records' && <div id="collab-panel-records" role="tabpanel" aria-labelledby="collab-tab-records" className={css.tabPanel}><div className={css.contextNav} role="tablist" aria-label="需求记录" onKeyDown={event => handleTabs(event, ['decisions', 'versions'], recordView, setRecordView)}><button id="records-tab-decisions" aria-controls="records-panel-decisions" role="tab" tabIndex={recordView === 'decisions' ? 0 : -1} aria-selected={recordView === 'decisions'} className={recordView === 'decisions' ? css.activeContext : ''} onClick={() => setRecordView('decisions')}>关键决策</button><button id="records-tab-versions" aria-controls="records-panel-versions" role="tab" tabIndex={recordView === 'versions' ? 0 : -1} aria-selected={recordView === 'versions'} className={recordView === 'versions' ? css.activeContext : ''} onClick={() => setRecordView('versions')}>版本历史</button></div><div id={`records-panel-${recordView}`} role="tabpanel" aria-labelledby={`records-tab-${recordView}`} className={css.threadList}>{recordView === 'decisions' && <DecisionPanel key={selected.id} requirement={selected} act={act}/>} {recordView === 'versions' && <VersionPanel key={selected.id} requirement={selected} api={api} act={act}/>}</div></div>}
|
|
337
549
|
{!selected && <div className={css.emptyAside}><strong>等待创建需求</strong><p>创建后,下一步操作会显示在这里。</p></div>}
|
|
338
550
|
</aside>
|
|
339
551
|
</div>
|
|
340
552
|
<footer className={css.footer}><span>AI 可以检查和建议,最终版本始终由人确认</span><span>{selected ? `${stageLabel(selected.stage)} · ${selected.currentCommit.slice(0, 8)} · ${selected.aiRuns.at(-1)?.status === 'running' ? 'AI 分析中' : '版本已记录'}` : '从原始需求开始'}</span></footer>
|
|
341
|
-
{identityOpen && <IdentityDialog value={participant} {...(boundRole === undefined ? {} : { boundRole })} onChange={setParticipant} close={() => setIdentityOpen(false)}/>} {createOpen && <CreateDialog value={createForm} setValue={setCreateForm} workspaces={reviewWorkspaces} close={() => setCreateOpen(false)} submit={() => void create()} busy={busy}/>} {bindWorkspaceOpen && selected && <WorkspaceDialog value={bindWorkspaceId} setValue={setBindWorkspaceId} workspaces={reviewWorkspaces} close={() => { setBindWorkspaceOpen(false); setBindWorkspaceId('') }} submit={() => void bindWorkspace()} busy={busy}/>} {renameOpen && <RenameDialog title={renameTitle} setTitle={setRenameTitle} close={() => { setRenameOpen(false); setManageTargetId(undefined) }} submit={() => void renameRequirement()} busy={busy}/>} {deleteOpen && manageTarget && <DeleteDialog title={manageTarget.title} close={() => { setDeleteOpen(false); setManageTargetId(undefined) }} submit={() => void deleteRequirement()} busy={busy}/>} {saveConflict && <ConflictDialog conflict={saveConflict} value={mergeDraft} setValue={setMergeDraft} close={() => setSaveConflict(undefined)} busy={busy} submit={() => void act(actor => ({ kind: 'version.save', participant: actor, requirementId: saveConflict.requirementId, baseCommit: saveConflict.currentCommit, markdown: mergeDraft, summary })).then(ok => { if (ok) { setDraft(mergeDraft); setSummary(''); setSaveConflict(undefined); setNotice('冲突已合并并创建新的 Git commit') } })}/>}
|
|
553
|
+
{identityOpen && <IdentityDialog value={participant} {...(boundRole === undefined ? {} : { boundRole })} onChange={setParticipant} close={() => setIdentityOpen(false)} save={() => { localStorage.setItem('dsh-spec-collab.participant', JSON.stringify(participant)); setIdentityOpen(false); if (selected) void api.action({ kind: 'participant.register', participant, requirementId: selected.id }).then(result => { if (!result.ok) throw new Error(result.error); return refresh() }).catch(error => setNotice(`登记失败:${error instanceof Error ? error.message : String(error)}`)) }}/>} {createOpen && <CreateDialog value={createForm} setValue={setCreateForm} workspaces={reviewWorkspaces} close={() => setCreateOpen(false)} submit={() => void create()} busy={busy}/>} {bindWorkspaceOpen && selected && <WorkspaceDialog value={bindWorkspaceId} setValue={setBindWorkspaceId} workspaces={reviewWorkspaces} close={() => { setBindWorkspaceOpen(false); setBindWorkspaceId('') }} submit={() => void bindWorkspace()} busy={busy}/>} {renameOpen && <RenameDialog title={renameTitle} setTitle={setRenameTitle} close={() => { setRenameOpen(false); setManageTargetId(undefined) }} submit={() => void renameRequirement()} busy={busy}/>} {deleteOpen && manageTarget && <DeleteDialog title={manageTarget.title} close={() => { setDeleteOpen(false); setManageTargetId(undefined) }} submit={() => void deleteRequirement()} busy={busy}/>} {saveConflict && <ConflictDialog conflict={saveConflict} value={mergeDraft} setValue={setMergeDraft} close={() => setSaveConflict(undefined)} busy={busy} submit={() => void act(actor => ({ kind: 'version.save', participant: actor, requirementId: saveConflict.requirementId, baseCommit: saveConflict.currentCommit, markdown: mergeDraft, summary })).then(ok => { if (ok) { setDraft(mergeDraft); setSummary(''); setSaveConflict(undefined); setNotice('冲突已合并并创建新的 Git commit') } })}/>} {pageCommentOpen && selected && <PageCommentDialog value={pageCommentText} setValue={setPageCommentText} close={() => setPageCommentOpen(false)} submit={() => void addPageComment()} busy={busy}/>} {notificationsOpen && <NotificationDialog notifications={notifications} close={() => setNotificationsOpen(false)} open={item => { setNotificationsOpen(false); location.hash = item.deepLink }} markRead={item => void act(actor => ({ kind: 'notification.mark-read', participant: actor, requirementId: item.requirementId, notificationIds: [item.id] }))}/>} {myWorkOpen && <MyWorkDialog items={myItems} notifications={notifications} close={() => setMyWorkOpen(false)} openItem={item => { setMyWorkOpen(false); const tab = item.target.tab; const view = tab === 'discussion' ? 'discussion' : tab === 'decisions' ? 'records' : 'tasks'; location.hash = `#spec-collab/${encodeURIComponent(item.requirementId)}/${view}/${encodeURIComponent(item.target.objectId)}` }} openNotification={item => { setMyWorkOpen(false); location.hash = item.deepLink }}/>} {pendingNavigation && selected && <AccessibleDialog title="处理未保存草稿" close={() => setPendingNavigation(undefined)} className={css.dialogSurface} dismissOnBackdrop={false}><div className={css.dialogForm}><div className={css.dialogHead}><div><span>本地草稿保护</span><h2>离开前如何处理当前草稿?</h2></div><button aria-label="继续编辑" onClick={() => setPendingNavigation(undefined)}>×</button></div><p>草稿已自动保存在此浏览器,尚未写入 Git。保留后可在下次打开此需求时继续;丢弃后无法恢复。</p><div className={css.stickyActions}><button onClick={() => setPendingNavigation(undefined)}>继续编辑</button><button onClick={() => void leaveWithDraft(true)} className={css.dangerText}>丢弃并离开</button><button className={css.execute} onClick={() => void leaveWithDraft(false)}>保留草稿并离开</button></div></div></AccessibleDialog>} {pendingWorkflow && selected && <AccessibleDialog title="确认流程操作" close={() => setPendingWorkflow(undefined)} className={css.dialogSurface}><div className={css.dialogForm}><div className={css.dialogHead}><div><span>流程确认</span><h2>{pendingWorkflow.kind === 'advance' ? `进入${selected.stage === 'product-review' ? '产品确认' : '产研确认'}?` : pendingWorkflow.kind === 'confirm' ? `确认当前版本 ${selected.currentCommit.slice(0, 8)}?` : '生成就绪需求?'}</h2></div><button aria-label="关闭" onClick={() => setPendingWorkflow(undefined)}>×</button></div><p>{pendingWorkflow.kind === 'advance' ? '阶段变化会通知协作者,当前版本和所有历史记录保持可追溯。' : pendingWorkflow.kind === 'confirm' ? '确认只绑定当前 commit;正文再次变化后需要重新确认。' : '将以产品和研发共同确认的当前 commit 生成可下载交付包。'}</p><div className={css.stickyActions}><button onClick={() => setPendingWorkflow(undefined)}>取消</button><button className={css.execute} onClick={() => void confirmWorkflow()}>确认执行</button></div></div></AccessibleDialog>}
|
|
342
554
|
</div>
|
|
343
555
|
}
|
|
344
556
|
|
|
@@ -362,9 +574,9 @@ function WorkflowFocus({ state, pendingForMe, onExecute }: { state: WorkflowStat
|
|
|
362
574
|
</section>
|
|
363
575
|
}
|
|
364
576
|
const taskTypeLabel: Record<MyActionItem['type'], string> = { reply: '需要回复', confirm: '需要确认', review: '需要审核', reconfirm: '需要重新确认' }
|
|
365
|
-
function TaskQueue({ items, open }: { items: MyActionItem[]; open: (item: MyActionItem) => void }) {
|
|
577
|
+
function TaskQueue({ items, open, participants, act }: { items: MyActionItem[]; open: (item: MyActionItem) => void; participants: ParticipantSnapshot[]; act: Act }) {
|
|
366
578
|
const sorted = items.slice().sort((left, right) => Number(right.blocking) - Number(left.blocking) || right.updatedAt - left.updatedAt)
|
|
367
|
-
return <details className={css.taskQueue}><summary><span>与你相关的事项</span><b>{items.length}</b></summary><div>{sorted.map(item => <
|
|
579
|
+
return <details className={css.taskQueue}><summary><span>与你相关的事项</span><b>{items.length}</b></summary><div>{sorted.map(item => <div className={css.taskRow} key={item.id}><button onClick={() => open(item)}><span>{item.blocking ? '优先' : '普通'}</span><div><strong>{item.objectTitle}</strong><small title={new Date(item.updatedAt).toLocaleString()}>{taskTypeLabel[item.type]} · {stageLabel(item.dueStage)}前 · {relativeTime(item.updatedAt)}</small></div><i aria-hidden="true">›</i></button><div className={css.taskAssignment}><label>指派<select aria-label="指派待办" value={item.assigneeParticipantId ?? `role:${item.assigneeRole}`} onChange={event => { const assignee = participants.find(person => person.participantId === event.target.value); const role = event.target.value === 'role:engineering' ? 'engineering' : assignee?.role ?? 'product'; void act(actor => ({ kind: 'action.assign', participant: actor, requirementId: item.requirementId, actionItemId: item.id, assigneeRole: role, ...(assignee ? { assigneeParticipantId: assignee.participantId } : {}), dueStage: item.dueStage })) }}><option value="role:product">产品角色</option><option value="role:engineering">研发角色</option>{participants.map(person => <option key={person.participantId} value={person.participantId}>{person.nickname}</option>)}</select></label><label>截止阶段<select aria-label="待办截止阶段" value={item.dueStage} onChange={event => void act(actor => ({ kind: 'action.assign', participant: actor, requirementId: item.requirementId, actionItemId: item.id, assigneeRole: item.assigneeRole, ...(item.assigneeParticipantId ? { assigneeParticipantId: item.assigneeParticipantId } : {}), dueStage: event.target.value as RequirementStage }))}>{stageSteps.map(stage => <option key={stage.stage} value={stage.stage}>{stage.label}</option>)}</select></label></div></div>)}</div></details>
|
|
368
580
|
}
|
|
369
581
|
|
|
370
582
|
type DocumentCollabStats = { openReviews: number; blockingReviews: number; openDiscussions: number; pendingPatches: number; activeDecisions: number; invalidatedDecisions: number; runningAi: number; dirty: boolean }
|
|
@@ -411,6 +623,11 @@ export function InlineCommentComposer({ selection, text, setText, busy, cancel,
|
|
|
411
623
|
}
|
|
412
624
|
|
|
413
625
|
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 }
|
|
626
|
+
function DocumentMarkerIcon({ kind, blocking }: { kind: DocumentMarker['kind']; blocking: boolean }) {
|
|
627
|
+
if (kind === 'comment') return <svg viewBox="0 0 20 20" aria-hidden="true" focusable="false"><path d="M4.2 4.5h11.6a1.7 1.7 0 0 1 1.7 1.7v6.1a1.7 1.7 0 0 1-1.7 1.7H9l-4.2 2.8V14h-.6a1.7 1.7 0 0 1-1.7-1.7V6.2a1.7 1.7 0 0 1 1.7-1.7Z" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/></svg>
|
|
628
|
+
if (blocking) return <svg viewBox="0 0 20 20" aria-hidden="true" focusable="false"><path d="M10 2.6 18 16.5H2L10 2.6Z" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/><path d="M10 7.2v4.6M10 14.4v.1" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"/></svg>
|
|
629
|
+
return <svg viewBox="0 0 20 20" aria-hidden="true" focusable="false"><circle cx="10" cy="10" r="7.4" fill="none" stroke="currentColor" strokeWidth="1.6"/><path d="M7.9 7.6a2.3 2.3 0 1 1 3.1 2.2c-.8.4-1 .9-1 1.6M10 14.3v.1" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
|
|
630
|
+
}
|
|
414
631
|
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
632
|
const shell = useRef<HTMLDivElement>(null)
|
|
416
633
|
const host = useRef<HTMLDivElement>(null)
|
|
@@ -487,7 +704,7 @@ function RichMarkdownEditor({ markdown, reviewItems, comments, documentFocus, fo
|
|
|
487
704
|
target.dataset.annotationKind = target.dataset.annotationKind === 'review' ? 'mixed' : 'comment'
|
|
488
705
|
if (selected) target.classList.add(commentSourceClass)
|
|
489
706
|
if (selected) target.dataset.annotationSelected = 'comment'
|
|
490
|
-
addMarker(target, { kind: 'comment', objectId: comment.id, label: '评', title: comment.body.trim() || comment.anchor
|
|
707
|
+
addMarker(target, { kind: 'comment', objectId: comment.id, label: '评', title: comment.body.trim() || comment.anchor?.quote.trim() || '整篇需求评论', blocking: false, selected })
|
|
491
708
|
})
|
|
492
709
|
setMarkers(nextMarkers)
|
|
493
710
|
}
|
|
@@ -569,7 +786,7 @@ function RichMarkdownEditor({ markdown, reviewItems, comments, documentFocus, fo
|
|
|
569
786
|
else window.setTimeout(updateLocatedReview, 220)
|
|
570
787
|
}, [reviewItems, comments, documentFocus, focusRequest])
|
|
571
788
|
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))}
|
|
789
|
+
{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))}><DocumentMarkerIcon kind={marker.kind} blocking={marker.blocking}/></button>)}</div></div>
|
|
573
790
|
}
|
|
574
791
|
|
|
575
792
|
type Act = (factory: (actor: ParticipantSnapshot) => CollaborationAction) => Promise<boolean>
|
|
@@ -590,6 +807,7 @@ export function ReviewPanel({ requirement, act, api, focusedItemId, openRequest,
|
|
|
590
807
|
const answeredCount = active.filter(item => item.status === 'answered').length
|
|
591
808
|
const processedCount = current.filter(item => item.status !== 'open').length
|
|
592
809
|
const currentRuns = requirement.aiRuns.filter(run => run.commit === requirement.currentCommit)
|
|
810
|
+
const currentStageSessionId = requirement.aiConversations?.find(item => item.stage === requirement.stage && item.stageCycle === requirement.stageCycle)?.sessionId
|
|
593
811
|
const openItem = (itemId: string): void => {
|
|
594
812
|
setSelectedItemId(itemId)
|
|
595
813
|
const sourceKey = [...current, ...historical].find(item => item.id === itemId)?.sourceAnchors?.[0] ? `quote-0` : undefined
|
|
@@ -603,7 +821,7 @@ export function ReviewPanel({ requirement, act, api, focusedItemId, openRequest,
|
|
|
603
821
|
}, [openRequest?.requestId])
|
|
604
822
|
return <>
|
|
605
823
|
<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>
|
|
606
|
-
{currentRuns.length > 0 && <details className={css.runHistory}><summary
|
|
824
|
+
{currentRuns.length > 0 && <details className={css.runHistory}><summary>AI 运行中心({currentRuns.length}){currentStageSessionId ? ' · 当前阶段复用 1 个会话' : ''}</summary>{currentRuns.slice().reverse().map(run => { const endedAt = ['completed', 'failed'].includes(run.status) ? run.updatedAt : Date.now(); const sharedSession = Boolean(run.sessionId && run.sessionId === currentStageSessionId); const step = run.status === 'queued' ? '等待可用执行槽' : run.status === 'running' ? sharedSession ? '复用当前阶段上下文并分析增量' : '读取工作区并核对当前正文' : run.status === 'completed' ? '检查结果已写入问题清单' : '运行中断,输入和历史结果已保留'; return <div className={css.run} key={run.id}><div><strong>{reviewKindLabel[run.kind]}</strong><span>{statusLabel[run.status] ?? run.status}</span></div><dl><div><dt>当前步骤</dt><dd>{step}</dd></div><div><dt>开始</dt><dd title={new Date(run.createdAt).toLocaleString()}>{relativeTime(run.createdAt)}</dd></div><div><dt>耗时</dt><dd>{durationText(endedAt - run.createdAt)}</dd></div></dl>{run.maturitySummary && <MarkdownBody text={run.maturitySummary}/>} {run.error && <><p className={css.chatError}>{friendlyActionError(run.error)}</p><button className={css.panelAction} onClick={() => void act(actor => ({ kind: 'review.request', participant: actor, requirementId: requirement.id, reviewKind: run.kind }))}>重试本次检查</button></>}{run.sessionId && <AiConversation api={api} requirementId={requirement.id} sessionId={run.sessionId}/>}</div>})}</details>}
|
|
607
825
|
{current.length === 0 && <div className={css.emptyPanel}><strong>等待 AI 完成检查</strong><p>检查结果会按优先级出现在这里。</p></div>}
|
|
608
826
|
{active.length > 0 && <ReviewChecklist items={active} selectedItemId={focusedItemId ?? selectedItemId} open={openItem}/>}
|
|
609
827
|
{deferred.length > 0 && <details className={css.historyGroup}><summary>保留待核对 · {deferred.length}</summary><ReviewChecklist items={deferred} selectedItemId={focusedItemId ?? selectedItemId} open={openItem}/></details>}
|
|
@@ -657,25 +875,33 @@ export function InlineReviewComposer({ item, sourceMarkdown, requirementId, posi
|
|
|
657
875
|
}}>
|
|
658
876
|
<header className={css.inlineReviewHead}>
|
|
659
877
|
<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>
|
|
878
|
+
<span className={css.inlineReviewHeadActions}><button type="button" onClick={() => void navigator.clipboard.writeText(`${location.origin}${location.pathname}#spec-collab/${requirementId}/tasks/${item.id}`)}>复制链接</button><button type="button" aria-label="关闭问题窗口" title="关闭" onClick={close}>×</button></span>
|
|
661
879
|
</header>
|
|
662
|
-
<
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
{
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
880
|
+
<div className={css.inlineReviewBody} data-dialog-scroll-region>
|
|
881
|
+
<section className={css.inlineReviewQuestion}><span>待回答</span><MarkdownBody text={item.question}/></section>
|
|
882
|
+
{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>}
|
|
883
|
+
{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 ? <>
|
|
884
|
+
{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>}
|
|
885
|
+
<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>
|
|
886
|
+
<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>
|
|
887
|
+
</> : <div className={css.decisionResponse}><span>{statusLabel[item.status] ?? item.status}</span><strong>这条记录当前不可回复</strong><p>你仍可以查看完整问题、影响和来源。</p></div>}
|
|
888
|
+
</div>
|
|
889
|
+
{canRespond && <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>}
|
|
670
890
|
</form>
|
|
671
891
|
}
|
|
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 }) {
|
|
892
|
+
export function DiscussionPanel({ requirement, notifications, focusedCommentId, onSelectComment, onLocateComment, act, api }: { requirement: RequirementView; notifications?: Notification[] | undefined; 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 }) {
|
|
893
|
+
const [filter, setFilter] = useState<'open' | 'resolved' | 'unread' | 'all'>('open'); const [sort, setSort] = useState<'document' | 'recent'>('document'); const [replyDrafts, setReplyDrafts] = useState<Record<string, string>>({}); const [directory, setDirectory] = useState<ParticipantSnapshot[]>([])
|
|
894
|
+
useEffect(() => { const request = (api as Partial<SpecApi>).directory?.(); if (request) void request.then(setDirectory, () => undefined) }, [requirement.id])
|
|
895
|
+
useEffect(() => { const focused = requirement.comments.find(item => item.id === focusedCommentId); if (focused) setFilter(focused.commit !== requirement.currentCommit ? 'all' : focused.status === 'open' ? 'open' : 'resolved') }, [focusedCommentId, requirement.id, requirement.currentCommit])
|
|
673
896
|
const locateComment = (commentId: string): void => {
|
|
674
897
|
onSelectComment?.(commentId)
|
|
675
898
|
onLocateComment?.(commentId)
|
|
676
899
|
}
|
|
677
|
-
const comments = requirement.comments.slice().sort((left, right) => Number(right.status === 'open') - Number(left.status === 'open') ||
|
|
900
|
+
const comments = requirement.comments.slice().sort((left, right) => sort === 'recent' ? right.updatedAt - left.updatedAt : Number(right.status === 'open') - Number(left.status === 'open') || left.createdAt - right.createdAt)
|
|
678
901
|
const currentComments = comments.filter(comment => comment.commit === requirement.currentCommit)
|
|
902
|
+
const unreadCommentNotifications = (notifications ?? []).filter(item => item.requirementId === requirement.id && item.objectType === 'comment' && item.readAt === undefined)
|
|
903
|
+
const unreadCommentIds = new Set(unreadCommentNotifications.map(item => item.objectId))
|
|
904
|
+
const unreadComments = currentComments.filter(comment => unreadCommentIds.has(comment.id))
|
|
679
905
|
const openComments = currentComments.filter(comment => comment.status === 'open')
|
|
680
906
|
const closedComments = currentComments.filter(comment => comment.status !== 'open')
|
|
681
907
|
const historicalComments = comments.filter(comment => comment.commit !== requirement.currentCommit)
|
|
@@ -690,21 +916,27 @@ export function DiscussionPanel({ requirement, focusedCommentId, onSelectComment
|
|
|
690
916
|
<strong>{comment.author.nickname}</strong>
|
|
691
917
|
<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
918
|
</div>
|
|
693
|
-
<button type="button" className={css.locateSourceButton} onClick={() => locateComment(comment.id)}>定位正文</button>
|
|
919
|
+
<div className={css.threadHeaderActions}>{unreadCommentIds.has(comment.id) && <button type="button" onClick={() => void act(actor => ({ kind: 'notification.mark-read', participant: actor, requirementId: requirement.id, notificationIds: unreadCommentNotifications.filter(item => item.objectId === comment.id).map(item => item.id) }))}>标为已读</button>}{comment.anchor && <button type="button" className={css.locateSourceButton} onClick={() => locateComment(comment.id)}>定位正文</button>}<button type="button" onClick={() => void navigator.clipboard.writeText(`${location.origin}${location.pathname}#spec-collab/${requirement.id}/discussion/${comment.id}`)}>复制链接</button></div>
|
|
694
920
|
</header>
|
|
695
|
-
<button type="button" className={css.commentSourceButton} onClick={() => locateComment(comment.id)}><span>{comment.anchor.heading?.trim() || '原文片段'}</span><q>{comment.anchor.quote}</q></button>
|
|
921
|
+
{comment.anchor && <button type="button" className={css.commentSourceButton} onClick={() => locateComment(comment.id)}><span>{comment.anchor.heading?.trim() || '原文片段'}</span><q>{comment.anchor.quote}</q></button>}
|
|
922
|
+
{!comment.anchor && <div className={css.commentSourceButton}><span>整篇需求</span><q>页面级总评</q></div>}
|
|
696
923
|
<MarkdownBody text={comment.body} className={css.commentBody}/>
|
|
697
924
|
{comment.aiSessionId && <AiConversation api={api} requirementId={requirement.id} sessionId={comment.aiSessionId}/>}
|
|
698
925
|
{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>}
|
|
926
|
+
{comment.status === 'open' && <div className={css.replyComposer}><label>回复评论<textarea value={replyDrafts[comment.id] ?? ''} onChange={event => setReplyDrafts(current => ({ ...current, [comment.id]: event.target.value }))} placeholder={directory.length > 0 ? `输入回复,可使用 ${directory.slice(0, 2).map(item => `@${item.nickname}`).join('、')}` : '输入回复'}/></label><button disabled={!(replyDrafts[comment.id] ?? '').trim()} onClick={() => { const body = (replyDrafts[comment.id] ?? '').trim(); const mentions = mentionedParticipantIds(body, directory); void act(actor => ({ kind: 'comment.reply', participant: actor, requirementId: requirement.id, commentId: comment.id, body, mentions })).then(ok => { if (ok) setReplyDrafts(current => ({ ...current, [comment.id]: '' })) }) }}>回复</button></div>}
|
|
699
927
|
{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>}
|
|
928
|
+
{comment.status === 'resolved' && <div className={css.commentActions}><button onClick={() => void act(actor => ({ kind: 'comment.reopen', participant: actor, requirementId: requirement.id, commentId: comment.id }))}>重新打开</button></div>}
|
|
700
929
|
</section>
|
|
701
930
|
}
|
|
702
931
|
return <div className={css.discussionPanel}>
|
|
703
|
-
<div className={css.discussionSummary}><div><strong
|
|
704
|
-
{
|
|
705
|
-
{openComments.
|
|
706
|
-
{
|
|
707
|
-
{
|
|
932
|
+
<div className={css.discussionSummary}><div><strong>统一评论</strong><span>{openComments.length > 0 ? `${openComments.length} 个当前正文问题待收口` : '当前正文没有待处理讨论'}</span></div><b>{comments.length}</b></div>
|
|
933
|
+
<div className={css.discussionFilters}><label>状态<select value={filter} onChange={event => setFilter(event.target.value as typeof filter)}><option value="open">未解决</option><option value="unread">未读</option><option value="resolved">已解决</option><option value="all">全部</option></select></label><label>排序<select value={sort} onChange={event => setSort(event.target.value as typeof sort)}><option value="document">正文顺序</option><option value="recent">最近更新</option></select></label></div>
|
|
934
|
+
{filter === 'open' && openComments.length === 0 && <div className={css.emptyPanel}><strong>没有打开的评论</strong><p>选中正文可发起行内评论,也可以使用“评论整篇”给出页面总评。</p></div>}
|
|
935
|
+
{filter === 'unread' && unreadComments.length === 0 && <div className={css.emptyPanel}><strong>没有未读评论</strong><p>新的提及、回复和重新打开会进入插件内通知。</p></div>}
|
|
936
|
+
{(filter === 'open' || filter === 'all') && openComments.map(renderThread)}
|
|
937
|
+
{filter === 'unread' && unreadComments.map(renderThread)}
|
|
938
|
+
{(filter === 'resolved' || filter === 'all') && closedComments.map(renderThread)}
|
|
939
|
+
{filter === 'all' && historicalComments.length > 0 && <details className={css.historyGroup} open={historicalComments.some(item => item.id === focusedCommentId)}><summary>历史正文讨论 · {historicalComments.length}</summary><div className={css.threadStack}>{historicalComments.map(renderThread)}</div></details>}
|
|
708
940
|
</div>
|
|
709
941
|
}
|
|
710
942
|
function AiConversation({ api, requirementId, sessionId }: { api: SpecApi; requirementId: string; sessionId: string }) {
|
|
@@ -718,9 +950,81 @@ function AiConversation({ api, requirementId, sessionId }: { api: SpecApi; requi
|
|
|
718
950
|
const send = async (): Promise<void> => { if (!draft.trim()) return; setSending(true); try { await api.followUp(requirementId, sessionId, draft); setMessages(current => [...current, { role: 'user', text: draft }]); setDraft(''); window.setTimeout(() => { void load() }, 1000) } catch (reason) { setError(reason instanceof Error ? reason.message : String(reason)) } finally { setSending(false) } }
|
|
719
951
|
return <div className={css.aiConversation}><button className={`${css.chatToggle} ${open ? css.collapseChat : ''}`} aria-label={open ? '收起智能对话' : '展开智能对话'} title={open ? '收起智能对话' : '展开智能对话'} onClick={() => setOpen(value => !value)}>{open ? '⌃' : '展开智能对话'}</button>{open && <><div className={css.chatMessages}>{messages.map((message, index) => <div key={`${message.role}-${index}`} className={message.role === 'assistant' ? css.aiMessage : css.userMessage}><strong>{message.role === 'assistant' ? '智能助手' : '你'}</strong><div dangerouslySetInnerHTML={{ __html: md.render(message.text) }}/></div>)}{messages.length === 0 && !error && <small>正在读取审核会话…</small>}</div>{error && <p className={css.chatError}>{error}</p>}<div className={css.chatComposer}><textarea required aria-label="追问内容(必填)" value={draft} onChange={event => setDraft(event.target.value)} placeholder="追问内容(必填)"/><button disabled={sending || !draft.trim()} onClick={() => void send()}>发送</button></div></>}</div>
|
|
720
952
|
}
|
|
721
|
-
|
|
953
|
+
|
|
954
|
+
type InsightData = Awaited<ReturnType<SpecApi['insights']>>
|
|
955
|
+
function InsightPanel({ requirement, api, act }: { requirement: RequirementView; api: SpecApi; act: Act }) {
|
|
956
|
+
const [data, setData] = useState<InsightData>({ items: [], total: 0, links: [], customers: [], companies: [], sources: [] })
|
|
957
|
+
const [catalog, setCatalog] = useState<InsightData>({ items: [], total: 0, links: [], customers: [], companies: [], sources: [] })
|
|
958
|
+
const [filters, setFilters] = useState<{ customerId: string; companyId: string; sourceId: string; importance: '' | keyof typeof importanceLabel }>({ customerId: '', companyId: '', sourceId: '', importance: '' })
|
|
959
|
+
const [form, setForm] = useState({ title: '', body: '', customer: '', customerRef: '', company: '', companyRef: '', source: '', url: '', importance: 'unknown' as 'unknown' | 'want' | 'important' | 'critical', targets: '' })
|
|
960
|
+
const [open, setOpen] = useState(false); const [error, setError] = useState(''); const [importPreview, setImportPreview] = useState<ReturnType<typeof parseInsightFile>>()
|
|
961
|
+
const importSummary = useMemo(() => {
|
|
962
|
+
if (!importPreview) return { added: 0, updated: 0, duplicates: 0 }
|
|
963
|
+
const sourceId = stableLocalId('source', `${importPreview.kind}:${importPreview.name}`)
|
|
964
|
+
const existing = new Set(catalog.items.filter(item => item.sourceId === sourceId).map(item => normalizeInsightBody(item.body)))
|
|
965
|
+
const seen = new Set<string>(); let duplicates = 0
|
|
966
|
+
for (const row of importPreview.rows) { const body = normalizeInsightBody(row.body); if (existing.has(body) || seen.has(body)) duplicates += 1; else seen.add(body) }
|
|
967
|
+
return { added: importPreview.rows.length - duplicates, updated: 0, duplicates }
|
|
968
|
+
}, [catalog.items, importPreview])
|
|
969
|
+
const load = (): void => { void Promise.all([api.insights({ requirementId: requirement.id }), api.insights({ requirementId: requirement.id, ...(filters.customerId ? { customerId: filters.customerId } : {}), ...(filters.companyId ? { companyId: filters.companyId } : {}), ...(filters.sourceId ? { sourceId: filters.sourceId } : {}), ...(filters.importance ? { importance: filters.importance } : {}) })]).then(([all, filtered]) => { setCatalog(all); setData(filtered) }, reason => setError(reason instanceof Error ? reason.message : String(reason))) }
|
|
970
|
+
useEffect(load, [requirement.id, requirement.metrics.insightCount, filters.customerId, filters.companyId, filters.sourceId, filters.importance])
|
|
971
|
+
const submit = async (): Promise<void> => {
|
|
972
|
+
if (!form.body.trim() || !form.source.trim()) return
|
|
973
|
+
const companyId = form.company.trim() ? stableLocalId('company', form.companyRef || form.company) : undefined
|
|
974
|
+
const customerId = form.customer.trim() ? stableLocalId('customer', form.customerRef || `${form.company}:${form.customer}`) : undefined
|
|
975
|
+
const sourceId = stableLocalId('source', form.url || form.source); const insightId = `insight-${browserUuid()}`
|
|
976
|
+
if (companyId && !await act(actor => ({ kind: 'company.upsert', participant: actor, requirementId: requirement.id, company: { id: companyId, name: form.company.trim(), ...(form.companyRef.trim() ? { externalRef: form.companyRef.trim() } : {}) } }))) return
|
|
977
|
+
if (customerId && !await act(actor => ({ kind: 'customer.upsert', participant: actor, requirementId: requirement.id, customer: { id: customerId, displayName: form.customer.trim(), ...(companyId ? { companyId } : {}), ...(form.customerRef.trim() ? { externalRef: form.customerRef.trim() } : {}) } }))) return
|
|
978
|
+
const sourceUrl = safeHttpUrl(form.url.trim())
|
|
979
|
+
if (!await act(actor => ({ kind: 'source.upsert', participant: actor, requirementId: requirement.id, source: { id: sourceId, kind: form.url.trim() ? 'url' : 'text', label: form.source.trim(), ...(sourceUrl ? { url: sourceUrl } : {}), accessStatus: form.url.trim() && !sourceUrl ? 'unverified' : 'available' } }))) return
|
|
980
|
+
const links = parseInsightTargets(form.targets, requirement.id)
|
|
981
|
+
if (await act(actor => ({ kind: 'insight.create', participant: actor, requirementId: requirement.id, insight: { id: insightId, sourceId, ...(customerId ? { customerId } : {}), ...(companyId && !customerId ? { companyId } : {}), title: form.title.trim() || truncateGraphemes(form.body.trim(), 28), body: form.body.trim(), importance: form.importance, capturedAt: Date.now() }, links }))) { setOpen(false); setForm({ title: '', body: '', customer: '', customerRef: '', company: '', companyRef: '', source: '', url: '', importance: 'unknown', targets: '' }); load() }
|
|
982
|
+
}
|
|
983
|
+
const importRows = async (): Promise<void> => {
|
|
984
|
+
if (!importPreview || importPreview.errors.length > 0) return
|
|
985
|
+
const defaultSourceId = stableLocalId('source', `${importPreview.kind}:${importPreview.name}`); const sources = new Map<string, { id: string; kind: 'url' | 'csv' | 'markdown'; label: string; url?: string; accessStatus: 'available' | 'unverified' }>(); const companies = new Map<string, { id: string; name: string; externalRef?: string }>(); const customers = new Map<string, { id: string; displayName: string; companyId?: string; externalRef?: string }>()
|
|
986
|
+
sources.set(defaultSourceId, { id: defaultSourceId, kind: importPreview.kind, label: importPreview.name, accessStatus: 'available' })
|
|
987
|
+
const links: Array<{ insightId: string; requirementId: string; targetType: 'requirement' | 'section' | 'acceptance-criterion'; targetId?: string }> = []
|
|
988
|
+
const rows = importPreview.rows.map((row, index) => {
|
|
989
|
+
const companyId = row.company ? stableLocalId('company', row.companyRef || row.company) : undefined; const customerId = row.customer ? stableLocalId('customer', row.customerRef || `${row.company}:${row.customer}`) : undefined
|
|
990
|
+
if (companyId) companies.set(companyId, { id: companyId, name: row.company!, ...(row.companyRef ? { externalRef: row.companyRef } : {}) }); if (customerId) customers.set(customerId, { id: customerId, displayName: row.customer!, ...(companyId ? { companyId } : {}), ...(row.customerRef ? { externalRef: row.customerRef } : {}) })
|
|
991
|
+
const sourceUrl = safeHttpUrl(row.sourceUrl ?? ''); const sourceLabel = row.source?.trim() || row.sourceUrl?.trim(); const sourceId = sourceLabel ? stableLocalId('source', sourceUrl || sourceLabel) : defaultSourceId
|
|
992
|
+
if (sourceLabel) sources.set(sourceId, { id: sourceId, kind: sourceUrl ? 'url' : importPreview.kind, label: row.source?.trim() || sourceUrl || sourceLabel, ...(sourceUrl ? { url: sourceUrl } : {}), accessStatus: sourceUrl || !row.sourceUrl ? 'available' : 'unverified' })
|
|
993
|
+
const id = `insight-${browserUuid()}-${index}`; links.push(...parseInsightTargets(row.targets?.join(',') ?? '', requirement.id).map(link => ({ insightId: id, ...link })))
|
|
994
|
+
return { id, sourceId, ...(customerId ? { customerId } : {}), ...(companyId && !customerId ? { companyId } : {}), title: row.title || truncateGraphemes(row.body, 28), body: row.body, importance: row.importance, capturedAt: row.capturedAt ?? Date.now() }
|
|
995
|
+
})
|
|
996
|
+
if (await act(actor => ({ kind: 'insight.import', participant: actor, requirementId: requirement.id, sources: [...sources.values()], companies: [...companies.values()], customers: [...customers.values()], rows, links }))) { setImportPreview(undefined); load() }
|
|
997
|
+
}
|
|
998
|
+
return <div className={css.insightPanel}><div className={css.insightScore}><div><span>客户重要度分</span><b>{requirement.metrics.customerImportanceScore}</b></div><dl><div><dt>洞察</dt><dd>{requirement.metrics.insightCount}</dd></div><div><dt>客户</dt><dd>{requirement.metrics.customerCount}</dd></div><div><dt>公司</dt><dd>{requirement.metrics.companyCount}</dd></div><div><dt>匿名</dt><dd>{requirement.metrics.anonymousInsightCount}</dd></div></dl></div><div className={css.insightFilters}><label>客户<select value={filters.customerId} onChange={event => setFilters(current => ({ ...current, customerId: event.target.value }))}><option value="">全部</option>{catalog.customers.map(item => <option key={item.id} value={item.id}>{item.displayName}</option>)}</select></label><label>公司<select value={filters.companyId} onChange={event => setFilters(current => ({ ...current, companyId: event.target.value }))}><option value="">全部</option>{catalog.companies.map(item => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label><label>来源<select value={filters.sourceId} onChange={event => setFilters(current => ({ ...current, sourceId: event.target.value }))}><option value="">全部</option>{catalog.sources.map(item => <option key={item.id} value={item.id}>{item.label}</option>)}</select></label><label>重要度<select value={filters.importance} onChange={event => setFilters(current => ({ ...current, importance: event.target.value as typeof current.importance }))}><option value="">全部</option>{Object.entries(importanceLabel).map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select></label></div><div className={css.insightActions}><button className={css.execute} onClick={() => setOpen(true)}>记录客户洞察</button><label className={css.fileButton}>导入 CSV / Markdown<input type="file" accept=".csv,.md,.markdown,text/csv,text/markdown" onChange={event => { const file = event.target.files?.[0]; if (!file) return; if (file.size > 5 * 1024 * 1024) { setError('文件超过 5 MB'); return } void file.text().then(text => setImportPreview(parseInsightFile(file.name, text))) }}/></label></div>{error && <p className={css.chatError}>{error}</p>}{importPreview && <section className={css.importPreview}><header><div><strong>{importPreview.name}</strong><span>新增 {importSummary.added} · 更新 {importSummary.updated} · 重复 {importSummary.duplicates} · 错误 {importPreview.errors.length}</span></div><button onClick={() => setImportPreview(undefined)}>取消</button></header>{importPreview.errors.map(errorText => <p key={errorText}>{errorText}</p>)}<div>{importPreview.rows.slice(0, 5).map((row, index) => <article key={index}><b>{row.title || truncateGraphemes(row.body, 24)}</b><span>{row.customer || '匿名'} · {importanceLabel[row.importance]}{row.targets?.length ? ` · ${row.targets.length} 个关联` : ''}</span></article>)}</div><button className={css.execute} disabled={importPreview.errors.length > 0 || importPreview.rows.length === 0} onClick={() => void importRows()}>确认原子导入</button></section>}{data.items.length === 0 && <div className={css.emptyPanel}><strong>没有符合条件的客户证据</strong><p>清除筛选,或记录客户原声并把它连接到需求、规则和验收标准。</p></div>}{data.items.map(insight => { const source = data.sources.find(item => item.id === insight.sourceId) ?? catalog.sources.find(item => item.id === insight.sourceId); const customer = data.customers.find(item => item.id === insight.customerId) ?? catalog.customers.find(item => item.id === insight.customerId); const company = data.companies.find(item => item.id === (insight.companyId ?? customer?.companyId)) ?? catalog.companies.find(item => item.id === (insight.companyId ?? customer?.companyId)); return <article id={`spec-object-${insight.id}`} className={css.insightCard} key={insight.id}><header><span>{importanceLabel[insight.importance]}</span><time title={new Date(insight.capturedAt).toLocaleString()}>{relativeTime(insight.capturedAt)}</time></header><h3>{insight.title}</h3><blockquote>{insight.body}</blockquote><footer><span>{customer?.displayName ?? '匿名客户'}{company ? ` · ${company.name}` : ''}</span>{source?.url && safeHttpUrl(source.url) ? <a href={source.url} target="_blank" rel="noreferrer">{source.label}</a> : <code>{source?.label ?? insight.sourceId}</code>}</footer><div className={css.insightLinks}>{data.links.filter(link => link.insightId === insight.id).map(link => <span key={link.id}>{link.targetType === 'requirement' ? '需求' : link.targetId}<button aria-label={`取消关联 ${link.targetId ?? '需求'}`} onClick={() => void act(actor => ({ kind: 'insight.unlink', participant: actor, requirementId: requirement.id, linkId: link.id })).then(ok => { if (ok) load() })}>×</button></span>)}<button onClick={() => { void navigator.clipboard.writeText(`${location.origin}${location.pathname}#spec-collab/${requirement.id}/insights/${insight.id}`) }}>复制链接</button></div></article>})}{open && <AccessibleDialog title="记录客户洞察" close={() => setOpen(false)} className={css.insightDialog}><form onSubmit={event => { event.preventDefault(); void submit() }}><div className={css.dialogHead}><div><span>客户证据</span><h2>记录客户洞察</h2></div><button type="button" aria-label="关闭" onClick={() => setOpen(false)}>×</button></div><label>洞察正文(必填)<textarea autoFocus required value={form.body} onChange={event => setForm({ ...form, body: event.target.value })} placeholder="保留客户原话或可核对的观察"/></label><div className={css.formGrid}><label>标题<input value={form.title} onChange={event => setForm({ ...form, title: event.target.value })}/></label><label>重要度<select value={form.importance} onChange={event => setForm({ ...form, importance: event.target.value as typeof form.importance })}>{Object.entries(importanceLabel).map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select></label></div><div className={css.formGrid}><label>客户显示名<input value={form.customer} onChange={event => setForm({ ...form, customer: event.target.value })}/></label><label>客户外部编号<input value={form.customerRef} onChange={event => setForm({ ...form, customerRef: event.target.value })}/></label><label>公司<input value={form.company} onChange={event => setForm({ ...form, company: event.target.value })}/></label><label>公司外部编号<input value={form.companyRef} onChange={event => setForm({ ...form, companyRef: event.target.value })}/></label></div><div className={css.formGrid}><label>来源名称(必填)<input required value={form.source} onChange={event => setForm({ ...form, source: event.target.value })}/></label><label>来源 URL(选填,仅 http/https)<input type="url" value={form.url} onChange={event => setForm({ ...form, url: event.target.value })}/></label></div><label>关联目标(逗号分隔)<input value={form.targets} onChange={event => setForm({ ...form, targets: event.target.value })} placeholder="section:业务规则, ac:AC-2, requirement:需求编号"/><small>当前需求会自动关联;可追加多个需求、章节或验收标准。</small></label><div className={css.stickyActions}><button type="button" onClick={() => setOpen(false)}>取消</button><button className={css.execute} disabled={!form.body.trim() || !form.source.trim()}>保存洞察</button></div></form></AccessibleDialog>}</div>
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
const importanceLabel = { unknown: '未标注', want: '想要', important: '重要', critical: '关键' } as const
|
|
1002
|
+
type ImportedInsight = { title?: string; body: string; customer?: string; customerRef?: string; company?: string; companyRef?: string; source?: string; sourceUrl?: string; importance: keyof typeof importanceLabel; capturedAt?: number; targets?: string[] }
|
|
1003
|
+
function normalizeInsightBody(value: string): string { return value.normalize('NFKC').trim().replace(/\s+/g, ' ').toLocaleLowerCase() }
|
|
1004
|
+
function stableLocalId(prefix: string, value: string): string { let hash = 2166136261; for (const character of value.normalize('NFKC').toLocaleLowerCase()) { hash ^= character.codePointAt(0) ?? 0; hash = Math.imul(hash, 16777619) } return `${prefix}-${(hash >>> 0).toString(16)}` }
|
|
1005
|
+
function parseInsightTargets(value: string, currentRequirementId: string): Array<{ requirementId: string; targetType: 'requirement' | 'section' | 'acceptance-criterion'; targetId?: string }> { return value.split(/[,,;;\n]/).map(item => item.trim()).filter(Boolean).map(item => { const [rawType = '', ...rest] = item.split(':'); const targetId = rest.join(':').trim(); const type = rawType.trim().toLocaleLowerCase(); if ((type === 'requirement' || type === '需求') && targetId) return { requirementId: targetId, targetType: 'requirement' as const }; if ((type === 'ac' || type === '验收') && targetId) return { requirementId: currentRequirementId, targetType: 'acceptance-criterion' as const, targetId }; if ((type === 'section' || type === '章节') && targetId) return { requirementId: currentRequirementId, targetType: 'section' as const, targetId }; return { requirementId: currentRequirementId, targetType: 'section' as const, targetId: item } }) }
|
|
1006
|
+
export function parseInsightFile(name: string, text = ''): { name: string; kind: 'csv' | 'markdown'; rows: ImportedInsight[]; errors: string[] } {
|
|
1007
|
+
const kind = name.toLocaleLowerCase().endsWith('.csv') ? 'csv' : 'markdown'; const rows: ImportedInsight[] = []; const errors: string[] = []
|
|
1008
|
+
if (kind === 'markdown') {
|
|
1009
|
+
const sections = text.split(/^##\s+/m).slice(1)
|
|
1010
|
+
for (const [index, section] of sections.entries()) { const [heading = '', ...bodyLines] = section.split('\n'); const metadataLine = /^[-*]\s*(客户|客户编号|公司|公司编号|重要度|来源|来源 URL|关联目标)\s*[::]/; const metadata = new Map(bodyLines.filter(line => metadataLine.test(line)).map(line => { const match = /^[-*]\s*([^::]+)\s*[::]\s*(.*)$/.exec(line)!; return [match[1]!.trim(), match[2]!.trim()] })); const body = bodyLines.filter(line => !metadataLine.test(line)).join('\n').trim(); if (!body) { errors.push(`第 ${index + 1} 个 Markdown 小节缺少正文`); continue } const customer = metadata.get('客户'); const customerRef = metadata.get('客户编号'); const company = metadata.get('公司'); const companyRef = metadata.get('公司编号'); const source = metadata.get('来源'); const sourceUrl = metadata.get('来源 URL'); const targets = metadata.get('关联目标')?.split(/[,,;;]/).map(value => value.trim()).filter(Boolean); rows.push({ title: heading.trim(), body, ...(customer ? { customer } : {}), ...(customerRef ? { customerRef } : {}), ...(company ? { company } : {}), ...(companyRef ? { companyRef } : {}), ...(source ? { source } : {}), ...(sourceUrl ? { sourceUrl } : {}), importance: parseImportance(metadata.get('重要度')), ...(targets?.length ? { targets } : {}) }) }
|
|
1011
|
+
} else {
|
|
1012
|
+
const records = parseCsvRecords(text.replace(/^\uFEFF/, '')); const headers = (records.shift() ?? []).map(value => value.trim().toLocaleLowerCase()); const bodyIndex = headers.indexOf('body')
|
|
1013
|
+
if (bodyIndex < 0) errors.push('CSV 缺少必填列 body')
|
|
1014
|
+
for (const [index, values] of records.entries()) { const value = (key: string): string => values[headers.indexOf(key)]?.trim() ?? ''; const body = values[bodyIndex]?.trim() ?? ''; if (!body) { errors.push(`CSV 第 ${index + 2} 条记录缺少 body`); continue } const targets = (value('targets') || value('target')).split(/[;;]/).map(item => item.trim()).filter(Boolean); const customerRef = value('customer_external_ref') || value('customer_ref'); const companyRef = value('company_external_ref') || value('company_ref'); const source = value('source'); const sourceUrl = value('source_url') || value('url'); rows.push({ ...(value('title') ? { title: value('title') } : {}), body, ...(value('customer') ? { customer: value('customer') } : {}), ...(customerRef ? { customerRef } : {}), ...(value('company') ? { company: value('company') } : {}), ...(companyRef ? { companyRef } : {}), ...(source ? { source } : {}), ...(sourceUrl ? { sourceUrl } : {}), importance: parseImportance(value('importance')), ...(Number.isFinite(Date.parse(value('captured_at'))) ? { capturedAt: Date.parse(value('captured_at')) } : {}), ...(targets.length ? { targets } : {}) }) }
|
|
1015
|
+
}
|
|
1016
|
+
if (rows.length > 2_000) errors.push('最多导入 2,000 条洞察')
|
|
1017
|
+
return { name, kind, rows: rows.slice(0, 2_000), errors }
|
|
1018
|
+
}
|
|
1019
|
+
function parseCsvLine(line: string): string[] { const values: string[] = []; let value = ''; let quoted = false; for (let index = 0; index < line.length; index += 1) { const char = line[index]!; if (char === '"' && quoted && line[index + 1] === '"') { value += '"'; index += 1 } else if (char === '"') quoted = !quoted; else if (char === ',' && !quoted) { values.push(value); value = '' } else value += char } values.push(value); return values }
|
|
1020
|
+
function parseCsvRecords(text: string): string[][] { const records: string[][] = []; let record = ''; let quoted = false; for (let index = 0; index < text.length; index += 1) { const char = text[index]!; if (char === '"') { record += char; if (quoted && text[index + 1] === '"') { record += text[index + 1]; index += 1 } else quoted = !quoted } else if ((char === '\n' || char === '\r') && !quoted) { if (char === '\r' && text[index + 1] === '\n') index += 1; if (record.trim()) records.push(parseCsvLine(record)); record = '' } else record += char } if (record.trim()) records.push(parseCsvLine(record)); return records }
|
|
1021
|
+
function parseImportance(value: string | undefined): keyof typeof importanceLabel { const normalized = value?.trim().toLocaleLowerCase(); return normalized === 'critical' || normalized === '关键' ? 'critical' : normalized === 'important' || normalized === '重要' ? 'important' : normalized === 'want' || normalized === '想要' ? 'want' : 'unknown' }
|
|
1022
|
+
|
|
1023
|
+
function PatchPanel({ requirement, act, api }: { requirement: RequirementView; act: Act; api: SpecApi }) {
|
|
722
1024
|
const [summaries, setSummaries] = useState<Record<string, string>>({})
|
|
723
1025
|
const [submitting, setSubmitting] = useState<string>()
|
|
1026
|
+
const [reviewing, setReviewing] = useState<{ patchId: string; diff: StructuredDiff }>()
|
|
1027
|
+
const [diffError, setDiffError] = useState('')
|
|
724
1028
|
const current = requirement.patches.filter(patch => patch.baseCommit === requirement.currentCommit && patch.status === 'pending').slice().reverse()
|
|
725
1029
|
const historical = requirement.patches.filter(patch => !current.some(item => item.id === patch.id)).slice().reverse()
|
|
726
1030
|
const renderPatch = (patch: RequirementView['patches'][number]) => {
|
|
@@ -729,27 +1033,47 @@ function PatchPanel({ requirement, act }: { requirement: RequirementView; act: A
|
|
|
729
1033
|
return <article id={`spec-object-${patch.id}`} className={css.reviewCard} key={patch.id}>
|
|
730
1034
|
<div className={css.badges}><b>{statusLabel[patch.status] ?? patch.status}</b><span>{reviewKindLabel[patch.reviewKind]}</span></div>
|
|
731
1035
|
<MarkdownBody text={patch.summary} className={css.reviewTitle}/>
|
|
1036
|
+
<dl className={css.patchImpact}><div><dt>影响章节</dt><dd>{patch.affectedSections.length > 0 ? patch.affectedSections.join('、') : '未标注'}</dd></div><div><dt>验收项</dt><dd>{patch.affectedAcceptanceIds.length > 0 ? patch.affectedAcceptanceIds.join('、') : '无'}</dd></div><div><dt>修改规模</dt><dd>{Math.abs(patch.proposedMarkdown.length - requirement.version.markdown.length)} 字符净变化</dd></div><div><dt>冲突风险</dt><dd>{patch.baseCommit === requirement.currentCommit ? '基线一致,可原子接受' : '基线已变化,禁止接受'}</dd></div></dl>
|
|
732
1037
|
{!chinese && <div className={css.legacyWarning}><strong>旧建议无法使用</strong><p>这份建议生成于中文约束启用前,请重新运行 AI 检查。</p></div>}
|
|
733
|
-
<
|
|
1038
|
+
<button className={css.panelAction} onClick={async () => { setDiffError(''); try { setReviewing({ patchId: patch.id, diff: await api.previewDiff(requirement.version.markdown, patch.proposedMarkdown, `基线 ${patch.baseCommit.slice(0, 8)}`, 'AI 建议') }) } catch (error) { setDiffError(error instanceof Error ? error.message : String(error)) } }}>审核全部改动</button>
|
|
734
1039
|
{patch.status === 'pending' && (chinese ? <div className={css.patchAccept}><label>版本说明<input required value={commitSummary} onChange={event => setSummaries(currentValues => ({ ...currentValues, [patch.id]: event.target.value }))}/></label><div className={css.cardActions}><button className={css.execute} disabled={submitting === patch.id || !commitSummary.trim()} onClick={async () => { setSubmitting(patch.id); try { await act(actor => ({ kind: 'patch.accept', participant: actor, requirementId: requirement.id, patchId: patch.id, summary: commitSummary })) } finally { setSubmitting(undefined) } }}>{submitting === patch.id ? '正在写入…' : '接受并写入正文'}</button><button disabled={submitting === patch.id} onClick={() => void act(actor => ({ kind: 'patch.reject', participant: actor, requirementId: requirement.id, patchId: patch.id }))}>不采用</button></div></div> : <div className={css.cardActions}><button onClick={() => void act(actor => ({ kind: 'review.request', participant: actor, requirementId: requirement.id, reviewKind: patch.reviewKind }))}>重新生成建议</button><button onClick={() => void act(actor => ({ kind: 'patch.reject', participant: actor, requirementId: requirement.id, patchId: patch.id }))}>废弃旧建议</button></div>)}
|
|
735
1040
|
</article>
|
|
736
1041
|
}
|
|
737
|
-
return <>{current.length === 0 && <div className={css.emptyPanel}><strong>当前没有需要审核的 AI 建议</strong><p>AI 根据你的回答整理正文后,建议会出现在这里。</p></div>}{current.map(renderPatch)}{historical.length > 0 && <details className={css.historyGroup}><summary>历史建议 · {historical.length}</summary><div>{historical.map(renderPatch)}</div></details>}</>
|
|
1042
|
+
return <>{diffError && <p className={css.chatError}>{diffError}</p>}{current.length === 0 && <div className={css.emptyPanel}><strong>当前没有需要审核的 AI 建议</strong><p>AI 根据你的回答整理正文后,建议会出现在这里。</p></div>}{current.map(renderPatch)}{historical.length > 0 && <details className={css.historyGroup}><summary>历史建议 · {historical.length}</summary><div>{historical.map(renderPatch)}</div></details>}{reviewing && <AccessibleDialog title="审核 AI 建议差异" close={() => setReviewing(undefined)} className={css.diffDialog}><div className={css.diffHeader}><div><span>整包原子接受</span><h2>审核 AI 建议的全部改动</h2></div><button aria-label="关闭差异" onClick={() => setReviewing(undefined)}>×</button></div><StructuredDiffView diff={reviewing.diff}/><div className={css.diffActions}><button onClick={() => setReviewing(undefined)}>继续检查</button><button className={css.execute} onClick={() => { const patch = current.find(item => item.id === reviewing.patchId); if (!patch) return; const summary = summaries[patch.id] ?? `合入 AI 建议:${patch.summary}`; void act(actor => ({ kind: 'patch.accept', participant: actor, requirementId: requirement.id, patchId: patch.id, summary })).then(ok => { if (ok) setReviewing(undefined) }) }}>整包接受并保存</button></div></AccessibleDialog>}</>
|
|
738
1043
|
}
|
|
739
1044
|
function DecisionPanel({ requirement, act }: { requirement: RequirementView; act: Act }) {
|
|
740
1045
|
const [open, setOpen] = useState(false)
|
|
1046
|
+
const formRef = useRef<HTMLDivElement>(null)
|
|
741
1047
|
const [form, setForm] = useState({ question: '', decision: '', rationale: '', sections: '', acceptanceIds: '' })
|
|
742
1048
|
const affectedSections = form.sections.split(',').map(value => value.trim()).filter(Boolean)
|
|
743
1049
|
const affectedAcceptanceIds = form.acceptanceIds.split(',').map(value => value.trim()).filter(Boolean)
|
|
1050
|
+
useEffect(() => {
|
|
1051
|
+
if (!open) return
|
|
1052
|
+
const behavior = window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth'
|
|
1053
|
+
const frame = window.requestAnimationFrame(() => formRef.current?.scrollIntoView({ block: 'start', behavior }))
|
|
1054
|
+
return () => window.cancelAnimationFrame(frame)
|
|
1055
|
+
}, [open])
|
|
744
1056
|
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
|
|
1057
|
+
return <>{requirement.decisions.length === 0 && !open && <div className={css.emptyPanel}><strong>还没有需要长期保留的决策</strong><p>当评论形成明确取舍、例外或边界时,把它记录为决策,避免版本变化后丢失上下文。</p><button className={css.execute} onClick={() => setOpen(true)}>记录第一个决策</button></div>}{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 title={new Date(item.createdAt).toLocaleString()}>{item.rationale} · {item.confirmer.nickname} · {relativeTime(item.createdAt)} · {item.status === 'active' ? '生效中' : '已作废'}</small><button className={css.recordLinkButton} onClick={() => void navigator.clipboard.writeText(`${location.origin}${location.pathname}#spec-collab/${requirement.id}/records/${item.id}?commit=${item.commit}`)}>复制链接</button></section>)}{open ? <div ref={formRef} className={css.decisionForm}><label>待决策问题(必填)<textarea rows={2} required autoFocus value={form.question} onChange={event => setForm({ ...form, question: event.target.value })}/></label><label>确认结论(必填)<textarea rows={3} required value={form.decision} onChange={event => setForm({ ...form, decision: event.target.value })}/></label><label>决策理由(选填)<textarea rows={2} value={form.rationale} onChange={event => setForm({ ...form, rationale: event.target.value })}/></label><label>受影响章节(与 AC 至少填写一项)<input list="decision-sections" value={form.sections} onChange={event => setForm({ ...form, sections: event.target.value })} placeholder="业务术语与规则"/><datalist id="decision-sections">{[...requirement.version.markdown.matchAll(/^##\s+(.+)$/gm)].map(match => <option key={match[1]} value={match[1]}/>)}</datalist></label><label>受影响 AC IDs(与章节至少填写一项)<input value={form.acceptanceIds} onChange={event => setForm({ ...form, acceptanceIds: event.target.value })} placeholder="AC-RETRY-001"/></label><div className={css.stickyActions}><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> : requirement.decisions.length > 0 && <button className={css.panelAction} onClick={() => setOpen(true)}>记录新决策</button>}</>
|
|
746
1058
|
}
|
|
747
|
-
function VersionPanel({ requirement, api }: { requirement: RequirementView; api: SpecApi }) {
|
|
748
|
-
const
|
|
1059
|
+
function VersionPanel({ requirement, api, act }: { requirement: RequirementView; api: SpecApi; act: Act }) {
|
|
1060
|
+
const previous = requirement.history.find(version => version.commit !== requirement.currentCommit)?.commit ?? requirement.currentCommit
|
|
1061
|
+
const [baseCommit, setBaseCommit] = useState(previous)
|
|
1062
|
+
const [headCommit, setHeadCommit] = useState(requirement.currentCommit)
|
|
1063
|
+
const [comparison, setComparison] = useState<StructuredDiff>()
|
|
749
1064
|
const [loading, setLoading] = useState(false)
|
|
750
1065
|
const [error, setError] = useState('')
|
|
751
|
-
const
|
|
752
|
-
|
|
1066
|
+
const [restoreCommit, setRestoreCommit] = useState<string>()
|
|
1067
|
+
const compare = async (): Promise<void> => { if (baseCommit === headCommit) return; setLoading(true); setError(''); try { setComparison(await api.diff(requirement.id, baseCommit, headCommit)) } catch (reason) { setError(reason instanceof Error ? reason.message : String(reason)) } finally { setLoading(false) } }
|
|
1068
|
+
const restore = async (): Promise<void> => { if (!restoreCommit) return; if (await act(actor => ({ kind: 'version.restore', participant: actor, requirementId: requirement.id, commit: restoreCommit, summary: `恢复版本 ${restoreCommit.slice(0, 8)}` }))) setRestoreCommit(undefined) }
|
|
1069
|
+
return <><div className={css.versionPicker}><label>基准版本<select value={baseCommit} onChange={event => setBaseCommit(event.target.value)}>{requirement.history.map(version => <option key={version.commit} value={version.commit}>{version.commit === requirement.currentCommit ? '当前 · ' : ''}{version.commit.slice(0, 8)} · {cleanDisplayText(version.summary)}</option>)}</select></label><label>对比版本<select value={headCommit} onChange={event => setHeadCommit(event.target.value)}>{requirement.history.map(version => <option key={version.commit} value={version.commit}>{version.commit === requirement.currentCommit ? '当前 · ' : ''}{version.commit.slice(0, 8)} · {cleanDisplayText(version.summary)}</option>)}</select></label><button className={css.execute} disabled={loading || baseCommit === headCommit} onClick={() => void compare()}>{loading ? '生成中…' : '比较差异'}</button></div>{error && <p className={css.chatError}>{error}</p>}{requirement.history.map(version => <div id={`spec-object-${version.commit}`} className={css.versionRow} key={version.commit} aria-current={version.commit === requirement.currentCommit ? 'true' : undefined}><div className={css.versionCopy}><code>{version.commit.slice(0, 10)}</code><span>{cleanDisplayText(version.summary)}</span><small title={new Date(version.createdAt).toLocaleString()}>{version.author.nickname} · {relativeTime(version.createdAt)}</small></div><div className={css.versionActions}><button onClick={() => void navigator.clipboard.writeText(`${location.origin}${location.pathname}#spec-collab/${requirement.id}/records/${version.commit}?commit=${version.commit}`)}>复制链接</button><button disabled={version.commit === requirement.currentCommit} onClick={() => setRestoreCommit(version.commit)}>{version.commit === requirement.currentCommit ? '当前版本' : '恢复为新版本'}</button></div></div>)}{comparison && <AccessibleDialog title="版本差异" close={() => setComparison(undefined)} className={css.diffDialog}><div className={css.diffHeader}><div><span>版本历史</span><h2>比较两个版本</h2></div><button aria-label="关闭版本差异" onClick={() => setComparison(undefined)}>×</button></div><StructuredDiffView diff={comparison}/><div className={css.diffActions}><button onClick={() => setComparison(undefined)}>关闭</button></div></AccessibleDialog>}{restoreCommit && <AccessibleDialog title="恢复历史版本" close={() => setRestoreCommit(undefined)} className={css.dialogSurface}><div className={css.dialogForm}><div className={css.dialogHead}><div><span>可追溯恢复</span><h2>恢复 {restoreCommit.slice(0, 8)} 为新版本?</h2></div><button aria-label="关闭" onClick={() => setRestoreCommit(undefined)}>×</button></div><p>系统会创建新的 Git commit,不移动或重写历史。受正文变化影响的确认、决策与 AI 建议将按现有规则失效。</p><div className={css.stickyActions}><button onClick={() => setRestoreCommit(undefined)}>取消</button><button className={css.dangerButton} onClick={() => void restore()}>确认恢复并创建版本</button></div></div></AccessibleDialog>}</>
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
function StructuredDiffView({ diff }: { diff: StructuredDiff }) {
|
|
1073
|
+
const [expanded, setExpanded] = useState<Set<string>>(() => new Set())
|
|
1074
|
+
const toggle = (key: string): void => setExpanded(current => { const next = new Set(current); if (next.has(key)) next.delete(key); else next.add(key); return next })
|
|
1075
|
+
const lines = (items: StructuredDiff['hunks'][number]['lines'], key: string) => items.map((line, index) => <div key={`${key}-${index}`} className={line.type === 'added' ? css.diffAdded : line.type === 'removed' ? css.diffRemoved : css.diffContext}><span>{line.oldLine ?? ''}</span><span>{line.newLine ?? ''}</span><b aria-hidden="true">{line.type === 'added' ? '+' : line.type === 'removed' ? '−' : ' '}</b><code>{line.text || ' '}</code></div>)
|
|
1076
|
+
return <div className={css.structuredDiff}><header><code>{diff.baseLabel}</code><span>→</span><code>{diff.headLabel}</code><b>+{diff.added} / −{diff.removed}</b></header>{diff.hunks.length === 0 ? <div className={css.emptyPanel}>两个版本没有正文差异。</div> : diff.hunks.map(hunk => { const beforeKey = `${hunk.id}:before`; const afterKey = `${hunk.id}:after`; return <section key={hunk.id}>{hunk.collapsedBefore > 0 && (expanded.has(beforeKey) ? <><button className={css.diffCollapsed} onClick={() => toggle(beforeKey)}>收起 {hunk.collapsedBefore} 行上下文</button>{lines(hunk.collapsedBeforeLines, beforeKey)}</> : <button className={css.diffCollapsed} onClick={() => toggle(beforeKey)}>展开前方 {hunk.collapsedBefore} 行未变内容</button>)}{lines(hunk.lines, hunk.id)}{hunk.collapsedAfter > 0 && (expanded.has(afterKey) ? <>{lines(hunk.collapsedAfterLines, afterKey)}<button className={css.diffCollapsed} onClick={() => toggle(afterKey)}>收起 {hunk.collapsedAfter} 行上下文</button></> : <button className={css.diffCollapsed} onClick={() => toggle(afterKey)}>展开后方 {hunk.collapsedAfter} 行未变内容</button>)}</section> })}</div>
|
|
753
1077
|
}
|
|
754
1078
|
const readinessLabel: Record<string, string> = { goal: '目标与用户结果', acceptance: '验收标准', scope: '范围与非范围', semantics: '业务语义', evidence: '证据来源', 'test-constraints': '测试约束' }
|
|
755
1079
|
function ReadyPanel({ requirement, act }: { requirement: RequirementView; act: Act }) {
|
|
@@ -760,13 +1084,378 @@ function ReadyPanel({ requirement, act }: { requirement: RequirementView; act: A
|
|
|
760
1084
|
if (ok) { setReturnOpen(false); setForm({ summary: '', sections: '', acceptanceIds: '', source: '', version: '', evidence: '' }) }
|
|
761
1085
|
}
|
|
762
1086
|
const passed = requirement.readiness.filter(check => check.passed).length
|
|
763
|
-
return <><div className={css.readyHead}><h3>交付条件</h3><span>{passed} / {requirement.readiness.length} 已满足</span></div><div className={css.checklist}>{requirement.readiness.map(check => <section className={`${css.checkItem} ${check.passed ? css.checkPassed : css.checkBlocked}`} key={check.key}><span className={css.checkIcon} aria-hidden="true">{check.passed ? '✓' : '!'}</span><div><strong>{readinessLabel[check.key] ?? check.key}</strong><small>{check.passed ? '已满足' : '需要补充'}</small>{check.reasons.map(reason => <MarkdownBody key={reason} text={reason}/>)}</div></section>)}</div>{requirement.readyPackage && <section><
|
|
1087
|
+
return <><div className={css.readyHead}><h3>交付条件</h3><span>{passed} / {requirement.readiness.length} 已满足</span></div><div className={css.checklist}>{requirement.readiness.map(check => <section className={`${css.checkItem} ${check.passed ? css.checkPassed : css.checkBlocked}`} key={check.key}><span className={css.checkIcon} aria-hidden="true">{check.passed ? '✓' : '!'}</span><div><strong>{readinessLabel[check.key] ?? check.key}</strong><small>{check.passed ? '已满足' : '需要补充'}</small>{check.reasons.map(reason => <MarkdownBody key={reason} text={reason}/>)}</div></section>)}</div>{requirement.readyPackage && <section className={css.readyPackage} data-ready-package><div className={css.readyPackageHead}><div><span>就绪需求</span><strong>{requirement.readyPackage.packageHash.slice(0, 12)}</strong></div><div><button onClick={() => void navigator.clipboard.writeText(requirement.readyPackage!.markdown)}>复制 Markdown</button><button onClick={() => downloadText(`${requirement.id}.md`, requirement.readyPackage!.markdown)}>下载 .md</button><button onClick={() => void navigator.clipboard.writeText(requirement.readyPackage!.commit)}>复制 commit</button>{requirement.commitUrl && <a href={requirement.commitUrl} target="_blank" rel="noreferrer">打开 commit</a>}<button onClick={() => void navigator.clipboard.writeText(`${location.origin}${location.pathname}#spec-collab/${requirement.id}/tasks/${requirement.id}?commit=${requirement.readyPackage!.commit}`)}>复制分享链接</button></div></div><MarkdownBody text={requirement.readyPackage.markdown}/></section>}{requirement.stage === 'ready' && <section className={css.downstreamReturn}><button onClick={() => setReturnOpen(value => !value)}>{returnOpen ? '取消返回问题' : '反馈研发阶段发现的问题'}</button>{returnOpen && <div><label>问题摘要(必填)<textarea required value={form.summary} onChange={event => setForm({ ...form, summary: event.target.value })} placeholder="描述研发阶段发现的产品语义或验收问题"/></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><label>依据来源(选填)<input value={form.source} onChange={event => setForm({ ...form, source: event.target.value })} placeholder="测试报告、Issue 或代码位置"/></label><label>依据版本(选填)<input value={form.version} onChange={event => setForm({ ...form, version: event.target.value })} placeholder="commit SHA 或版本号"/></label><label>依据说明(选填)<textarea value={form.evidence} onChange={event => setForm({ ...form, evidence: event.target.value })}/></label><button className={css.execute} disabled={!form.summary.trim() || (!form.sections.trim() && !form.acceptanceIds.trim())} onClick={() => void submitReturn()}>重新打开受影响内容</button></div>}</section>}</>
|
|
764
1088
|
}
|
|
765
1089
|
function ConflictDialog({ conflict, value, setValue, close, submit, busy }: { conflict: SaveConflict; value: string; setValue: (value: string) => void; close: () => void; submit: () => void; busy: boolean }) {
|
|
766
|
-
return <
|
|
1090
|
+
return <AccessibleDialog title="解决保存冲突" close={close} className={css.conflictDialog} dismissOnBackdrop={false}><div className={css.conflictHeader}><div><h2>解决保存冲突</h2><p>基线 {conflict.baseCommit.slice(0, 8)} 已更新为 {conflict.currentCommit.slice(0, 8)},Git 尚未写入你的本地草稿。</p></div><button aria-label="关闭冲突窗口" onClick={close}>×</button></div><div className={css.conflictColumns}><label>打开时的基线(只读)<textarea readOnly value={conflict.baseMarkdown}/></label><label>版本库最新版本(只读)<textarea readOnly value={conflict.currentMarkdown}/></label><label>合并稿(必填)<textarea required value={value} onChange={event => setValue(event.target.value)}/></label></div><div className={css.conflictDiffs}><details><summary>基线 → 版本库 Diff</summary><pre>{conflict.baseToCurrentDiff}</pre></details><details><summary>基线 → 本地草稿 Diff</summary><pre>{conflict.baseToDraftDiff}</pre></details></div><div className={css.conflictActions}><button onClick={close}>稍后处理</button><button className={css.execute} disabled={busy || !value.trim()} onClick={submit}>{busy ? '正在提交…' : '基于最新版本保存合并稿'}</button></div></AccessibleDialog>
|
|
1091
|
+
}
|
|
1092
|
+
function DialogForm({ title, close, children, submit, noValidate = false }: { title: string; close: () => void; children: ReactNode; submit: (event: FormEvent) => void; noValidate?: boolean }) { return <AccessibleDialog title={title} close={close} className={css.dialogSurface}><form className={css.dialogForm} noValidate={noValidate} onSubmit={submit}>{children}</form></AccessibleDialog> }
|
|
1093
|
+
function IdentityDialog({
|
|
1094
|
+
value,
|
|
1095
|
+
boundRole,
|
|
1096
|
+
onChange,
|
|
1097
|
+
close,
|
|
1098
|
+
save,
|
|
1099
|
+
}: {
|
|
1100
|
+
value: ParticipantSnapshot;
|
|
1101
|
+
boundRole?: ParticipantRole;
|
|
1102
|
+
onChange: (value: ParticipantSnapshot) => void;
|
|
1103
|
+
close: () => void;
|
|
1104
|
+
save: () => void;
|
|
1105
|
+
}) {
|
|
1106
|
+
return (
|
|
1107
|
+
<DialogForm
|
|
1108
|
+
title="设置协作身份"
|
|
1109
|
+
close={close}
|
|
1110
|
+
submit={(event) => {
|
|
1111
|
+
event.preventDefault();
|
|
1112
|
+
if (value.nickname.trim().length >= 2) save();
|
|
1113
|
+
}}
|
|
1114
|
+
>
|
|
1115
|
+
<div className={css.dialogHead}>
|
|
1116
|
+
<div>
|
|
1117
|
+
<span>协作身份</span>
|
|
1118
|
+
<h2>设置花名和角色</h2>
|
|
1119
|
+
</div>
|
|
1120
|
+
<button type="button" aria-label="关闭" onClick={close}>
|
|
1121
|
+
×
|
|
1122
|
+
</button>
|
|
1123
|
+
</div>
|
|
1124
|
+
<p>用于标记回答、决策和版本确认。同一浏览器首次参与后,角色保持不变。</p>
|
|
1125
|
+
<label>
|
|
1126
|
+
花名(必填)
|
|
1127
|
+
<input
|
|
1128
|
+
required
|
|
1129
|
+
autoFocus
|
|
1130
|
+
value={value.nickname}
|
|
1131
|
+
onChange={(event) =>
|
|
1132
|
+
onChange({ ...value, nickname: event.target.value })
|
|
1133
|
+
}
|
|
1134
|
+
/>
|
|
1135
|
+
</label>
|
|
1136
|
+
<label>
|
|
1137
|
+
参与角色(必填)
|
|
1138
|
+
<select
|
|
1139
|
+
required
|
|
1140
|
+
disabled={boundRole !== undefined}
|
|
1141
|
+
value={boundRole ?? value.role}
|
|
1142
|
+
onChange={(event) =>
|
|
1143
|
+
onChange({ ...value, role: event.target.value as ParticipantRole })
|
|
1144
|
+
}
|
|
1145
|
+
>
|
|
1146
|
+
<option value="product">产品</option>
|
|
1147
|
+
<option value="engineering">研发</option>
|
|
1148
|
+
</select>
|
|
1149
|
+
</label>
|
|
1150
|
+
{boundRole && (
|
|
1151
|
+
<small>
|
|
1152
|
+
当前身份已固定为{boundRole === "product" ? "产品" : "研发"}角色。
|
|
1153
|
+
</small>
|
|
1154
|
+
)}
|
|
1155
|
+
<div className={css.stickyActions}>
|
|
1156
|
+
<button type="button" onClick={close}>
|
|
1157
|
+
取消
|
|
1158
|
+
</button>
|
|
1159
|
+
<button
|
|
1160
|
+
className={css.execute}
|
|
1161
|
+
disabled={value.nickname.trim().length < 2}
|
|
1162
|
+
>
|
|
1163
|
+
保存身份
|
|
1164
|
+
</button>
|
|
1165
|
+
</div>
|
|
1166
|
+
</DialogForm>
|
|
1167
|
+
);
|
|
1168
|
+
}
|
|
1169
|
+
function RenameDialog({
|
|
1170
|
+
title,
|
|
1171
|
+
setTitle,
|
|
1172
|
+
close,
|
|
1173
|
+
submit,
|
|
1174
|
+
busy,
|
|
1175
|
+
}: {
|
|
1176
|
+
title: string;
|
|
1177
|
+
setTitle: (title: string) => void;
|
|
1178
|
+
close: () => void;
|
|
1179
|
+
submit: () => void;
|
|
1180
|
+
busy: boolean;
|
|
1181
|
+
}) {
|
|
1182
|
+
return (
|
|
1183
|
+
<DialogForm
|
|
1184
|
+
title="重命名需求"
|
|
1185
|
+
close={close}
|
|
1186
|
+
submit={(event) => {
|
|
1187
|
+
event.preventDefault();
|
|
1188
|
+
submit();
|
|
1189
|
+
}}
|
|
1190
|
+
>
|
|
1191
|
+
<div className={css.dialogHead}>
|
|
1192
|
+
<h2>重命名需求</h2>
|
|
1193
|
+
<button type="button" aria-label="关闭" onClick={close}>
|
|
1194
|
+
×
|
|
1195
|
+
</button>
|
|
1196
|
+
</div>
|
|
1197
|
+
<label>
|
|
1198
|
+
需求名称(必填)
|
|
1199
|
+
<input
|
|
1200
|
+
required
|
|
1201
|
+
autoFocus
|
|
1202
|
+
value={title}
|
|
1203
|
+
onChange={(event) => setTitle(event.target.value)}
|
|
1204
|
+
/>
|
|
1205
|
+
</label>
|
|
1206
|
+
<div className={css.stickyActions}>
|
|
1207
|
+
<button type="button" onClick={close}>
|
|
1208
|
+
取消
|
|
1209
|
+
</button>
|
|
1210
|
+
<button className={css.execute} disabled={busy || !title.trim()}>
|
|
1211
|
+
保存名称
|
|
1212
|
+
</button>
|
|
1213
|
+
</div>
|
|
1214
|
+
</DialogForm>
|
|
1215
|
+
);
|
|
1216
|
+
}
|
|
1217
|
+
function DeleteDialog({
|
|
1218
|
+
title,
|
|
1219
|
+
close,
|
|
1220
|
+
submit,
|
|
1221
|
+
busy,
|
|
1222
|
+
}: {
|
|
1223
|
+
title: string;
|
|
1224
|
+
close: () => void;
|
|
1225
|
+
submit: () => void;
|
|
1226
|
+
busy: boolean;
|
|
1227
|
+
}) {
|
|
1228
|
+
return (
|
|
1229
|
+
<DialogForm
|
|
1230
|
+
title="删除需求"
|
|
1231
|
+
close={close}
|
|
1232
|
+
submit={(event) => {
|
|
1233
|
+
event.preventDefault();
|
|
1234
|
+
submit();
|
|
1235
|
+
}}
|
|
1236
|
+
>
|
|
1237
|
+
<div className={css.dialogHead}>
|
|
1238
|
+
<h2>删除需求</h2>
|
|
1239
|
+
<button type="button" aria-label="关闭" onClick={close}>
|
|
1240
|
+
×
|
|
1241
|
+
</button>
|
|
1242
|
+
</div>
|
|
1243
|
+
<p>
|
|
1244
|
+
将删除“{title}”及其协作记录,并创建 Git 删除提交。历史版本仍可从 Git
|
|
1245
|
+
恢复。
|
|
1246
|
+
</p>
|
|
1247
|
+
<div className={css.stickyActions}>
|
|
1248
|
+
<button type="button" onClick={close}>
|
|
1249
|
+
取消
|
|
1250
|
+
</button>
|
|
1251
|
+
<button className={css.dangerButton} disabled={busy}>
|
|
1252
|
+
{busy ? "正在删除…" : "确认删除"}
|
|
1253
|
+
</button>
|
|
1254
|
+
</div>
|
|
1255
|
+
</DialogForm>
|
|
1256
|
+
);
|
|
1257
|
+
}
|
|
1258
|
+
function WorkspaceDialog({
|
|
1259
|
+
value,
|
|
1260
|
+
setValue,
|
|
1261
|
+
workspaces,
|
|
1262
|
+
close,
|
|
1263
|
+
submit,
|
|
1264
|
+
busy,
|
|
1265
|
+
}: {
|
|
1266
|
+
value: string;
|
|
1267
|
+
setValue: (value: string) => void;
|
|
1268
|
+
workspaces: ReviewWorkspaceSummary[];
|
|
1269
|
+
close: () => void;
|
|
1270
|
+
submit: () => void;
|
|
1271
|
+
busy: boolean;
|
|
1272
|
+
}) {
|
|
1273
|
+
return (
|
|
1274
|
+
<DialogForm
|
|
1275
|
+
title="关联项目"
|
|
1276
|
+
close={close}
|
|
1277
|
+
submit={(event) => {
|
|
1278
|
+
event.preventDefault();
|
|
1279
|
+
submit();
|
|
1280
|
+
}}
|
|
1281
|
+
>
|
|
1282
|
+
<div className={css.dialogHead}>
|
|
1283
|
+
<h2>关联项目</h2>
|
|
1284
|
+
<button type="button" aria-label="关闭" onClick={close}>
|
|
1285
|
+
×
|
|
1286
|
+
</button>
|
|
1287
|
+
</div>
|
|
1288
|
+
<p>AI 会从所选项目读取代码、规范和团队知识。关联后不能中途切换。</p>
|
|
1289
|
+
<label>
|
|
1290
|
+
需求所在项目(必填)
|
|
1291
|
+
<select
|
|
1292
|
+
required
|
|
1293
|
+
autoFocus
|
|
1294
|
+
value={value}
|
|
1295
|
+
onChange={(event) => setValue(event.target.value)}
|
|
1296
|
+
>
|
|
1297
|
+
<option value="" disabled>
|
|
1298
|
+
{workspaces.length > 0 ? "选择一个项目" : "当前没有可用项目"}
|
|
1299
|
+
</option>
|
|
1300
|
+
{workspaces.map((workspace) => (
|
|
1301
|
+
<option key={workspace.workspaceId} value={workspace.workspaceId}>
|
|
1302
|
+
{workspace.title} · {workspace.path}
|
|
1303
|
+
</option>
|
|
1304
|
+
))}
|
|
1305
|
+
</select>
|
|
1306
|
+
</label>
|
|
1307
|
+
<div className={css.stickyActions}>
|
|
1308
|
+
<button type="button" onClick={close}>
|
|
1309
|
+
取消
|
|
1310
|
+
</button>
|
|
1311
|
+
<button className={css.execute} disabled={busy || !value}>
|
|
1312
|
+
确认关联
|
|
1313
|
+
</button>
|
|
1314
|
+
</div>
|
|
1315
|
+
</DialogForm>
|
|
1316
|
+
);
|
|
1317
|
+
}
|
|
1318
|
+
function CreateDialog({
|
|
1319
|
+
value,
|
|
1320
|
+
setValue,
|
|
1321
|
+
workspaces,
|
|
1322
|
+
close,
|
|
1323
|
+
submit,
|
|
1324
|
+
busy,
|
|
1325
|
+
}: {
|
|
1326
|
+
value: {
|
|
1327
|
+
title: string;
|
|
1328
|
+
rawRequirement: string;
|
|
1329
|
+
sources: string;
|
|
1330
|
+
workspaceId: string;
|
|
1331
|
+
};
|
|
1332
|
+
setValue: (value: {
|
|
1333
|
+
title: string;
|
|
1334
|
+
rawRequirement: string;
|
|
1335
|
+
sources: string;
|
|
1336
|
+
workspaceId: string;
|
|
1337
|
+
}) => void;
|
|
1338
|
+
workspaces: ReviewWorkspaceSummary[];
|
|
1339
|
+
close: () => void;
|
|
1340
|
+
submit: () => void;
|
|
1341
|
+
busy: boolean;
|
|
1342
|
+
}) {
|
|
1343
|
+
const [attempted, setAttempted] = useState(false);
|
|
1344
|
+
const errors = [
|
|
1345
|
+
...(!value.title.trim() ? ["请填写需求标题"] : []),
|
|
1346
|
+
...(!value.workspaceId ? ["请选择需求所在项目"] : []),
|
|
1347
|
+
...(!value.rawRequirement.trim() ? ["请填写原始需求"] : []),
|
|
1348
|
+
];
|
|
1349
|
+
return (
|
|
1350
|
+
<DialogForm
|
|
1351
|
+
title="新建需求"
|
|
1352
|
+
close={close}
|
|
1353
|
+
noValidate
|
|
1354
|
+
submit={(event) => {
|
|
1355
|
+
event.preventDefault();
|
|
1356
|
+
setAttempted(true);
|
|
1357
|
+
if (errors.length === 0) submit();
|
|
1358
|
+
else window.requestAnimationFrame(() => document.getElementById(!value.title.trim() ? 'create-requirement-title' : !value.workspaceId ? 'create-requirement-workspace' : 'create-requirement-raw')?.focus());
|
|
1359
|
+
}}
|
|
1360
|
+
>
|
|
1361
|
+
<div className={css.dialogHead}>
|
|
1362
|
+
<div>
|
|
1363
|
+
<span>新需求</span>
|
|
1364
|
+
<h2>从真实问题开始</h2>
|
|
1365
|
+
</div>
|
|
1366
|
+
<button type="button" aria-label="关闭" onClick={close}>
|
|
1367
|
+
×
|
|
1368
|
+
</button>
|
|
1369
|
+
</div>
|
|
1370
|
+
<p>
|
|
1371
|
+
先写清用户问题和期望结果。创建后 AI
|
|
1372
|
+
会读取所选项目的已配置资料并在后台检查,你可以离开页面。
|
|
1373
|
+
</p>
|
|
1374
|
+
{attempted && errors.length > 0 && (
|
|
1375
|
+
<div className={css.formErrors} role="alert">
|
|
1376
|
+
<strong>还需要补充</strong>
|
|
1377
|
+
{errors.map((error) => (
|
|
1378
|
+
<span key={error}>{error}</span>
|
|
1379
|
+
))}
|
|
1380
|
+
</div>
|
|
1381
|
+
)}
|
|
1382
|
+
<label>
|
|
1383
|
+
需求标题(必填)
|
|
1384
|
+
<input
|
|
1385
|
+
id="create-requirement-title"
|
|
1386
|
+
autoFocus
|
|
1387
|
+
required
|
|
1388
|
+
value={value.title}
|
|
1389
|
+
aria-invalid={attempted && !value.title.trim()}
|
|
1390
|
+
onChange={(event) =>
|
|
1391
|
+
setValue({ ...value, title: event.target.value })
|
|
1392
|
+
}
|
|
1393
|
+
/>
|
|
1394
|
+
</label>
|
|
1395
|
+
<label>
|
|
1396
|
+
需求所在项目(必填)
|
|
1397
|
+
<select
|
|
1398
|
+
id="create-requirement-workspace"
|
|
1399
|
+
required
|
|
1400
|
+
value={value.workspaceId}
|
|
1401
|
+
aria-invalid={attempted && !value.workspaceId}
|
|
1402
|
+
onChange={(event) =>
|
|
1403
|
+
setValue({ ...value, workspaceId: event.target.value })
|
|
1404
|
+
}
|
|
1405
|
+
>
|
|
1406
|
+
<option value="" disabled>
|
|
1407
|
+
{workspaces.length > 0 ? "选择一个项目" : "当前没有可用项目"}
|
|
1408
|
+
</option>
|
|
1409
|
+
{workspaces.map((workspace) => (
|
|
1410
|
+
<option key={workspace.workspaceId} value={workspace.workspaceId}>
|
|
1411
|
+
{workspace.title} · {workspace.path}
|
|
1412
|
+
</option>
|
|
1413
|
+
))}
|
|
1414
|
+
</select>
|
|
1415
|
+
</label>
|
|
1416
|
+
<label>
|
|
1417
|
+
原始需求(必填)
|
|
1418
|
+
<textarea
|
|
1419
|
+
id="create-requirement-raw"
|
|
1420
|
+
required
|
|
1421
|
+
value={value.rawRequirement}
|
|
1422
|
+
aria-invalid={attempted && !value.rawRequirement.trim()}
|
|
1423
|
+
onChange={(event) =>
|
|
1424
|
+
setValue({ ...value, rawRequirement: event.target.value })
|
|
1425
|
+
}
|
|
1426
|
+
placeholder="描述用户遇到的问题、期望结果、已有方案和已知限制"
|
|
1427
|
+
/>
|
|
1428
|
+
</label>
|
|
1429
|
+
<label>
|
|
1430
|
+
补充资料(选填,每行一项)
|
|
1431
|
+
<textarea
|
|
1432
|
+
value={value.sources}
|
|
1433
|
+
onChange={(event) =>
|
|
1434
|
+
setValue({ ...value, sources: event.target.value })
|
|
1435
|
+
}
|
|
1436
|
+
placeholder="相关文档链接 历史决策 代码目录或组件"
|
|
1437
|
+
/>
|
|
1438
|
+
</label>
|
|
1439
|
+
<div className={css.createSummary}>
|
|
1440
|
+
<strong>提交后</strong>
|
|
1441
|
+
<span>创建 Git 初始版本</span>
|
|
1442
|
+
<span>开始产品 AI 初审</span>
|
|
1443
|
+
<span>输入和运行状态会保留</span>
|
|
1444
|
+
</div>
|
|
1445
|
+
<div className={css.stickyActions}>
|
|
1446
|
+
<button type="button" onClick={close}>
|
|
1447
|
+
取消
|
|
1448
|
+
</button>
|
|
1449
|
+
<button className={css.execute} disabled={busy}>
|
|
1450
|
+
{busy ? "正在创建…" : "创建并开始 AI 检查"}
|
|
1451
|
+
</button>
|
|
1452
|
+
</div>
|
|
1453
|
+
</DialogForm>
|
|
1454
|
+
);
|
|
1455
|
+
}
|
|
1456
|
+
function PageCommentDialog({ value, setValue, close, submit, busy }: { value: string; setValue: (value: string) => void; close: () => void; submit: () => void; busy: boolean }) { return <DialogForm title="评论整篇需求" close={close} submit={event => { event.preventDefault(); submit() }}><div className={css.dialogHead}><div><span>页面总评</span><h2>评论整篇需求</h2></div><button type="button" aria-label="关闭" onClick={close}>×</button></div><p>用于整体方向、完整性或跨章节问题。针对具体文字时,请在正文中选中片段评论。</p><label>评论内容(必填)<textarea autoFocus required value={value} onChange={event => setValue(event.target.value)}/></label><div className={css.stickyActions}><button type="button" onClick={close}>取消</button><button className={css.execute} disabled={busy || !value.trim()}>提交总评</button></div></DialogForm> }
|
|
1457
|
+
function NotificationDialog({ notifications, close, open, markRead }: { notifications: Notification[]; close: () => void; open: (item: Notification) => void; markRead: (item: Notification) => void }) { return <AccessibleDialog title="通知中心" close={close} className={css.notificationDialog}><div className={css.dialogHead}><div><span>插件内协作</span><h2>通知中心</h2></div><button aria-label="关闭" onClick={close}>×</button></div>{notifications.length === 0 ? <div className={css.emptyPanel}><strong>没有新通知</strong><p>提及、回复、指派和状态变化会出现在这里。</p></div> : <div className={css.notificationList}>{notifications.map(item => <article className={item.readAt ? '' : css.unreadNotification} key={item.id}><button onClick={() => { markRead(item); open(item) }}><strong>{item.message}</strong><span title={new Date(item.createdAt).toLocaleString()}>{relativeTime(item.createdAt)}</span></button>{!item.readAt && <button onClick={() => markRead(item)}>标为已读</button>}</article>)}</div>}</AccessibleDialog> }
|
|
1458
|
+
function MyWorkDialog({ items, notifications, close, openItem, openNotification }: { items: MyActionItem[]; notifications: Notification[]; close: () => void; openItem: (item: MyActionItem) => void; openNotification: (item: Notification) => void }) {
|
|
1459
|
+
const unread = notifications.filter(item => item.readAt === undefined)
|
|
1460
|
+
return <AccessibleDialog title="我的工作" close={close} className={css.notificationDialog}><div className={css.dialogHead}><div><span>跨需求个人工作台</span><h2>我的工作</h2></div><button aria-label="关闭" onClick={close}>×</button></div><div className={css.myWorkSummary}><span><b>{items.length}</b> 个待办</span><span><b>{unread.length}</b> 条未读</span></div>{items.length === 0 && unread.length === 0 ? <div className={css.emptyPanel}><strong>当前没有需要你处理的事项</strong><p>指派、提及、回复和待确认项会跨需求汇总到这里。</p></div> : <div className={css.myWorkList}>{items.map(item => <button key={`${item.category}-${item.id}`} onClick={() => openItem(item)}><span>{item.blocking ? '优先处理' : '普通'}</span><strong>{item.objectTitle}</strong><small title={new Date(item.updatedAt).toLocaleString()}>{item.requirementTitle} · {taskTypeLabel[item.type]} · {stageLabel(item.dueStage)}前 · {relativeTime(item.updatedAt)}</small></button>)}{unread.map(item => <button key={item.id} onClick={() => openNotification(item)}><span>{item.kind === 'mention' ? '@ 提及' : item.kind === 'assignment' ? '指派' : '未读通知'}</span><strong>{item.message}</strong><small title={new Date(item.createdAt).toLocaleString()}>{relativeTime(item.createdAt)}</small></button>)}</div>}</AccessibleDialog>
|
|
767
1461
|
}
|
|
768
|
-
function IdentityDialog({ value, boundRole, onChange, close }: { value: ParticipantSnapshot; boundRole?: ParticipantRole; onChange: (value: ParticipantSnapshot) => void; close: () => void }) { return <div className={css.modal}><form onSubmit={event => { event.preventDefault(); if (value.nickname.trim().length >= 2) close() }}><h2>设置协作身份</h2><p>用于标记回答、决策和版本确认。同一浏览器首次参与后,角色会保持不变。</p><label>花名(必填)<input required autoFocus value={value.nickname} onChange={event => onChange({ ...value, nickname: event.target.value })}/></label><label>参与角色(必填)<select required disabled={boundRole !== undefined} value={boundRole ?? value.role} onChange={event => onChange({ ...value, role: event.target.value as ParticipantRole })}><option value="product">产品</option><option value="engineering">研发</option></select></label>{boundRole && <small>当前身份已固定为{boundRole === 'product' ? '产品' : '研发'}角色。</small>}<button type="submit" disabled={value.nickname.trim().length < 2}>保存身份</button></form></div> }
|
|
769
|
-
function RenameDialog({ title, setTitle, close, submit, busy }: { title: string; setTitle: (title: string) => void; close: () => void; submit: () => void; busy: boolean }) { return <div className={css.modal}><form onSubmit={event => { event.preventDefault(); submit() }}><h2>重命名需求</h2><label>需求名称(必填)<input required autoFocus value={title} onChange={event => setTitle(event.target.value)}/></label><div><button type="button" onClick={close}>取消</button><button type="submit" disabled={busy || !title.trim()}>保存名称</button></div></form></div> }
|
|
770
|
-
function DeleteDialog({ title, close, submit, busy }: { title: string; close: () => void; submit: () => void; busy: boolean }) { return <div className={css.modal}><form onSubmit={event => { event.preventDefault(); submit() }}><h2>删除需求</h2><p>将删除“{title}”及其协作记录,并创建 Git 删除提交。历史版本仍可从 Git 恢复。</p><div><button type="button" onClick={close}>取消</button><button type="submit" className={css.dangerButton} disabled={busy}>{busy ? '正在删除…' : '确认删除'}</button></div></form></div> }
|
|
771
|
-
function WorkspaceDialog({ value, setValue, workspaces, close, submit, busy }: { value: string; setValue: (value: string) => void; workspaces: ReviewWorkspaceSummary[]; close: () => void; submit: () => void; busy: boolean }) { return <div className={css.modal}><form onSubmit={event => { event.preventDefault(); submit() }}><h2>关联项目</h2><p>AI 会从所选项目读取代码、规范和团队知识。关联后不能中途切换。</p><label>需求所在项目(必填)<select required autoFocus value={value} onChange={event => setValue(event.target.value)}><option value="" disabled>{workspaces.length > 0 ? '选择一个项目' : '当前没有可用项目'}</option>{workspaces.map(workspace => <option key={workspace.workspaceId} value={workspace.workspaceId}>{workspace.title} · {workspace.path}</option>)}</select></label><div><button type="button" onClick={close}>取消</button><button type="submit" disabled={busy || !value}>确认关联</button></div></form></div> }
|
|
772
|
-
function CreateDialog({ value, setValue, workspaces, close, submit, busy }: { value: { title: string; rawRequirement: string; sources: string; workspaceId: string }; setValue: (value: { title: string; rawRequirement: string; sources: string; workspaceId: string }) => void; workspaces: ReviewWorkspaceSummary[]; close: () => void; submit: () => void; busy: boolean }) { return <div className={css.modal}><form onSubmit={event => { event.preventDefault(); submit() }}><h2>新建需求</h2><p>先写清用户问题和期望结果,其余缺口交给 AI 检查。</p><label>需求标题(必填)<input required value={value.title} onChange={event => setValue({ ...value, title: event.target.value })}/></label><label>需求所在项目(必填)<select required value={value.workspaceId} onChange={event => setValue({ ...value, workspaceId: event.target.value })}><option value="" disabled>{workspaces.length > 0 ? '选择一个项目' : '当前没有可用项目'}</option>{workspaces.map(workspace => <option key={workspace.workspaceId} value={workspace.workspaceId}>{workspace.title} · {workspace.path}</option>)}</select></label><label>原始需求(必填)<textarea required value={value.rawRequirement} onChange={event => setValue({ ...value, rawRequirement: event.target.value })} placeholder="描述用户遇到的问题、期望结果、已有方案和已知限制"/></label><label>补充资料(选填,每行一项)<textarea value={value.sources} onChange={event => setValue({ ...value, sources: event.target.value })} placeholder="相关文档链接 历史决策 代码目录或组件"/></label><div><button type="button" onClick={close}>取消</button><button type="submit" disabled={busy || !value.title.trim() || !value.rawRequirement.trim() || !value.workspaceId}>创建并开始 AI 检查</button></div></form></div> }
|