dsh-spec-collab 0.2.1 → 0.3.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/README.md +28 -7
- 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 +142 -0
- package/docs/insight-import-template.csv +3 -0
- package/docs/insight-import-template.md +19 -0
- package/docs/migration-v3.md +23 -0
- package/lib/client.js +11456 -1275
- package/lib/index.js +1335 -93
- 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 +94 -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 +5 -2
- package/lib/types/client/review-anchors.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 -8
- package/lib/types/protocol.d.ts.map +1 -1
- 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 +5 -2
- package/src/client/AccessibleDialog.tsx +42 -0
- package/src/client/SpecWorkbench.tsx +1084 -176
- package/src/client/api.ts +8 -3
- package/src/client/drafts.ts +51 -0
- package/src/client/mount.tsx +40 -9
- package/src/client/review-anchors.ts +66 -18
- package/src/client/workbench.module.css +330 -73
- package/src/engine.ts +485 -44
- package/src/git-store.ts +87 -18
- package/src/index.ts +1 -1
- package/src/protocol.ts +64 -13
- 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/src/client/api.ts
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
|
-
import { API_PREFIX, type ActionEnvelope, type ActionResult, type CollaborationAction, type MyActionItem, type ParticipantSnapshot, type RequirementVersion, type RequirementView, type ReviewWorkspaceSummary } from '../protocol.ts'
|
|
1
|
+
import { API_PREFIX, type ActionEnvelope, type ActionResult, type CollaborationAction, type Company, type Customer, type FeedbackSource, type Insight, type InsightImportance, type InsightLink, type MyActionItem, type Notification, type ParticipantSnapshot, type RequirementSummary, type RequirementVersion, type RequirementView, type ReviewWorkspaceSummary, type StructuredDiff } from '../protocol.ts'
|
|
2
2
|
import { browserUuid } from './browser-uuid.ts'
|
|
3
|
-
export interface ClientState { revision: number; participants: ParticipantSnapshot[]; requirements:
|
|
3
|
+
export interface ClientState { revision: number; participants: ParticipantSnapshot[]; requirements: RequirementSummary[]; requirement?: RequirementView }
|
|
4
4
|
export class SpecApi {
|
|
5
|
-
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 state(requirementId?: string): Promise<ClientState> { const query = requirementId ? `?${new URLSearchParams({ requirementId })}` : ''; const response = await fetch(`${API_PREFIX}/state${query}`, { 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 ?? [], ...(state.requirement ? { requirement: state.requirement } : {}) } }
|
|
6
6
|
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 ?? [] }
|
|
7
7
|
async action(action: CollaborationAction): Promise<ActionResult> { const envelope: ActionEnvelope = { requestId: browserUuid(), 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> }
|
|
8
8
|
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 ?? [] }
|
|
9
9
|
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 }
|
|
10
|
+
async directory(): Promise<ParticipantSnapshot[]> { const response = await fetch(`${API_PREFIX}/directory`, { headers: { accept: 'application/json' } }); const result = await response.json() as { ok: boolean; participants?: ParticipantSnapshot[]; error?: string }; if (!response.ok || !result.ok) throw new Error(result.error ?? '加载协作成员失败'); return result.participants ?? [] }
|
|
11
|
+
async notifications(participantId: string): Promise<{ items: Notification[]; total: number; unread: number }> { const query = new URLSearchParams({ participantId }); const response = await fetch(`${API_PREFIX}/notifications?${query}`, { headers: { accept: 'application/json' } }); const result = await response.json() as { ok: boolean; items?: Notification[]; total?: number; unread?: number; error?: string }; if (!response.ok || !result.ok) throw new Error(result.error ?? '加载通知失败'); return { items: result.items ?? [], total: result.total ?? 0, unread: result.unread ?? 0 } }
|
|
12
|
+
async insights(queryInput: { requirementId?: string; customerId?: string; companyId?: string; sourceId?: string; importance?: InsightImportance } = {}): Promise<{ items: Insight[]; total: number; links: InsightLink[]; customers: Customer[]; companies: Company[]; sources: FeedbackSource[] }> { const query = new URLSearchParams(Object.entries(queryInput).filter((entry): entry is [string, string] => typeof entry[1] === 'string')); const response = await fetch(`${API_PREFIX}/insights?${query}`, { headers: { accept: 'application/json' } }); const result = await response.json() as { ok: boolean; items?: Insight[]; total?: number; links?: InsightLink[]; customers?: Customer[]; companies?: Company[]; sources?: FeedbackSource[]; error?: string }; if (!response.ok || !result.ok) throw new Error(result.error ?? '加载客户洞察失败'); return { items: result.items ?? [], total: result.total ?? 0, links: result.links ?? [], customers: result.customers ?? [], companies: result.companies ?? [], sources: result.sources ?? [] } }
|
|
13
|
+
async diff(requirementId: string, baseCommit: string, headCommit?: string): Promise<StructuredDiff> { const query = new URLSearchParams({ requirementId, baseCommit, ...(headCommit ? { headCommit } : {}) }); const response = await fetch(`${API_PREFIX}/diff?${query}`, { headers: { accept: 'application/json' } }); const result = await response.json() as { ok: boolean; diff?: StructuredDiff; error?: string }; if (!response.ok || !result.ok || !result.diff) throw new Error(result.error ?? '加载版本差异失败'); return result.diff }
|
|
14
|
+
async previewDiff(before: string, after: string, baseLabel?: string, headLabel?: string): Promise<StructuredDiff> { const response = await fetch(`${API_PREFIX}/diff`, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify({ before, after, baseLabel, headLabel }) }); const result = await response.json() as { ok: boolean; diff?: StructuredDiff; error?: string }; if (!response.ok || !result.ok || !result.diff) throw new Error(result.error ?? '生成差异失败'); return result.diff }
|
|
10
15
|
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 ?? [] }
|
|
11
16
|
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 ?? '发送追问失败') }
|
|
12
17
|
events(onChange: () => void): () => void { const events = new EventSource(`${API_PREFIX}/events`); events.onmessage = onChange; return () => events.close() }
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { DraftRecord } from '../protocol.ts'
|
|
2
|
+
|
|
3
|
+
const DATABASE = 'dsh-spec-collab'
|
|
4
|
+
const STORE = 'drafts'
|
|
5
|
+
const FALLBACK = 'dsh-spec-collab.draft.'
|
|
6
|
+
|
|
7
|
+
export function draftKey(requirementId: string, participantId: string): string { return `${requirementId}:${participantId}` }
|
|
8
|
+
|
|
9
|
+
export async function loadDraft(requirementId: string, participantId: string): Promise<DraftRecord | undefined> {
|
|
10
|
+
const key = draftKey(requirementId, participantId)
|
|
11
|
+
if (typeof indexedDB === 'undefined') return fallbackRead(key)
|
|
12
|
+
try { return await request<DraftRecord | undefined>('readonly', store => store.get(key)) } catch { return fallbackRead(key) }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function saveDraft(record: DraftRecord): Promise<void> {
|
|
16
|
+
const key = draftKey(record.requirementId, record.participantId)
|
|
17
|
+
if (typeof indexedDB === 'undefined') return fallbackWrite(key, record)
|
|
18
|
+
try { await request('readwrite', store => store.put(record, key)) } catch { fallbackWrite(key, record) }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function deleteDraft(requirementId: string, participantId: string): Promise<void> {
|
|
22
|
+
const key = draftKey(requirementId, participantId)
|
|
23
|
+
localStorage.removeItem(`${FALLBACK}${key}`)
|
|
24
|
+
if (typeof indexedDB === 'undefined') return
|
|
25
|
+
try { await request('readwrite', store => store.delete(key)) } catch {}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function request<T = undefined>(mode: IDBTransactionMode, operation: (store: IDBObjectStore) => IDBRequest): Promise<T> {
|
|
29
|
+
return new Promise((resolve, reject) => {
|
|
30
|
+
const opening = indexedDB.open(DATABASE, 1)
|
|
31
|
+
opening.onupgradeneeded = () => { if (!opening.result.objectStoreNames.contains(STORE)) opening.result.createObjectStore(STORE) }
|
|
32
|
+
opening.onerror = () => reject(opening.error)
|
|
33
|
+
opening.onsuccess = () => {
|
|
34
|
+
const transaction = opening.result.transaction(STORE, mode); const result = operation(transaction.objectStore(STORE))
|
|
35
|
+
result.onerror = () => reject(result.error)
|
|
36
|
+
result.onsuccess = () => resolve(result.result as T)
|
|
37
|
+
transaction.oncomplete = () => opening.result.close()
|
|
38
|
+
}
|
|
39
|
+
})
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function fallbackRead(key: string): DraftRecord | undefined { try { return JSON.parse(localStorage.getItem(`${FALLBACK}${key}`) ?? '') as DraftRecord } catch { return undefined } }
|
|
43
|
+
function fallbackWrite(key: string, record: DraftRecord): void { localStorage.setItem(`${FALLBACK}${key}`, JSON.stringify(record)) }
|
|
44
|
+
|
|
45
|
+
export function truncateGraphemes(value: string, max: number): string {
|
|
46
|
+
const Segmenter = (Intl as unknown as { Segmenter?: new (locale?: string, options?: { granularity: 'grapheme' }) => { segment(input: string): Iterable<{ segment: string }> } }).Segmenter
|
|
47
|
+
const parts = Segmenter ? [...new Segmenter('zh-CN', { granularity: 'grapheme' }).segment(value)].map(item => item.segment) : Array.from(value)
|
|
48
|
+
return parts.length <= max ? value : `${parts.slice(0, max).join('')}…`
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function safeHttpUrl(value: string): string | undefined { try { const url = new URL(value); return url.protocol === 'http:' || url.protocol === 'https:' ? url.toString() : undefined } catch { return undefined } }
|
package/src/client/mount.tsx
CHANGED
|
@@ -9,6 +9,15 @@ const ACTIVE = 'data-dsh-spec-collab-active'
|
|
|
9
9
|
const VIEW = '[data-dsh-spec-collab-view]'
|
|
10
10
|
const ACTIVATE_EVENT = 'dsh-panel-activate'
|
|
11
11
|
const CLOSE_EVENT = 'dsh-spec-collab-close'
|
|
12
|
+
const REQUEST_CLOSE_EVENT = 'dsh-spec-collab-request-close'
|
|
13
|
+
const SIDEBAR_COLLAPSED = 'data-sidebar-collapsed'
|
|
14
|
+
|
|
15
|
+
function isSidebarChromeControl(target: Element | undefined): boolean {
|
|
16
|
+
const control = target?.closest<HTMLElement>('button, [role="button"]')
|
|
17
|
+
if (control === undefined || control === null) return false
|
|
18
|
+
const label = [control.getAttribute('aria-label'), control.getAttribute('title'), control.textContent].filter(Boolean).join(' ')
|
|
19
|
+
return /侧边栏|边栏|侧栏|sidebar/i.test(label) && /收起|折叠|展开|隐藏|显示|collapse|expand|toggle/i.test(label)
|
|
20
|
+
}
|
|
12
21
|
|
|
13
22
|
export function mountWorkbench(api: SpecApi): () => void {
|
|
14
23
|
let root: Root | undefined
|
|
@@ -34,17 +43,34 @@ export function mountWorkbench(api: SpecApi): () => void {
|
|
|
34
43
|
|
|
35
44
|
export function mountSidebarEntry(): () => void {
|
|
36
45
|
let row: HTMLButtonElement | undefined
|
|
37
|
-
|
|
46
|
+
let resizeObserver: ResizeObserver | undefined
|
|
47
|
+
const syncSidebarState = (): void => {
|
|
48
|
+
if (!row?.isConnected) return
|
|
49
|
+
const rect = row.getBoundingClientRect()
|
|
50
|
+
const hostCollapsed = document.body.hasAttribute('data-dsh-sidebar-collapsed') || Boolean(row.closest('[data-sidebar-collapsed="true"]'))
|
|
51
|
+
row.toggleAttribute('data-dsh-spec-collab-collapsed', rect.width > 0 ? rect.width < 64 : hostCollapsed)
|
|
52
|
+
}
|
|
53
|
+
const deactivate = (): void => { document.documentElement.removeAttribute(ACTIVE); row?.classList.remove(css.entryActive!) }
|
|
54
|
+
const requestClose = (): void => { if (document.dispatchEvent(new CustomEvent(REQUEST_CLOSE_EVENT, { cancelable: true }))) deactivate() }
|
|
55
|
+
const openDeepLink = (): void => { if (location.hash.startsWith('#spec-collab/')) { document.documentElement.setAttribute(ACTIVE, ''); row?.classList.add(css.entryActive!) } }
|
|
38
56
|
const closeOnExternalNavigation = (event: MouseEvent): void => {
|
|
39
57
|
if (!document.documentElement.hasAttribute(ACTIVE)) return
|
|
40
58
|
const target = event.target instanceof Element ? event.target : undefined
|
|
41
|
-
if (target?.closest(VIEW) || target?.closest('[data-dsh-spec-collab-entry]')) return
|
|
42
|
-
|
|
59
|
+
if (target?.closest(VIEW) || target?.closest('[data-dsh-spec-collab-entry]') || target?.closest('[data-dsh-spec-collab-portal]')) return
|
|
60
|
+
if (isSidebarChromeControl(target)) return
|
|
61
|
+
const sidebarCollapsedBefore = document.documentElement.getAttribute(SIDEBAR_COLLAPSED)
|
|
62
|
+
window.setTimeout(() => {
|
|
63
|
+
if (!document.documentElement.hasAttribute(ACTIVE)) return
|
|
64
|
+
if (document.documentElement.getAttribute(SIDEBAR_COLLAPSED) !== sidebarCollapsedBefore) return
|
|
65
|
+
requestClose()
|
|
66
|
+
}, 0)
|
|
43
67
|
}
|
|
44
68
|
document.addEventListener('click', closeOnExternalNavigation, true)
|
|
45
|
-
document.addEventListener(CLOSE_EVENT,
|
|
69
|
+
document.addEventListener(CLOSE_EVENT, deactivate)
|
|
70
|
+
window.addEventListener('hashchange', openDeepLink)
|
|
46
71
|
const toggle = (): void => {
|
|
47
72
|
const opening = !document.documentElement.hasAttribute(ACTIVE)
|
|
73
|
+
if (!opening) { requestClose(); return }
|
|
48
74
|
for (const name of document.documentElement.getAttributeNames()) {
|
|
49
75
|
if (name.startsWith('data-dsh-') && name.endsWith('-active')) document.documentElement.removeAttribute(name)
|
|
50
76
|
}
|
|
@@ -53,9 +79,10 @@ export function mountSidebarEntry(): () => void {
|
|
|
53
79
|
document.dispatchEvent(new CustomEvent(ACTIVATE_EVENT, { detail: 'spec-collab' }))
|
|
54
80
|
}
|
|
55
81
|
row?.classList.toggle(css.entryActive!, opening)
|
|
82
|
+
syncSidebarState()
|
|
56
83
|
}
|
|
57
84
|
const ensure = (): void => {
|
|
58
|
-
if (row?.isConnected) return
|
|
85
|
+
if (row?.isConnected) { syncSidebarState(); return }
|
|
59
86
|
const anchor = findSidebarAnchor(document)
|
|
60
87
|
if (anchor === undefined) return
|
|
61
88
|
row = document.createElement('button')
|
|
@@ -67,9 +94,13 @@ export function mountSidebarEntry(): () => void {
|
|
|
67
94
|
row.innerHTML = '<span aria-hidden="true">▤</span><span>需求讨论</span>'
|
|
68
95
|
row.addEventListener('click', toggle)
|
|
69
96
|
anchor.element[anchor.placement](row)
|
|
97
|
+
resizeObserver?.disconnect()
|
|
98
|
+
resizeObserver = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(syncSidebarState)
|
|
99
|
+
resizeObserver?.observe(row)
|
|
100
|
+
window.setTimeout(syncSidebarState, 0)
|
|
70
101
|
}
|
|
71
|
-
const observer = new MutationObserver(ensure)
|
|
72
|
-
observer.observe(document.body, { childList: true, subtree: true })
|
|
73
|
-
ensure()
|
|
74
|
-
return () => { observer.disconnect(); document.removeEventListener('click', closeOnExternalNavigation, true); document.removeEventListener(CLOSE_EVENT,
|
|
102
|
+
const observer = new MutationObserver(() => { ensure(); syncSidebarState() })
|
|
103
|
+
observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['class', 'data-dsh-sidebar-collapsed', 'data-sidebar-collapsed'] })
|
|
104
|
+
ensure(); openDeepLink()
|
|
105
|
+
return () => { observer.disconnect(); resizeObserver?.disconnect(); document.removeEventListener('click', closeOnExternalNavigation, true); document.removeEventListener(CLOSE_EVENT, deactivate); window.removeEventListener('hashchange', openDeepLink); deactivate(); row?.remove(); document.querySelector(VIEW)?.remove() }
|
|
75
106
|
}
|
|
@@ -1,17 +1,19 @@
|
|
|
1
1
|
import MarkdownIt from 'markdown-it'
|
|
2
|
-
import type { ReviewItem } from '../protocol.ts'
|
|
2
|
+
import type { CommentThread, ReviewItem } from '../protocol.ts'
|
|
3
3
|
|
|
4
4
|
const parser = new MarkdownIt({ html: false })
|
|
5
5
|
export const reviewBlockSelector = 'h1, h2, h3, h4, p, li, td, th, blockquote'
|
|
6
6
|
|
|
7
7
|
export interface ReviewSourceSnippet {
|
|
8
8
|
key: string
|
|
9
|
+
targetKey: string
|
|
9
10
|
label: string
|
|
10
11
|
markdown: string
|
|
11
12
|
line?: number
|
|
12
13
|
}
|
|
13
14
|
|
|
14
15
|
export interface ReviewAnchorTerm {
|
|
16
|
+
key: string
|
|
15
17
|
kind: 'quote' | 'acceptance' | 'section'
|
|
16
18
|
label: string
|
|
17
19
|
value: string
|
|
@@ -23,27 +25,74 @@ export function normalizeReviewText(value: string): string {
|
|
|
23
25
|
|
|
24
26
|
export function reviewAnchorTerms(item: ReviewItem): ReviewAnchorTerm[] {
|
|
25
27
|
const terms: ReviewAnchorTerm[] = []
|
|
26
|
-
for (const anchor of item.sourceAnchors ?? []) {
|
|
27
|
-
|
|
28
|
+
for (const [index, anchor] of (item.sourceAnchors ?? []).entries()) {
|
|
29
|
+
const quote = anchor.quote.trim()
|
|
30
|
+
if (quote) terms.push({ key: `quote-${index}`, kind: 'quote', label: anchor.heading?.trim() || '正文引用', value: quote })
|
|
31
|
+
}
|
|
32
|
+
for (const [index, id] of item.affectedAcceptanceIds.entries()) {
|
|
33
|
+
const value = id.trim()
|
|
34
|
+
if (value) terms.push({ key: `acceptance-${index}-${value}`, kind: 'acceptance', label: value, value })
|
|
35
|
+
}
|
|
36
|
+
for (const [index, section] of item.affectedSections.entries()) {
|
|
37
|
+
const value = section.trim()
|
|
38
|
+
if (value) terms.push({ key: `section-${index}-${value}`, kind: 'section', label: value, value })
|
|
28
39
|
}
|
|
29
|
-
for (const id of item.affectedAcceptanceIds) if (id.trim()) terms.push({ kind: 'acceptance', label: id.trim(), value: id.trim() })
|
|
30
|
-
for (const section of item.affectedSections) if (section.trim()) terms.push({ kind: 'section', label: section.trim(), value: section.trim() })
|
|
31
40
|
return terms
|
|
32
41
|
}
|
|
33
42
|
|
|
34
|
-
export function reviewTargetElements(root: HTMLElement, item: ReviewItem): HTMLElement[] {
|
|
43
|
+
export function reviewTargetElements(root: HTMLElement, item: ReviewItem, targetKey?: string): HTMLElement[] {
|
|
35
44
|
const blocks = Array.from(root.querySelectorAll<HTMLElement>(reviewBlockSelector))
|
|
45
|
+
const terms = reviewAnchorTerms(item)
|
|
36
46
|
const targets: HTMLElement[] = []
|
|
37
|
-
|
|
47
|
+
const addTermTarget = (term: ReviewAnchorTerm): void => {
|
|
38
48
|
const candidates = (term.kind === 'section' ? blocks.filter(block => /^H[1-4]$/.test(block.tagName)) : blocks)
|
|
39
49
|
.filter(block => normalizeReviewText(block.textContent ?? '').includes(normalizeReviewText(term.value)))
|
|
40
50
|
.sort((left, right) => (left.textContent?.length ?? 0) - (right.textContent?.length ?? 0))
|
|
41
51
|
const target = candidates[0]
|
|
42
52
|
if (target && !targets.includes(target)) targets.push(target)
|
|
43
53
|
}
|
|
54
|
+
if (targetKey) {
|
|
55
|
+
terms.filter(term => term.key === targetKey).forEach(addTermTarget)
|
|
56
|
+
if (targets.length > 0) return targets
|
|
57
|
+
}
|
|
58
|
+
terms.forEach(addTermTarget)
|
|
44
59
|
return targets
|
|
45
60
|
}
|
|
46
61
|
|
|
62
|
+
function previousHeadingText(root: HTMLElement, block: HTMLElement): string {
|
|
63
|
+
const headings = Array.from(root.querySelectorAll<HTMLElement>('h1, h2, h3, h4'))
|
|
64
|
+
return headings.filter(heading => Boolean(heading.compareDocumentPosition(block) & Node.DOCUMENT_POSITION_FOLLOWING)).at(-1)?.textContent?.trim() ?? ''
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function commentTargetElements(root: HTMLElement, anchor: CommentThread['anchor']): HTMLElement[] {
|
|
68
|
+
if (anchor === undefined) return []
|
|
69
|
+
const blocks = Array.from(root.querySelectorAll<HTMLElement>(reviewBlockSelector))
|
|
70
|
+
const quote = anchor.quote.trim()
|
|
71
|
+
const normalizedQuote = normalizeReviewText(quote)
|
|
72
|
+
const heading = normalizeReviewText(anchor.heading ?? '')
|
|
73
|
+
const prefix = normalizeReviewText(anchor.prefix ?? '')
|
|
74
|
+
const suffix = normalizeReviewText(anchor.suffix ?? '')
|
|
75
|
+
const context = normalizeReviewText(`${anchor.prefix ?? ''}${quote}${anchor.suffix ?? ''}`)
|
|
76
|
+
const candidates = normalizedQuote
|
|
77
|
+
? blocks.filter(block => normalizeReviewText(block.textContent ?? '').includes(normalizedQuote))
|
|
78
|
+
: []
|
|
79
|
+
|
|
80
|
+
const score = (block: HTMLElement): number => {
|
|
81
|
+
const text = normalizeReviewText(block.textContent ?? '')
|
|
82
|
+
let value = block.textContent?.length ?? 0
|
|
83
|
+
if (heading) value += normalizeReviewText(previousHeadingText(root, block)).includes(heading) ? -10000 : 2500
|
|
84
|
+
if (context && text.includes(context)) value -= 3000
|
|
85
|
+
if (prefix && text.includes(prefix.slice(Math.max(0, prefix.length - 32)))) value -= 900
|
|
86
|
+
if (suffix && text.includes(suffix.slice(0, 32))) value -= 900
|
|
87
|
+
return value
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const targets = candidates.sort((left, right) => score(left) - score(right))
|
|
91
|
+
if (targets.length > 0) return targets
|
|
92
|
+
if (!heading) return []
|
|
93
|
+
return blocks.filter(block => /^H[1-4]$/.test(block.tagName) && normalizeReviewText(block.textContent ?? '').includes(heading))
|
|
94
|
+
}
|
|
95
|
+
|
|
47
96
|
export function reviewSourceSnippets(markdown: string, item: ReviewItem): ReviewSourceSnippet[] {
|
|
48
97
|
const lines = markdown.split('\n')
|
|
49
98
|
const tokens = parser.parse(markdown, {})
|
|
@@ -56,30 +105,29 @@ export function reviewSourceSnippets(markdown: string, item: ReviewItem): Review
|
|
|
56
105
|
snippets.push(snippet)
|
|
57
106
|
}
|
|
58
107
|
|
|
59
|
-
for (const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
add({ key: `quote-${index}`, label: anchor.heading?.trim() || '正文引用', markdown: quote, ...(exactLine < 0 ? {} : { line: exactLine + 1 }) })
|
|
108
|
+
for (const term of reviewAnchorTerms(item).filter(term => term.kind === 'quote')) {
|
|
109
|
+
if (!normalizeReviewText(markdown).includes(normalizeReviewText(term.value))) continue
|
|
110
|
+
const exactLine = lines.findIndex(line => normalizeReviewText(line).includes(normalizeReviewText(term.value)))
|
|
111
|
+
add({ key: term.key, targetKey: term.key, label: term.label, markdown: term.value, ...(exactLine < 0 ? {} : { line: exactLine + 1 }) })
|
|
64
112
|
}
|
|
65
113
|
|
|
66
|
-
for (const
|
|
67
|
-
const token = tokens.find(candidate => candidate.type === 'inline' && candidate.map && normalizeReviewText(candidate.content).includes(normalizeReviewText(
|
|
114
|
+
for (const term of reviewAnchorTerms(item).filter(term => term.kind === 'acceptance')) {
|
|
115
|
+
const token = tokens.find(candidate => candidate.type === 'inline' && candidate.map && normalizeReviewText(candidate.content).includes(normalizeReviewText(term.value)))
|
|
68
116
|
if (!token?.map) continue
|
|
69
117
|
const [start, end] = token.map
|
|
70
|
-
add({ key:
|
|
118
|
+
add({ key: term.key, targetKey: term.key, label: term.label, markdown: lines.slice(start, end).join('\n').trim(), line: start + 1 })
|
|
71
119
|
}
|
|
72
120
|
|
|
73
121
|
if (snippets.length === 0) {
|
|
74
|
-
for (const
|
|
75
|
-
const headingIndex = tokens.findIndex((token, index) => token.type === 'heading_open' && tokens[index + 1]?.type === 'inline' && normalizeReviewText(tokens[index + 1]!.content).includes(normalizeReviewText(
|
|
122
|
+
for (const term of reviewAnchorTerms(item).filter(term => term.kind === 'section')) {
|
|
123
|
+
const headingIndex = tokens.findIndex((token, index) => token.type === 'heading_open' && tokens[index + 1]?.type === 'inline' && normalizeReviewText(tokens[index + 1]!.content).includes(normalizeReviewText(term.value)))
|
|
76
124
|
const heading = tokens[headingIndex]
|
|
77
125
|
if (headingIndex < 0 || !heading?.map) continue
|
|
78
126
|
const level = Number(heading.tag.slice(1))
|
|
79
127
|
const nextHeading = tokens.slice(headingIndex + 1).find(token => token.type === 'heading_open' && Number(token.tag.slice(1)) <= level && token.map)
|
|
80
128
|
const start = heading.map[0]
|
|
81
129
|
const end = Math.min(nextHeading?.map?.[0] ?? lines.length, start + 9)
|
|
82
|
-
add({ key:
|
|
130
|
+
add({ key: term.key, targetKey: term.key, label: term.label, markdown: lines.slice(start, end).join('\n').trim(), line: start + 1 })
|
|
83
131
|
}
|
|
84
132
|
}
|
|
85
133
|
|