dsh-spec-collab 0.1.0
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/LICENSE +201 -0
- package/README.md +106 -0
- package/cordis.patch.yml +3 -0
- package/lib/client.js +41298 -0
- package/lib/index.js +1986 -0
- package/lib/types/client/SpecWorkbench.d.ts +6 -0
- package/lib/types/client/SpecWorkbench.d.ts.map +1 -0
- package/lib/types/client/api.d.ts +20 -0
- package/lib/types/client/api.d.ts.map +1 -0
- package/lib/types/client/index.d.ts +4 -0
- package/lib/types/client/index.d.ts.map +1 -0
- package/lib/types/client/mount.d.ts +4 -0
- package/lib/types/client/mount.d.ts.map +1 -0
- package/lib/types/engine.d.ts +67 -0
- package/lib/types/engine.d.ts.map +1 -0
- package/lib/types/git-store.d.ts +40 -0
- package/lib/types/git-store.d.ts.map +1 -0
- package/lib/types/index.d.ts +12 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/protocol.d.ts +358 -0
- package/lib/types/protocol.d.ts.map +1 -0
- package/lib/types/review-context.d.ts +32 -0
- package/lib/types/review-context.d.ts.map +1 -0
- package/lib/types/review-runtime.d.ts +26 -0
- package/lib/types/review-runtime.d.ts.map +1 -0
- package/lib/types/routes.d.ts +5 -0
- package/lib/types/routes.d.ts.map +1 -0
- package/lib/types/tools.d.ts +8 -0
- package/lib/types/tools.d.ts.map +1 -0
- package/package.json +96 -0
- package/src/client/SpecWorkbench.tsx +293 -0
- package/src/client/api.ts +12 -0
- package/src/client/css-modules.d.ts +1 -0
- package/src/client/index.ts +16 -0
- package/src/client/mount.tsx +73 -0
- package/src/client/toast-ui.d.ts +25 -0
- package/src/client/workbench.module.css +275 -0
- package/src/engine.ts +358 -0
- package/src/git-store.ts +133 -0
- package/src/index.ts +49 -0
- package/src/protocol.ts +108 -0
- package/src/review-context.ts +87 -0
- package/src/review-runtime.ts +106 -0
- package/src/routes.ts +52 -0
- package/src/tools.ts +80 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../src/tools.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAA;AAOjD,wBAAgB,YAAY,CAAC,MAAM,EAAE,mBAAmB,mDAMvD;AAED,wBAAgB,YAAY,CAAC,MAAM,EAAE,mBAAmB,mDAmBvD;AAED,wBAAgB,aAAa,CAAC,MAAM,EAAE,mBAAmB,mDAOxD;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,mBAAmB,mDAqB/D;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,mBAAmB,mDAO/D;AAED,wBAAgB,YAAY,CAAC,MAAM,EAAE,mBAAmB,qDAA4I"}
|
package/package.json
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "dsh-spec-collab",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "AI-assisted requirement clarification and Git-backed Spec co-creation for DeepSeek Harness, ending at a human-confirmed Ready Spec.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"deepseek-harness",
|
|
7
|
+
"requirements",
|
|
8
|
+
"specification",
|
|
9
|
+
"ai-review",
|
|
10
|
+
"collaboration"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://github.com/zx490336534/dsh-spec-collab#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/zx490336534/dsh-spec-collab/issues"
|
|
15
|
+
},
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/zx490336534/dsh-spec-collab.git"
|
|
19
|
+
},
|
|
20
|
+
"type": "module",
|
|
21
|
+
"main": "lib/index.js",
|
|
22
|
+
"types": "lib/types/index.d.ts",
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./lib/types/index.d.ts",
|
|
26
|
+
"default": "./lib/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./client": {
|
|
29
|
+
"types": "./lib/types/client/index.d.ts",
|
|
30
|
+
"default": "./lib/client.js"
|
|
31
|
+
},
|
|
32
|
+
"./package.json": "./package.json"
|
|
33
|
+
},
|
|
34
|
+
"dsh": {
|
|
35
|
+
"bundle": {
|
|
36
|
+
"patch": "./cordis.patch.yml"
|
|
37
|
+
},
|
|
38
|
+
"client": {
|
|
39
|
+
"inject": [
|
|
40
|
+
"@deepseek-ai/dsh-client-runtime",
|
|
41
|
+
"@deepseek-ai/dsh-client-connection"
|
|
42
|
+
],
|
|
43
|
+
"platform": "web"
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
"files": [
|
|
47
|
+
"lib",
|
|
48
|
+
"src",
|
|
49
|
+
"cordis.patch.yml",
|
|
50
|
+
"README.md"
|
|
51
|
+
],
|
|
52
|
+
"scripts": {
|
|
53
|
+
"clean": "node -e \"require('node:fs').rmSync('lib', { recursive: true, force: true })\"",
|
|
54
|
+
"build": "npm run clean && tsc -p tsconfig.build.json && tsdown",
|
|
55
|
+
"bundle": "tsdown",
|
|
56
|
+
"prepare": "npm run build",
|
|
57
|
+
"typecheck": "tsc --noEmit",
|
|
58
|
+
"test": "vitest run"
|
|
59
|
+
},
|
|
60
|
+
"dependencies": {
|
|
61
|
+
"@toast-ui/editor": "3.2.2",
|
|
62
|
+
"lightningcss": "^1.32.0",
|
|
63
|
+
"markdown-it": "^14.1.0",
|
|
64
|
+
"prosemirror-inputrules": "^1.5.0",
|
|
65
|
+
"schemastery": "^3.18.0"
|
|
66
|
+
},
|
|
67
|
+
"devDependencies": {
|
|
68
|
+
"@deepseek-ai/cordis": "^4.0.1",
|
|
69
|
+
"@deepseek-ai/dsh-client-connection": "^0.1.0-rc.8",
|
|
70
|
+
"@deepseek-ai/dsh-client-runtime": "^0.1.0-rc.8",
|
|
71
|
+
"@deepseek-ai/dsh-host-apiproxy": "^0.1.0-rc.8",
|
|
72
|
+
"@deepseek-ai/dsh-host-webserver": "^0.1.0-rc.8",
|
|
73
|
+
"@deepseek-ai/dsh-llm": "^0.1.0-rc.8",
|
|
74
|
+
"@deepseek-ai/dsh-system-prompt": "^0.1.0-rc.8",
|
|
75
|
+
"@deepseek-ai/dsh-tools": "^0.1.0-rc.8",
|
|
76
|
+
"@types/markdown-it": "^14.1.2",
|
|
77
|
+
"@types/node": "^22.20.0",
|
|
78
|
+
"@types/react": "~18.3.1",
|
|
79
|
+
"@types/react-dom": "^18.3.5",
|
|
80
|
+
"jsdom": "^25.0.0",
|
|
81
|
+
"react": "^18.3.1",
|
|
82
|
+
"react-dom": "^18.3.1",
|
|
83
|
+
"tsdown": "0.22.2",
|
|
84
|
+
"typescript": "~5.7.2",
|
|
85
|
+
"vitest": "^3.0.0"
|
|
86
|
+
},
|
|
87
|
+
"peerDependencies": {
|
|
88
|
+
"react": "^18.2.0",
|
|
89
|
+
"react-dom": "^18.2.0"
|
|
90
|
+
},
|
|
91
|
+
"engines": {
|
|
92
|
+
"node": ">=20"
|
|
93
|
+
},
|
|
94
|
+
"packageManager": "pnpm@9.9.0",
|
|
95
|
+
"license": "Apache-2.0"
|
|
96
|
+
}
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { useEffect, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from 'react'
|
|
2
|
+
import MarkdownIt from 'markdown-it'
|
|
3
|
+
import ToastEditor from '@toast-ui/editor'
|
|
4
|
+
import '@toast-ui/editor/dist/i18n/zh-cn'
|
|
5
|
+
import { InputRule, inputRules } from 'prosemirror-inputrules'
|
|
6
|
+
import type { CollaborationAction, CommentResolution, MyActionItem, ParticipantRole, ParticipantSnapshot, RequirementStage, RequirementVersion, RequirementView, ReviewKind, ReviewWorkspaceSummary, SaveConflict } from '../protocol.ts'
|
|
7
|
+
import type { SpecApi } from './api.ts'
|
|
8
|
+
import css from './workbench.module.css'
|
|
9
|
+
|
|
10
|
+
const md = new MarkdownIt({ html: false, linkify: true })
|
|
11
|
+
const inlineStyleRule = (pattern: RegExp, markName: 'strong' | 'emph' | 'code'): InputRule => new InputRule(pattern, (state, match, start, end) => {
|
|
12
|
+
const text = match[1]
|
|
13
|
+
const mark = state.schema.marks[markName]
|
|
14
|
+
if (!text || !mark) return null
|
|
15
|
+
return state.tr.delete(start, end).insertText(text, start).addMark(start, start + text.length, mark.create())
|
|
16
|
+
})
|
|
17
|
+
const markdownShortcutsPlugin = () => ({ wysiwygPlugins: [() => inputRules({ rules: [
|
|
18
|
+
new InputRule(/^(#{1,6})\s$/, (state, match, start, end) => state.tr.delete(start, end).setBlockType(start, start, state.schema.nodes.heading!, { level: match[1]!.length })),
|
|
19
|
+
new InputRule(/^```\s$/, (state, _match, start, end) => state.tr.delete(start, end).setBlockType(start, start, state.schema.nodes.codeBlock!)),
|
|
20
|
+
inlineStyleRule(/\*\*([^*]+)\*\*$/, 'strong'), inlineStyleRule(/(?<!\*)\*([^*]+)\*$/, 'emph'), inlineStyleRule(/`([^`]+)`$/, 'code'),
|
|
21
|
+
] })] })
|
|
22
|
+
type SideTab = 'review' | 'discussion' | 'patches' | 'decisions' | 'items' | 'versions' | 'ready'
|
|
23
|
+
type CommentAnchor = { quote: string; prefix: string; suffix: string; heading?: string }
|
|
24
|
+
function newParticipant(): ParticipantSnapshot { return { participantId: crypto.randomUUID(), nickname: '', role: 'product', kind: 'human' } }
|
|
25
|
+
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() }
|
|
26
|
+
function stageLabel(stage: RequirementStage): string { return ({ 'product-review': '产品审核', 'product-confirmation': '产品确认', 'joint-review': '产研共审', ready: 'Ready' })[stage] }
|
|
27
|
+
const tabLabel: Record<SideTab, string> = { review: '审核问题', discussion: '协作讨论', patches: '修改建议', decisions: '确认决策', items: '我的事项', versions: '版本记录', ready: '完成检查' }
|
|
28
|
+
|
|
29
|
+
export function SpecWorkbench({ api }: { api: SpecApi }) {
|
|
30
|
+
const [requirements, setRequirements] = useState<RequirementView[]>([])
|
|
31
|
+
const [reviewWorkspaces, setReviewWorkspaces] = useState<ReviewWorkspaceSummary[]>([])
|
|
32
|
+
const [participantBindings, setParticipantBindings] = useState<ParticipantSnapshot[]>([])
|
|
33
|
+
const [selectedId, setSelectedId] = useState<string>()
|
|
34
|
+
const [participant, setParticipant] = useState(loadParticipant)
|
|
35
|
+
const [identityOpen, setIdentityOpen] = useState(false)
|
|
36
|
+
const [createOpen, setCreateOpen] = useState(false)
|
|
37
|
+
const [bindWorkspaceOpen, setBindWorkspaceOpen] = useState(false)
|
|
38
|
+
const [bindWorkspaceId, setBindWorkspaceId] = useState('')
|
|
39
|
+
const [showArchived, setShowArchived] = useState(false)
|
|
40
|
+
const [manageMenuId, setManageMenuId] = useState<string>()
|
|
41
|
+
const [manageTargetId, setManageTargetId] = useState<string>()
|
|
42
|
+
const [renameOpen, setRenameOpen] = useState(false)
|
|
43
|
+
const [deleteOpen, setDeleteOpen] = useState(false)
|
|
44
|
+
const [renameTitle, setRenameTitle] = useState('')
|
|
45
|
+
const [documentsOpen, setDocumentsOpen] = useState(true)
|
|
46
|
+
const [reviewOpen, setReviewOpen] = useState(true)
|
|
47
|
+
const [documentsWidth, setDocumentsWidth] = useState(() => Number(localStorage.getItem('dsh-spec-collab.documents-width')) || 220)
|
|
48
|
+
const [reviewWidth, setReviewWidth] = useState(() => Number(localStorage.getItem('dsh-spec-collab.review-width')) || 430)
|
|
49
|
+
const [createForm, setCreateForm] = useState({ title: '', rawRequirement: '', sources: '', workspaceId: '' })
|
|
50
|
+
const [sideTab, setSideTab] = useState<SideTab>('review')
|
|
51
|
+
const [mobilePane, setMobilePane] = useState<'spec' | 'collab'>('spec')
|
|
52
|
+
const [draft, setDraft] = useState('')
|
|
53
|
+
const [summary, setSummary] = useState('')
|
|
54
|
+
const [notice, setNotice] = useState('')
|
|
55
|
+
const [busy, setBusy] = useState(false)
|
|
56
|
+
const [saveConflict, setSaveConflict] = useState<SaveConflict>()
|
|
57
|
+
const [mergeDraft, setMergeDraft] = useState('')
|
|
58
|
+
const [myItems, setMyItems] = useState<MyActionItem[]>([])
|
|
59
|
+
const [commentText, setCommentText] = useState('')
|
|
60
|
+
const [selection, setSelection] = useState<CommentAnchor>()
|
|
61
|
+
const [draftSelection, setDraftSelection] = useState<CommentAnchor>()
|
|
62
|
+
const visibleRequirements = requirements.filter(item => Boolean(item.archivedAt) === showArchived)
|
|
63
|
+
const selected = requirements.find(item => item.id === selectedId) ?? visibleRequirements[0]
|
|
64
|
+
const manageTarget = requirements.find(item => item.id === manageTargetId)
|
|
65
|
+
const boundRole = participantBindings.find(item => item.participantId === participant.participantId)?.role
|
|
66
|
+
const productFirstRunning = selected?.aiRuns.some(run => run.kind === 'product-first' && run.commit === selected.currentCommit && ['queued', 'running'].includes(run.status)) ?? false
|
|
67
|
+
const currentMyItems = selected ? myItems.filter(item => item.requirementId === selected.id) : []
|
|
68
|
+
const tabCounts: Record<SideTab, number> = selected ? {
|
|
69
|
+
review: selected.reviewItems.filter(item => !['resolved', 'invalidated'].includes(item.status)).length,
|
|
70
|
+
discussion: selected.comments.filter(item => item.status === 'open').length,
|
|
71
|
+
patches: selected.patches.filter(item => item.status === 'pending').length,
|
|
72
|
+
decisions: selected.decisions.filter(item => item.status === 'active').length,
|
|
73
|
+
items: currentMyItems.length,
|
|
74
|
+
versions: 0,
|
|
75
|
+
ready: selected.readiness.filter(item => !item.passed).length,
|
|
76
|
+
} : { review: 0, discussion: 0, patches: 0, decisions: 0, items: 0, versions: 0, ready: 0 }
|
|
77
|
+
const renderSideTab = (tab: SideTab) => <button key={tab} className={sideTab === tab ? css.activeMode : ''} onClick={() => { setSideTab(tab); setMobilePane('collab') }}>{tabLabel[tab]}{tabCounts[tab] > 0 && <span className={css.tabBadge}>{tabCounts[tab]}</span>}</button>
|
|
78
|
+
|
|
79
|
+
const refresh = async (): Promise<void> => { try { const state = await api.state(); setRequirements(state.requirements); setParticipantBindings(state.participants); const binding = state.participants.find(item => item.participantId === participant.participantId); if (binding && binding.role !== participant.role) setParticipant(current => ({ ...current, role: binding.role })); setSelectedId(current => current && state.requirements.some(item => item.id === current) ? current : state.requirements[0]?.id) } catch (error) { setNotice(error instanceof Error ? error.message : String(error)) } }
|
|
80
|
+
useEffect(() => { void refresh(); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))); return api.events(() => { void refresh() }) }, [])
|
|
81
|
+
useEffect(() => { if (selected) setDraft(selected.version.markdown) }, [selected?.id, selected?.currentCommit])
|
|
82
|
+
useEffect(() => { localStorage.setItem('dsh-spec-collab.participant', JSON.stringify(participant)) }, [participant])
|
|
83
|
+
useEffect(() => { localStorage.setItem('dsh-spec-collab.documents-width', String(documentsWidth)) }, [documentsWidth])
|
|
84
|
+
useEffect(() => { localStorage.setItem('dsh-spec-collab.review-width', String(reviewWidth)) }, [reviewWidth])
|
|
85
|
+
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])
|
|
86
|
+
const registered = participant.nickname.trim().length >= 2
|
|
87
|
+
|
|
88
|
+
const act = async (factory: (actor: ParticipantSnapshot) => CollaborationAction): Promise<boolean> => {
|
|
89
|
+
if (!registered) { setIdentityOpen(true); setNotice('首次写操作前请登记花名'); return false }
|
|
90
|
+
setBusy(true); setNotice('')
|
|
91
|
+
try {
|
|
92
|
+
const result = await api.action(factory(participant))
|
|
93
|
+
if (!result.ok) {
|
|
94
|
+
if (result.conflict) { setSaveConflict(result.conflict); setMergeDraft(result.conflict.draftMarkdown); setNotice('检测到并发修改。请在三方对比中合并后再提交。'); return false }
|
|
95
|
+
setNotice(result.error); return false
|
|
96
|
+
}
|
|
97
|
+
setSaveConflict(undefined); await refresh(); if (!result.deletedRequirementId) setSelectedId(result.requirement.id); return true
|
|
98
|
+
}
|
|
99
|
+
finally { setBusy(false) }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const create = async (): Promise<void> => {
|
|
103
|
+
const links = createForm.sources.split('\n').map(value => value.trim()).filter(Boolean)
|
|
104
|
+
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' })) }))
|
|
105
|
+
if (ok) { setCreateOpen(false); setCreateForm({ title: '', rawRequirement: '', sources: '', workspaceId: '' }); setSideTab('review') }
|
|
106
|
+
}
|
|
107
|
+
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('') } }
|
|
108
|
+
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('已创建新的 Git commit,等待变更审核') } }
|
|
109
|
+
const requestReview = async (reviewKind: ReviewKind): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'review.request', participant: actor, requirementId: selected.id, reviewKind })) }
|
|
110
|
+
const confirm = async (role: ParticipantRole): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'confirmation.create', participant: actor, requirementId: selected.id, role, scope: 'version' })) }
|
|
111
|
+
const advance = async (): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'stage.advance', participant: actor, requirementId: selected.id })) }
|
|
112
|
+
const resizePane = (side: 'documents' | 'review', event: ReactPointerEvent<HTMLDivElement>): void => {
|
|
113
|
+
event.preventDefault()
|
|
114
|
+
const startX = event.clientX; const startWidth = side === 'documents' ? documentsWidth : reviewWidth
|
|
115
|
+
const move = (pointer: PointerEvent): void => {
|
|
116
|
+
const next = startWidth + (pointer.clientX - startX) * (side === 'documents' ? 1 : -1)
|
|
117
|
+
if (side === 'documents') setDocumentsWidth(Math.min(360, Math.max(160, next)))
|
|
118
|
+
else setReviewWidth(Math.min(600, Math.max(320, next)))
|
|
119
|
+
}
|
|
120
|
+
const stop = (): void => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', stop); document.body.style.cursor = '' }
|
|
121
|
+
document.body.style.cursor = 'col-resize'; window.addEventListener('pointermove', move); window.addEventListener('pointerup', stop)
|
|
122
|
+
}
|
|
123
|
+
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) } }
|
|
124
|
+
const archiveRequirement = async (target: RequirementView): Promise<void> => { const archived = !target.archivedAt; if (await act(actor => ({ kind: 'requirement.archive', participant: actor, requirementId: target.id, archived }))) { setManageMenuId(undefined); setSelectedId(visibleRequirements.find(item => item.id !== target.id)?.id) } }
|
|
125
|
+
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) } }
|
|
126
|
+
|
|
127
|
+
const captureSelection = (): void => {
|
|
128
|
+
if (!draftSelection) return
|
|
129
|
+
setSelection(draftSelection)
|
|
130
|
+
setDraftSelection(undefined)
|
|
131
|
+
setSideTab('discussion')
|
|
132
|
+
setMobilePane('collab')
|
|
133
|
+
}
|
|
134
|
+
const addComment = async (): Promise<void> => { if (!selected || !selection) return; const ok = await act(actor => ({ kind: 'comment.create', participant: actor, requirementId: selected.id, commit: selected.currentCommit, anchor: selection, body: commentText })); if (ok) { setSelection(undefined); setCommentText(''); setNotice('评论已提交,AI 正在自动分析理解、证据与关联影响') } }
|
|
135
|
+
|
|
136
|
+
return <div className={css.workbench}>
|
|
137
|
+
<header className={css.header}>
|
|
138
|
+
<div className={css.titleBlock}><strong>{selected?.title ?? 'AI 需求澄清与 Spec 共创'}</strong>{selected && <span>{stageLabel(selected.stage)} · {selected.workspaceId ? reviewWorkspaces.find(workspace => workspace.workspaceId === selected.workspaceId)?.title ?? selected.workspaceId : '未绑定工作区'} · {selected.currentCommit.slice(0, 10)} · {selected.reviewItems.filter(item => item.severity === 'blocking' && item.status !== 'resolved').length} 阻塞</span>}</div>
|
|
139
|
+
<div className={css.headerActions}>
|
|
140
|
+
{selected && !selected.workspaceId && <button onClick={() => { setBindWorkspaceOpen(true); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))) }}>绑定工作区</button>}
|
|
141
|
+
{selected?.stage === 'product-review' && <><button disabled={productFirstRunning || !selected.workspaceId} title={!selected.workspaceId ? '请先绑定工作区' : productFirstRunning ? '初审进行中' : '启动智能初审'} onClick={() => void requestReview('product-first')}>智能初审</button><button disabled={!selected.workspaceId} onClick={() => void requestReview('product-second')}>智能复审</button><button className={css.execute} onClick={() => void advance()}>进入产品确认</button></>}
|
|
142
|
+
{selected?.stage === 'product-confirmation' && <><button onClick={() => void confirm('product')}>产品确认当前版本</button><button onClick={() => void advance()}>进入产研共审</button></>}
|
|
143
|
+
{selected?.stage === 'joint-review' && <><button disabled={!selected.workspaceId} onClick={() => void requestReview('engineering-precheck')}>研发智能预审</button><button onClick={() => void confirm(participant.role)}>以{participant.role === 'product' ? '产品' : '研发'}确认</button><button className={css.execute} onClick={() => selected && void act(actor => ({ kind: 'ready.generate', participant: actor, requirementId: selected.id }))}>生成就绪规范</button></>}
|
|
144
|
+
<button className={css.identity} onClick={() => setIdentityOpen(true)}>{registered ? `${participant.nickname} · ${participant.role === 'product' ? '产品' : '研发'}` : '匿名只读'}</button>
|
|
145
|
+
</div>
|
|
146
|
+
</header>
|
|
147
|
+
<div className={notice ? css.notice : css.noticeHidden}>{notice}<button aria-label="关闭" onClick={() => setNotice('')}>×</button></div>
|
|
148
|
+
<div className={css.mobileViewSwitch}><button className={mobilePane === 'spec' ? css.activeMode : ''} onClick={() => setMobilePane('spec')}>规范正文</button><button className={mobilePane === 'collab' ? css.activeMode : ''} onClick={() => setMobilePane('collab')}>协作处理{selected ? ` · ${selected.actionItems.filter(item => item.status === 'pending').length}` : ''}</button></div>
|
|
149
|
+
<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}>
|
|
150
|
+
<aside className={`${css.documents} ${documentsOpen ? '' : css.paneClosed}`}><div className={css.paneHead}><strong>{showArchived ? '已归档需求' : '需求'}</strong><div className={css.paneActions}><button onClick={() => { setShowArchived(value => !value); setSelectedId(undefined); setManageMenuId(undefined) }}>{showArchived ? '进行中' : '已归档'}</button>{!showArchived && <button title="输入原始需求" onClick={() => { setCreateOpen(true); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))) }}>+</button>}<button className={css.iconButton} aria-label="收起需求栏" title="收起需求栏" onClick={() => setDocumentsOpen(false)}>‹</button></div></div><nav>{visibleRequirements.map(item => <div className={css.requirementRow} key={item.id}><button className={`${css.documentButton} ${item.id === selected?.id ? css.selectedDoc : ''}`} onClick={() => setSelectedId(item.id)}><span>{item.title}</span><small>{item.archivedAt ? `归档于 ${new Date(item.archivedAt).toLocaleDateString()}` : `${stageLabel(item.stage)} · ${item.actionItems.filter(task => task.status === 'pending' && task.blocking).length} 待办`}</small></button><button className={css.rowMenuButton} aria-label={`${item.title} 更多操作`} title="更多操作" onClick={() => { setSelectedId(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>{visibleRequirements.length === 0 && <div className={css.empty}>{showArchived ? '暂无已归档需求' : '暂无进行中的需求'}</div>}</aside>
|
|
151
|
+
<div className={`${css.resizer} ${documentsOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整需求栏宽度" aria-orientation="vertical" onPointerDown={event => resizePane('documents', event)}/>
|
|
152
|
+
<main className={css.editorPane}>
|
|
153
|
+
<div className={css.toolbar}><div className={css.editorTitle}>{!documentsOpen && <button className={css.iconButton} aria-label="展开需求栏" title="展开需求栏" onClick={() => setDocumentsOpen(true)}>‹</button>}<strong>规范正文</strong></div><div><span className={draft !== selected?.version.markdown ? css.unsaved : css.editorMeta}>{draft !== selected?.version.markdown ? '有未保存修改' : '已保存'} · {draft.split('\n').length} 行</span><input className={css.summaryInput} required aria-label="本次修改说明(必填)" value={summary} onChange={event => setSummary(event.target.value)} placeholder="本次修改说明(必填)"/><button className={css.saveButton} disabled={busy || !selected || draft === selected.version.markdown || !summary.trim()} onClick={() => void save()}>保存新版本</button>{!reviewOpen && <button className={css.iconButton} aria-label="展开协作栏" title="展开协作栏" onClick={() => setReviewOpen(true)}>›</button>}</div></div>
|
|
154
|
+
{draftSelection && <div className={css.editorContext}><div className={css.selectionPrompt}><span>已选 {draftSelection.quote.length} 字 · “{draftSelection.quote.replace(/\s+/g, ' ').slice(0, 48)}{draftSelection.quote.length > 48 ? '…' : ''}”</span><button className={css.commentAction} onClick={captureSelection}>添加评论</button><button aria-label="取消文字选择" title="取消文字选择" onClick={() => setDraftSelection(undefined)}>×</button></div></div>}
|
|
155
|
+
{!selected ? <div className={css.emptyMain}><button onClick={() => { setCreateOpen(true); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))) }}>输入原始需求</button></div> : <div className={css.editorBody}><RichMarkdownEditor key={`${selected.id}:${selected.currentCommit}`} markdown={draft} onChange={setDraft} onSelection={quote => setDraftSelection(quote ? { quote, prefix: '', suffix: '' } : undefined)}/></div>}
|
|
156
|
+
</main>
|
|
157
|
+
<div className={`${css.resizer} ${reviewOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整协作栏宽度" aria-orientation="vertical" onPointerDown={event => resizePane('review', event)}/>
|
|
158
|
+
<aside className={`${css.review} ${reviewOpen ? '' : css.paneClosed}`}>
|
|
159
|
+
<div className={css.tabbar}><div className={css.tabScroller}>{(['review', 'discussion', ...(tabCounts.items > 0 || sideTab === 'items' ? ['items' as const] : []), 'ready', ...(tabCounts.patches > 0 || sideTab === 'patches' ? ['patches' as const] : []), 'decisions', 'versions'] as SideTab[]).map(renderSideTab)}</div><button className={`${css.iconButton} ${css.collapseRight}`} aria-label="收起协作栏" title="收起协作栏" onClick={() => setReviewOpen(false)}>›</button></div>
|
|
160
|
+
<div className={css.threadList}>{selected && sideTab === 'review' && <ReviewPanel requirement={selected} participant={participant} act={act} api={api}/>} {selected && sideTab === 'discussion' && <DiscussionPanel requirement={selected} selection={selection} text={commentText} setText={setCommentText} cancel={() => setSelection(undefined)} submit={addComment} participant={participant} act={act} api={api}/>} {selected && sideTab === 'patches' && <PatchPanel requirement={selected} act={act}/>} {selected && sideTab === 'decisions' && <DecisionPanel requirement={selected} act={act}/>} {selected && sideTab === 'items' && <MyItemsPanel items={currentMyItems} open={item => { setSideTab(item.target.tab); setMobilePane('collab'); window.setTimeout(() => document.getElementById(`spec-object-${item.target.objectId}`)?.scrollIntoView({ block: 'center' }), 100) }}/>} {selected && sideTab === 'versions' && <VersionPanel requirement={selected} api={api}/>} {selected && sideTab === 'ready' && <ReadyPanel requirement={selected} act={act}/>}</div>
|
|
161
|
+
</aside>
|
|
162
|
+
</div>
|
|
163
|
+
<footer className={css.footer}><span>Git + Markdown 正式版本 · AI 只提议不确认</span><span>{selected ? `${selected.actionItems.filter(item => item.status === 'pending').length} 我的/角色事项 · ${selected.aiRuns.at(-1)?.status ?? '无 AI 任务'}` : '严格止于 Ready Spec'}</span></footer>
|
|
164
|
+
{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') } })}/>}
|
|
165
|
+
</div>
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function RichMarkdownEditor({ markdown, onChange, onSelection }: { markdown: string; onChange: (markdown: string) => void; onSelection: (quote: string) => void }) {
|
|
169
|
+
const host = useRef<HTMLDivElement>(null)
|
|
170
|
+
const instance = useRef<ToastEditor>()
|
|
171
|
+
const interacted = useRef(false)
|
|
172
|
+
const syncing = useRef(false)
|
|
173
|
+
const onChangeRef = useRef(onChange)
|
|
174
|
+
const onSelectionRef = useRef(onSelection)
|
|
175
|
+
onChangeRef.current = onChange
|
|
176
|
+
onSelectionRef.current = onSelection
|
|
177
|
+
useEffect(() => {
|
|
178
|
+
if (!host.current) return
|
|
179
|
+
const editor = new ToastEditor({ el: host.current, initialValue: markdown, initialEditType: 'wysiwyg', hideModeSwitch: true, toolbarItems: [], plugins: [markdownShortcutsPlugin], height: '100%', language: 'zh-CN', usageStatistics: false, autofocus: false })
|
|
180
|
+
const markInteraction = (): void => { interacted.current = true }
|
|
181
|
+
const change = (): void => { if (interacted.current && !syncing.current) onChangeRef.current(editor.getMarkdown()) }
|
|
182
|
+
const selection = (): void => onSelectionRef.current(editor.getSelectedText().trim())
|
|
183
|
+
editor.on('change', change)
|
|
184
|
+
host.current.addEventListener('beforeinput', markInteraction)
|
|
185
|
+
host.current.addEventListener('paste', markInteraction)
|
|
186
|
+
host.current.addEventListener('drop', markInteraction)
|
|
187
|
+
host.current.addEventListener('pointerdown', markInteraction)
|
|
188
|
+
host.current.addEventListener('mouseup', selection)
|
|
189
|
+
host.current.addEventListener('keyup', selection)
|
|
190
|
+
instance.current = editor
|
|
191
|
+
return () => { host.current?.removeEventListener('beforeinput', markInteraction); host.current?.removeEventListener('paste', markInteraction); host.current?.removeEventListener('drop', markInteraction); host.current?.removeEventListener('pointerdown', markInteraction); host.current?.removeEventListener('mouseup', selection); host.current?.removeEventListener('keyup', selection); editor.destroy() }
|
|
192
|
+
}, [])
|
|
193
|
+
useEffect(() => {
|
|
194
|
+
const editor = instance.current
|
|
195
|
+
if (!editor || editor.getMarkdown() === markdown) return
|
|
196
|
+
syncing.current = true
|
|
197
|
+
editor.setMarkdown(markdown)
|
|
198
|
+
syncing.current = false
|
|
199
|
+
}, [markdown])
|
|
200
|
+
return <div className={css.richEditor} ref={host}/>
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
type Act = (factory: (actor: ParticipantSnapshot) => CollaborationAction) => Promise<boolean>
|
|
204
|
+
const reviewKindLabel: Record<ReviewKind, string> = { 'product-first': '产品初审', 'product-second': '产品二审', 'engineering-precheck': '研发预审', 'change-review': '变更审核' }
|
|
205
|
+
const statusLabel: Record<string, string> = { queued: '排队中', running: '分析中', completed: '已完成', failed: '失败', open: '待处理', 'joint-review': '待产研共审', 'non-blocking-verify': '非阻塞待验证', resolved: '已解决', invalidated: '已失效', pending: '待确认', accepted: '已接受', rejected: '已拒绝', stale: '已过期', blocking: '阻塞', major: '重要', minor: '一般' }
|
|
206
|
+
function MarkdownBody({ text, className = '' }: { text: string; className?: string | undefined }) { return <div className={`${css.markdownBody} ${className}`} dangerouslySetInnerHTML={{ __html: md.render(text) }}/> }
|
|
207
|
+
function ReviewPanel({ requirement, act, api }: { requirement: RequirementView; participant: ParticipantSnapshot; act: Act; api: SpecApi }) {
|
|
208
|
+
const pendingCount = requirement.reviewItems.filter(item => !['resolved', 'invalidated'].includes(item.status)).length
|
|
209
|
+
return <>
|
|
210
|
+
<div className={css.panelSummary}><div><strong>{pendingCount} 个待处理问题</strong><span>{requirement.reviewItems.filter(item => item.severity === 'blocking' && !['resolved', 'invalidated'].includes(item.status)).length} 个阻塞 · {requirement.reviewItems.length - pendingCount} 个已结束</span></div></div>
|
|
211
|
+
{requirement.aiRuns.length > 0 && <details className={css.runHistory}><summary>智能审核记录({requirement.aiRuns.length})</summary>{requirement.aiRuns.slice().reverse().map(run => <div className={css.run} key={run.id}><div><strong>{reviewKindLabel[run.kind]}</strong><span>{statusLabel[run.status] ?? run.status}{run.sessionId ? ` · ${run.sessionId.slice(0, 8)}` : ''}</span></div>{run.maturitySummary && <MarkdownBody text={run.maturitySummary}/>} {run.error && <p className={css.chatError}>{run.error}</p>}{run.sessionId && <AiConversation api={api} requirementId={requirement.id} sessionId={run.sessionId}/>}</div>)}</details>}
|
|
212
|
+
{requirement.reviewItems.slice().reverse().map(item => <ReviewItemCard key={item.id} item={item} requirementId={requirement.id} act={act}/>)}
|
|
213
|
+
</>
|
|
214
|
+
}
|
|
215
|
+
function ReviewItemCard({ item, requirementId, act }: { item: RequirementView['reviewItems'][number]; requirementId: string; act: Act }) {
|
|
216
|
+
const ended = ['resolved', 'invalidated'].includes(item.status)
|
|
217
|
+
const content = <div className={css.reviewCardBody}><div className={css.badges}><b>{statusLabel[item.severity] ?? item.severity}</b><span>{item.epistemicStatus}</span></div><div className={css.reviewField}><span>影响</span><MarkdownBody text={item.impact}/></div><div className={`${css.reviewField} ${css.questionField}`}><span>待回答问题</span><MarkdownBody text={item.question}/></div><details className={css.evidence}><summary>查看依据 · {item.evidence.length} 条</summary>{item.evidence.length === 0 ? <p>暂无可访问证据,按 TO_VERIFY 处理。</p> : item.evidence.map((evidence, index) => <div key={`${evidence.source}-${index}`}><code>{evidence.source}{evidence.version ? `@${evidence.version}` : ''}</code><MarkdownBody text={evidence.statement}/></div>)}</details>{!item.response && item.status === 'open' && <ReviewResponseForm requirementId={requirementId} reviewItemId={item.id} reviewKind={item.reviewKind} {...(item.recommendedOptions ? { options: item.recommendedOptions } : {})} act={act}/>} {item.response && <div className={css.humanResponse}><strong>{item.response.participant.nickname} 的回复</strong><MarkdownBody text={item.response.body}/></div>}</div>
|
|
218
|
+
return <details id={`spec-object-${item.id}`} className={`${css.reviewDetails} ${ended ? css.endedReview : css.pendingReview}`} open={!ended}><summary><span>{item.statement}</span><b>{statusLabel[item.status] ?? item.status}</b></summary>{content}</details>
|
|
219
|
+
}
|
|
220
|
+
const dispositionLabel = { context: '补充业务语境或规则', evidence: '提供数据、案例或链接', accept: '接受 AI 建议', 'accept-modified': '修改后接受', reject: '不采纳并说明理由', 'to-verify': '当前无法回答,转待验证', 'joint-review': '转入产研共审' } as const
|
|
221
|
+
function ReviewResponseForm({ requirementId, reviewItemId, reviewKind, options, act }: { requirementId: string; reviewItemId: string; reviewKind: ReviewKind; options?: string[]; act: Act }) {
|
|
222
|
+
const [open, setOpen] = useState(false)
|
|
223
|
+
const [disposition, setDisposition] = useState<keyof typeof dispositionLabel>('context')
|
|
224
|
+
const [body, setBody] = useState('')
|
|
225
|
+
const recommendations = options?.map(option => option.trim()).filter(Boolean) ?? []
|
|
226
|
+
const choose = (option: string): void => { setBody(option); setDisposition('accept-modified'); setOpen(true) }
|
|
227
|
+
const submit = async (): Promise<void> => { if (await act(actor => ({ kind: 'review.respond', participant: actor, requirementId, reviewItemId, disposition, body }))) { setOpen(false); setBody('') } }
|
|
228
|
+
return <>{recommendations.length >= 3 ? <div className={css.quickOptions}><span>业务决策选项</span>{recommendations.slice(0, 5).map((option, index) => <button key={`${index}-${option}`} onClick={() => choose(option)}>{index + 1}. {option}</button>)}</div> : <div className={css.missingOptions}><span>此历史问题暂无基于业务上下文生成的推荐选项。</span><button onClick={() => void act(actor => ({ kind: 'review.request', participant: actor, requirementId, reviewKind }))}>重新智能审核生成</button></div>}{open ? <div className={css.responseForm}><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><label>回复内容(必填)<textarea required autoFocus value={body} onChange={event => setBody(event.target.value)} placeholder={disposition === 'evidence' ? '粘贴数据、案例或来源链接,并说明它支持什么结论' : '说明你的判断、规则或取舍'}/></label><div className={css.cardActions}><button onClick={() => setOpen(false)}>取消</button><button className={css.execute} disabled={!body.trim()} onClick={() => void submit()}>提交回复</button></div></div> : <div className={css.cardActions}><button onClick={() => setOpen(true)}>自行输入</button><button onClick={() => void act(actor => ({ kind: 'review.respond', participant: actor, requirementId, reviewItemId, disposition: 'joint-review', body: '转产研共同决策' }))}>转产研共审</button></div>}</>
|
|
229
|
+
}
|
|
230
|
+
function DiscussionPanel({ requirement, selection, text, setText, cancel, submit, act, api }: { requirement: RequirementView; selection: { quote: string } | undefined; text: string; setText: (value: string) => void; cancel: () => void; submit: () => Promise<void>; participant: ParticipantSnapshot; act: Act; api: SpecApi }) { return <>{selection && <section className={css.newThread}><blockquote>{selection.quote}</blockquote><label>评论内容(必填)<textarea required value={text} onChange={event => setText(event.target.value)} placeholder="输入实质评论;提交后智能助手自动分析"/></label><div><button onClick={cancel}>取消</button><button disabled={!text.trim()} onClick={() => void submit()}>提交并邀请智能助手</button></div></section>}{requirement.comments.slice().reverse().map(comment => <section id={`spec-object-${comment.id}`} key={comment.id}><blockquote>{comment.anchor.quote}</blockquote><strong>{comment.author.nickname}</strong><MarkdownBody text={comment.body}/><small>智能分析:{comment.aiStatus}{comment.aiSessionId ? ` · ${comment.aiSessionId.slice(0, 8)}` : ''}</small>{comment.aiSessionId && <AiConversation api={api} requirementId={requirement.id} sessionId={comment.aiSessionId}/>} {comment.replies.map(reply => <div className={css.reply} key={reply.id}><strong>{reply.author.nickname}{reply.author.kind === 'ai' ? ' · 智能助手' : ''}</strong><MarkdownBody text={reply.body}/></div>)}{comment.status === 'open' && <div>{(['written-back', 'decision', 'rejected', 'open-question'] as CommentResolution[]).map(resolution => <button key={resolution} onClick={() => void act(actor => ({ kind: 'comment.resolve', participant: actor, requirementId: requirement.id, commentId: comment.id, resolution }))}>{({ 'written-back': '已回写正文', decision: '形成决策', rejected: '不采纳', 'open-question': '转为开放问题' })[resolution]}</button>)}</div>}</section>)}</> }
|
|
231
|
+
function AiConversation({ api, requirementId, sessionId }: { api: SpecApi; requirementId: string; sessionId: string }) {
|
|
232
|
+
const [open, setOpen] = useState(false)
|
|
233
|
+
const [messages, setMessages] = useState<Array<{ role: 'user' | 'assistant'; text: string }>>([])
|
|
234
|
+
const [draft, setDraft] = useState('')
|
|
235
|
+
const [error, setError] = useState('')
|
|
236
|
+
const [sending, setSending] = useState(false)
|
|
237
|
+
const load = async (): Promise<void> => { try { setMessages(await api.conversation(requirementId, sessionId)); setError('') } catch (reason) { setError(reason instanceof Error ? reason.message : String(reason)) } }
|
|
238
|
+
useEffect(() => { if (!open) return; void load(); const timer = window.setInterval(() => { void load() }, 3000); return () => window.clearInterval(timer) }, [open, requirementId, sessionId])
|
|
239
|
+
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) } }
|
|
240
|
+
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>
|
|
241
|
+
}
|
|
242
|
+
function PatchPanel({ requirement, act }: { requirement: RequirementView; act: Act }) {
|
|
243
|
+
const [summaries, setSummaries] = useState<Record<string, string>>({})
|
|
244
|
+
const [submitting, setSubmitting] = useState<string>()
|
|
245
|
+
return <>{requirement.patches.slice().reverse().map(patch => {
|
|
246
|
+
const chinese = /[\u3400-\u9fff]/.test(`${patch.summary}\n${patch.proposedMarkdown}`)
|
|
247
|
+
const commitSummary = summaries[patch.id] ?? `接受中文候选 Patch:${patch.summary}`
|
|
248
|
+
return <article id={`spec-object-${patch.id}`} className={css.reviewCard} key={patch.id}>
|
|
249
|
+
<div className={css.badges}><b>{statusLabel[patch.status] ?? patch.status}</b><span>{reviewKindLabel[patch.reviewKind]}</span><span>{patch.baseCommit.slice(0, 8)}</span></div>
|
|
250
|
+
<MarkdownBody text={patch.summary} className={css.reviewTitle}/>
|
|
251
|
+
{!chinese && <div className={css.legacyWarning}><strong>旧版英文候选</strong><p>这份修改建议在中文约束上线前生成,已禁止接受。请重新运行中文审核。</p></div>}
|
|
252
|
+
<details className={css.patchDetails}><summary>预览候选规范</summary><MarkdownBody text={patch.proposedMarkdown}/></details>
|
|
253
|
+
{patch.status === 'pending' && (chinese ? <div className={css.patchAccept}><label>版本提交说明(必填)<input required value={commitSummary} onChange={event => setSummaries(current => ({ ...current, [patch.id]: event.target.value }))}/></label><div className={css.cardActions}><button 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>)}
|
|
254
|
+
</article>
|
|
255
|
+
})}</>
|
|
256
|
+
}
|
|
257
|
+
function DecisionPanel({ requirement, act }: { requirement: RequirementView; act: Act }) {
|
|
258
|
+
const [open, setOpen] = useState(false)
|
|
259
|
+
const [form, setForm] = useState({ question: '', decision: '', rationale: '' })
|
|
260
|
+
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: '' }) } }
|
|
261
|
+
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}</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><div className={css.cardActions}><button onClick={() => setOpen(false)}>取消</button><button className={css.execute} disabled={!form.question.trim() || !form.decision.trim()} onClick={() => void submit()}>保存决策</button></div></div> : <button className={css.panelAction} onClick={() => setOpen(true)}>记录新决策</button>}</>
|
|
262
|
+
}
|
|
263
|
+
function VersionPanel({ requirement, api }: { requirement: RequirementView; api: SpecApi }) {
|
|
264
|
+
const [historical, setHistorical] = useState<RequirementVersion>()
|
|
265
|
+
const [loading, setLoading] = useState(false)
|
|
266
|
+
const [error, setError] = useState('')
|
|
267
|
+
const open = async (commit: string): Promise<void> => { setLoading(true); setError(''); try { setHistorical(await api.version(requirement.id, commit)) } catch (reason) { setError(reason instanceof Error ? reason.message : String(reason)) } finally { setLoading(false) } }
|
|
268
|
+
return <>{historical && <div className={css.versionCompare}><div className={css.compareHead}><strong>版本内容比对</strong><button aria-label="关闭版本比对" title="关闭版本比对" onClick={() => setHistorical(undefined)}>×</button></div><div className={css.compareColumns}><section><b>历史版本 · {historical.commit.slice(0, 8)}</b><MarkdownBody text={historical.markdown}/></section><section><b>当前版本 · {requirement.currentCommit.slice(0, 8)}</b><MarkdownBody text={requirement.version.markdown}/></section></div></div>}{error && <p className={css.chatError}>{error}</p>}{requirement.history.map(version => <button className={css.versionRow} key={version.commit} disabled={loading} onClick={() => void open(version.commit)}><code>{version.commit.slice(0, 10)}</code><span>{version.summary}</span><small>{version.author.nickname} · {new Date(version.createdAt).toLocaleString()}</small></button>)}</>
|
|
269
|
+
}
|
|
270
|
+
const readinessLabel: Record<string, string> = { goal: '目标与用户结果', acceptance: '验收标准', scope: '范围与非范围', semantics: '业务语义', evidence: '证据来源', 'test-constraints': '测试约束' }
|
|
271
|
+
function ReadyPanel({ requirement, act }: { requirement: RequirementView; act: Act }) {
|
|
272
|
+
const [returnOpen, setReturnOpen] = useState(false)
|
|
273
|
+
const [form, setForm] = useState({ summary: '', sections: '', acceptanceIds: '', source: '', version: '', evidence: '' })
|
|
274
|
+
const submitReturn = async (): Promise<void> => {
|
|
275
|
+
const ok = await act(actor => ({ kind: 'downstream.return', participant: actor, requirementId: requirement.id, summary: form.summary, affectedSections: form.sections.split(',').map(value => value.trim()).filter(Boolean), affectedAcceptanceIds: form.acceptanceIds.split(',').map(value => value.trim()).filter(Boolean), evidence: form.source.trim() ? [{ statement: form.evidence || form.summary, source: form.source, ...(form.version.trim() ? { version: form.version.trim() } : {}), accessible: true }] : [] }))
|
|
276
|
+
if (ok) { setReturnOpen(false); setForm({ summary: '', sections: '', acceptanceIds: '', source: '', version: '', evidence: '' }) }
|
|
277
|
+
}
|
|
278
|
+
const passed = requirement.readiness.filter(check => check.passed).length
|
|
279
|
+
return <><div className={css.readyHead}><h3>Ready 质量门</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><strong>Ready Spec · {requirement.readyPackage.packageHash.slice(0, 12)}</strong><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>}</>
|
|
280
|
+
}
|
|
281
|
+
const categoryLabel: Record<MyActionItem['category'], string> = { 'awaiting-my-response': '待我回复', 'awaiting-my-confirmation': '待我确认', 'initiated-by-me': '我发起的', 'possibly-mine-by-ip': '可能属于当前 IP' }
|
|
282
|
+
function MyItemsPanel({ items, open }: { items: MyActionItem[]; open: (item: MyActionItem) => void }) {
|
|
283
|
+
const categories = ['awaiting-my-response', 'awaiting-my-confirmation', 'initiated-by-me', 'possibly-mine-by-ip'] as const
|
|
284
|
+
return <div className={css.itemsPanel}>{categories.map(category => <section key={category}><h3>{categoryLabel[category]} · {items.filter(item => item.category === category).length}</h3>{items.filter(item => item.category === category).map(item => <button className={css.itemRow} key={`${category}-${item.id}`} onClick={() => open(item)}><span><b>{item.blocking ? '阻塞' : '普通'}</b> · {item.requirementTitle}</span><small>{item.type === 'reconfirm' ? '需要重新确认' : item.type === 'confirm' ? '等待确认' : '等待回复'} · {new Date(item.updatedAt).toLocaleString()}</small></button>)}{items.every(item => item.category !== category) && <p className={css.empty}>当前需求暂无事项</p>}</section>)}</div>
|
|
285
|
+
}
|
|
286
|
+
function ConflictDialog({ conflict, value, setValue, close, submit, busy }: { conflict: SaveConflict; value: string; setValue: (value: string) => void; close: () => void; submit: () => void; busy: boolean }) {
|
|
287
|
+
return <div className={`${css.modal} ${css.conflictModal}`}><div className={css.conflictDialog}><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></div></div>
|
|
288
|
+
}
|
|
289
|
+
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>匿名可读。首次成功写入后,Host 会将 participant_id 与责任角色绑定;IP 不作为身份或权限依据。</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>该身份已由 Host 绑定为{boundRole === 'product' ? '产品' : '研发'}角色。</small>}<button type="submit" disabled={value.nickname.trim().length < 2}>保存身份</button></form></div> }
|
|
290
|
+
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> }
|
|
291
|
+
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> }
|
|
292
|
+
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><label>项目工作区(必填)<select required autoFocus value={value} onChange={event => setValue(event.target.value)}><option value="" disabled>{workspaces.length > 0 ? '选择 DSH 项目工作区' : '暂无可用的 DSH 工作区'}</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> }
|
|
293
|
+
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><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 ? '选择 DSH 项目工作区' : '暂无可用的 DSH 工作区'}</option>{workspaces.map(workspace => <option key={workspace.workspaceId} value={workspace.workspaceId}>{workspace.title} · {workspace.path}</option>)}</select></label><label>自然语言需求或已有 Markdown(必填)<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="https://... 历史 Decision ... workspace/repository scope"/></label><div><button type="button" onClick={close}>取消</button><button type="submit" disabled={busy || !value.title.trim() || !value.rawRequirement.trim() || !value.workspaceId}>创建并固定输入版本</button></div></form></div> }
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { API_PREFIX, type ActionEnvelope, type ActionResult, type CollaborationAction, type MyActionItem, type ParticipantSnapshot, type RequirementVersion, type RequirementView, type ReviewWorkspaceSummary } from '../protocol.ts'
|
|
2
|
+
export interface ClientState { revision: number; participants: ParticipantSnapshot[]; requirements: RequirementView[] }
|
|
3
|
+
export class SpecApi {
|
|
4
|
+
async state(): Promise<ClientState> { const response = await fetch(`${API_PREFIX}/state`, { headers: { accept: 'application/json' } }); if (!response.ok) throw new Error(`state request failed (${response.status})`); const state = await response.json() as Partial<ClientState>; return { revision: state.revision ?? 0, participants: state.participants ?? [], requirements: state.requirements ?? [] } }
|
|
5
|
+
async reviewWorkspaces(): Promise<ReviewWorkspaceSummary[]> { const response = await fetch(`${API_PREFIX}/review-workspaces`, { headers: { accept: 'application/json' } }); const result = await response.json() as { ok: boolean; workspaces?: ReviewWorkspaceSummary[]; error?: string }; if (!response.ok || !result.ok) throw new Error(result.error ?? '加载需求工作区失败'); return result.workspaces ?? [] }
|
|
6
|
+
async action(action: CollaborationAction): Promise<ActionResult> { const envelope: ActionEnvelope = { requestId: crypto.randomUUID(), action }; const response = await fetch(`${API_PREFIX}/action`, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify(envelope) }); return response.json() as Promise<ActionResult> }
|
|
7
|
+
async myItems(participant: ParticipantSnapshot): Promise<MyActionItem[]> { const query = new URLSearchParams({ participantId: participant.participantId, role: participant.role }); const response = await fetch(`${API_PREFIX}/my-items?${query}`, { headers: { accept: 'application/json' } }); const result = await response.json() as { ok: boolean; items?: MyActionItem[]; error?: string }; if (!response.ok || !result.ok) throw new Error(result.error ?? '加载我的事项失败'); return result.items ?? [] }
|
|
8
|
+
async version(requirementId: string, commit: string): Promise<RequirementVersion> { const query = new URLSearchParams({ requirementId, commit }); const response = await fetch(`${API_PREFIX}/version?${query}`, { headers: { accept: 'application/json' } }); const result = await response.json() as { ok: boolean; version?: RequirementVersion; error?: string }; if (!response.ok || !result.ok || !result.version) throw new Error(result.error ?? '加载历史版本失败'); return result.version }
|
|
9
|
+
async conversation(requirementId: string, sessionId: string): Promise<Array<{ role: 'user' | 'assistant'; text: string }>> { const query = new URLSearchParams({ requirementId, sessionId }); const response = await fetch(`${API_PREFIX}/ai-conversation?${query}`, { headers: { accept: 'application/json' } }); const result = await response.json() as { ok: boolean; messages?: Array<{ role: 'user' | 'assistant'; text: string }>; error?: string }; if (!response.ok || !result.ok) throw new Error(result.error ?? '加载 AI 对话失败'); return result.messages ?? [] }
|
|
10
|
+
async followUp(requirementId: string, sessionId: string, text: string): Promise<void> { const response = await fetch(`${API_PREFIX}/ai-conversation`, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify({ requirementId, sessionId, text }) }); const result = await response.json() as { ok: boolean; error?: string }; if (!response.ok || !result.ok) throw new Error(result.error ?? '发送追问失败') }
|
|
11
|
+
events(onChange: () => void): () => void { const events = new EventSource(`${API_PREFIX}/events`); events.onmessage = onChange; return () => events.close() }
|
|
12
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
declare module '*.module.css' { const classes: Record<string, string>; export default classes }
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'
|
|
2
|
+
import { SpecApi } from './api.ts'
|
|
3
|
+
import { mountSidebarEntry, mountWorkbench } from './mount.tsx'
|
|
4
|
+
|
|
5
|
+
export const inject = ['sessions']
|
|
6
|
+
|
|
7
|
+
export function apply(ctx: ClientContext): void {
|
|
8
|
+
const api = new SpecApi()
|
|
9
|
+
const disposers: Array<() => void> = []
|
|
10
|
+
try {
|
|
11
|
+
disposers.push(mountSidebarEntry(), mountWorkbench(api))
|
|
12
|
+
} catch (error) {
|
|
13
|
+
console.error('[dsh-spec-collab] UI mount failed', error)
|
|
14
|
+
}
|
|
15
|
+
ctx.effect(() => () => { for (const dispose of disposers.splice(0)) dispose() }, 'spec-collab: ui mounts')
|
|
16
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { Root } from 'react-dom/client'
|
|
2
|
+
import { createRoot } from 'react-dom/client'
|
|
3
|
+
import type { SpecApi } from './api.ts'
|
|
4
|
+
import { SpecWorkbench } from './SpecWorkbench.tsx'
|
|
5
|
+
import css from './workbench.module.css'
|
|
6
|
+
|
|
7
|
+
const ACTIVE = 'data-dsh-spec-collab-active'
|
|
8
|
+
const VIEW = '[data-dsh-spec-collab-view]'
|
|
9
|
+
const ACTIVATE_EVENT = 'dsh-panel-activate'
|
|
10
|
+
|
|
11
|
+
export function mountWorkbench(api: SpecApi): () => void {
|
|
12
|
+
let root: Root | undefined
|
|
13
|
+
let container: HTMLDivElement | undefined
|
|
14
|
+
const ensure = (): void => {
|
|
15
|
+
if (container?.isConnected) return
|
|
16
|
+
root?.unmount()
|
|
17
|
+
container?.remove()
|
|
18
|
+
const column = document.querySelector<HTMLElement>('[data-pane="conversation"], [class*="centerCol"]')
|
|
19
|
+
if (column === null) return
|
|
20
|
+
container = document.createElement('div')
|
|
21
|
+
container.dataset.dshSpecCollabView = ''
|
|
22
|
+
container.className = css.view!
|
|
23
|
+
column.appendChild(container)
|
|
24
|
+
root = createRoot(container)
|
|
25
|
+
root.render(<SpecWorkbench api={api} />)
|
|
26
|
+
}
|
|
27
|
+
const observer = new MutationObserver(ensure)
|
|
28
|
+
observer.observe(document.body, { childList: true, subtree: true })
|
|
29
|
+
ensure()
|
|
30
|
+
return () => { observer.disconnect(); document.documentElement.removeAttribute(ACTIVE); root?.unmount(); container?.remove() }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function mountSidebarEntry(): () => void {
|
|
34
|
+
let row: HTMLButtonElement | undefined
|
|
35
|
+
const close = (): void => { document.documentElement.removeAttribute(ACTIVE); row?.classList.remove(css.entryActive!) }
|
|
36
|
+
const closeOnExternalNavigation = (event: MouseEvent): void => {
|
|
37
|
+
if (!document.documentElement.hasAttribute(ACTIVE)) return
|
|
38
|
+
const target = event.target instanceof Element ? event.target : undefined
|
|
39
|
+
if (target?.closest(VIEW) || target?.closest('[data-dsh-spec-collab-entry]')) return
|
|
40
|
+
close()
|
|
41
|
+
}
|
|
42
|
+
document.addEventListener('click', closeOnExternalNavigation, true)
|
|
43
|
+
const toggle = (): void => {
|
|
44
|
+
const opening = !document.documentElement.hasAttribute(ACTIVE)
|
|
45
|
+
for (const name of document.documentElement.getAttributeNames()) {
|
|
46
|
+
if (name.startsWith('data-dsh-') && name.endsWith('-active')) document.documentElement.removeAttribute(name)
|
|
47
|
+
}
|
|
48
|
+
if (opening) {
|
|
49
|
+
document.documentElement.setAttribute(ACTIVE, '')
|
|
50
|
+
document.dispatchEvent(new CustomEvent(ACTIVATE_EVENT, { detail: 'spec-collab' }))
|
|
51
|
+
}
|
|
52
|
+
row?.classList.toggle(css.entryActive!, opening)
|
|
53
|
+
}
|
|
54
|
+
const ensure = (): void => {
|
|
55
|
+
if (row?.isConnected) return
|
|
56
|
+
const skillCenter = document.querySelector<HTMLElement>('button[aria-label="技能中心"]')
|
|
57
|
+
?? [...document.querySelectorAll<HTMLButtonElement>('button')].find(button => button.textContent?.trim() === '技能中心')
|
|
58
|
+
if (skillCenter === undefined || skillCenter === null) return
|
|
59
|
+
row = document.createElement('button')
|
|
60
|
+
row.type = 'button'
|
|
61
|
+
row.dataset.dshSpecCollabEntry = ''
|
|
62
|
+
row.className = `${skillCenter.className} ${css.entry!}`
|
|
63
|
+
row.title = '需求讨论'
|
|
64
|
+
row.setAttribute('aria-label', '需求讨论')
|
|
65
|
+
row.innerHTML = '<span aria-hidden="true">▤</span><span>需求讨论</span>'
|
|
66
|
+
row.addEventListener('click', toggle)
|
|
67
|
+
skillCenter.after(row)
|
|
68
|
+
}
|
|
69
|
+
const observer = new MutationObserver(ensure)
|
|
70
|
+
observer.observe(document.body, { childList: true, subtree: true })
|
|
71
|
+
ensure()
|
|
72
|
+
return () => { observer.disconnect(); document.removeEventListener('click', closeOnExternalNavigation, true); close(); row?.remove(); document.querySelector(VIEW)?.remove() }
|
|
73
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
declare module '@toast-ui/editor' {
|
|
2
|
+
export interface EditorOptions {
|
|
3
|
+
el: HTMLElement
|
|
4
|
+
initialValue?: string
|
|
5
|
+
initialEditType?: 'markdown' | 'wysiwyg'
|
|
6
|
+
hideModeSwitch?: boolean
|
|
7
|
+
toolbarItems?: unknown[][]
|
|
8
|
+
plugins?: Array<(context: unknown) => unknown>
|
|
9
|
+
height?: string
|
|
10
|
+
language?: string
|
|
11
|
+
usageStatistics?: boolean
|
|
12
|
+
autofocus?: boolean
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export default class ToastEditor {
|
|
16
|
+
constructor(options: EditorOptions)
|
|
17
|
+
on(type: string, handler: () => void): void
|
|
18
|
+
getMarkdown(): string
|
|
19
|
+
setMarkdown(markdown: string): void
|
|
20
|
+
getSelectedText(): string
|
|
21
|
+
destroy(): void
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
declare module '@toast-ui/editor/dist/i18n/zh-cn'
|