dsh-selection-annotations 0.0.0-stage → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/LICENSE +21 -0
  3. package/README.md +161 -3
  4. package/README.zh-CN.md +161 -0
  5. package/client.js +11136 -0
  6. package/cordis.patch.yml +3 -0
  7. package/icon.svg +7 -0
  8. package/lib/annotations-db.js +1157 -0
  9. package/lib/index.js +1304 -0
  10. package/locale/en.json +6 -0
  11. package/locale/zh.json +6 -0
  12. package/package.json +76 -6
  13. package/scripts/build.mjs +37 -0
  14. package/scripts/check-build.mjs +10 -0
  15. package/src/core/annotation-clipboard.js +93 -0
  16. package/src/core/annotation-utils.js +27 -0
  17. package/src/core/cards.js +502 -0
  18. package/src/core/config.js +91 -0
  19. package/src/core/constants.js +34 -0
  20. package/src/core/draft-codec.js +77 -0
  21. package/src/core/draft-store.js +85 -0
  22. package/src/core/hidden-payload.js +73 -0
  23. package/src/core/image-codec.js +111 -0
  24. package/src/core/jump-icon.js +25 -0
  25. package/src/core/locale.js +59 -0
  26. package/src/core/log.js +19 -0
  27. package/src/core/markdown.js +80 -0
  28. package/src/core/messages.js +311 -0
  29. package/src/core/note-tone.js +77 -0
  30. package/src/core/panel-render.js +315 -0
  31. package/src/core/payload.js +191 -0
  32. package/src/core/preview-bridge.js +216 -0
  33. package/src/core/remote-sync.js +206 -0
  34. package/src/core/scroll-trace.js +177 -0
  35. package/src/core/sent-store.js +148 -0
  36. package/src/core/session.js +60 -0
  37. package/src/core/settings.js +168 -0
  38. package/src/core/side-tab-state.js +30 -0
  39. package/src/core/source-capture.js +530 -0
  40. package/src/core/source-locate.js +220 -0
  41. package/src/core/source-resolve.js +89 -0
  42. package/src/core/styles.js +590 -0
  43. package/src/core/turn-anchor.js +54 -0
  44. package/src/core/util.js +55 -0
  45. package/src/core/uuid.js +23 -0
  46. package/src/core/web-picker.js +426 -0
  47. package/src/entry.js +22 -0
  48. package/src/plugin.js +8706 -0
@@ -0,0 +1,77 @@
1
+ import { dataUrlToFile } from './image-codec.js'
2
+ import { log } from './log.js'
3
+ import { uuidV4 } from './uuid.js'
4
+
5
+ /**
6
+ * 草稿的序列化与恢复。
7
+ * 只保留可序列化字段:liveRange 是活 DOM 对象,恢复时按锚点与引文重建。
8
+ */
9
+ export function createDraftCodec({ t, prefix, maxBytes }) {
10
+ const draftKey = (sessionId) => `${prefix}${sessionId}`
11
+
12
+ function draftItems(items) {
13
+ return items.map((item) => ({
14
+ id: item.id,
15
+ // uuid 在捕获时生成,草稿刷新后必须原样恢复:否则同一条批注会换一个身份。
16
+ ...(typeof item.uuid === 'string' && item.uuid !== '' ? { uuid: item.uuid } : {}),
17
+ number: item.number,
18
+ quote: item.quote,
19
+ note: item.note,
20
+ source: item.source,
21
+ createdAt: item.createdAt,
22
+ // 图片只存压缩后的 data URL:File 与对象 URL 都带不过本地存储。
23
+ images: (Array.isArray(item.images) ? item.images : [])
24
+ .filter((image) => typeof image?.dataUrl === 'string' && image.dataUrl !== '')
25
+ .map((image) => ({ id: image.id, name: image.name, dataUrl: image.dataUrl, bytes: image.bytes })),
26
+ }))
27
+ }
28
+
29
+ function isDraftItem(value) {
30
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
31
+ return typeof value.quote === 'string' || typeof value.note === 'string'
32
+ }
33
+
34
+ function restoreDraftItem(item) {
35
+ const images = (Array.isArray(item.images) ? item.images : [])
36
+ .filter((image) => typeof image?.dataUrl === 'string' && image.dataUrl !== '')
37
+ .map((image) => {
38
+ const file = dataUrlToFile(image)
39
+ return {
40
+ id: typeof image.id === 'string' ? image.id : `img-${Math.random().toString(36).slice(2, 8)}`,
41
+ name: typeof image.name === 'string' ? image.name : t('image.alt'),
42
+ dataUrl: image.dataUrl,
43
+ bytes: Number(image.bytes) || 0,
44
+ file,
45
+ // 恢复后没有对象 URL:直接用 data URL 当缩略图来源。
46
+ url: image.dataUrl,
47
+ }
48
+ })
49
+ return {
50
+ id: typeof item.id === 'string' && item.id !== '' ? item.id : `sa-restored-${Math.random().toString(36).slice(2, 10)}`,
51
+ // 升级前存下的草稿没有 uuid:恢复时补一个,保证发送时数据块里每条都有 uuid。
52
+ uuid: typeof item.uuid === 'string' && item.uuid !== '' ? item.uuid : uuidV4(),
53
+ number: Number.isFinite(item.number) ? item.number : 0,
54
+ quote: typeof item.quote === 'string' ? item.quote : '',
55
+ note: typeof item.note === 'string' ? item.note : '',
56
+ source: item.source ?? { kind: 'dom' },
57
+ createdAt: Number.isFinite(item.createdAt) ? item.createdAt : Date.now(),
58
+ images,
59
+ }
60
+ }
61
+
62
+ /** 超出体积上限时,从最旧的批注开始丢图片(文字永远保留)。 */
63
+ function fitDraftSize(items) {
64
+ let text = JSON.stringify({ version: 1, items })
65
+ if (text.length <= maxBytes) return items
66
+ const next = items.map((item) => ({ ...item, images: Array.isArray(item.images) ? item.images.slice() : [] }))
67
+ for (let i = 0; i < next.length && text.length > maxBytes; i += 1) {
68
+ if (next[i].images.length === 0) continue
69
+ next[i] = { ...next[i], images: [] }
70
+ text = JSON.stringify({ version: 1, items: next })
71
+ }
72
+ if (text.length > maxBytes) log('[selection-annotations] 草稿超出本地存储预算,图片已丢弃、文字保留')
73
+ return next
74
+ }
75
+
76
+ return { prefix, draftKey, draftItems, isDraftItem, restoreDraftItem, fitDraftSize }
77
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * 草稿的本地存储:保存当前会话的批注、读回历史草稿、限制会话数量。
3
+ * 所有"当前批注"通过 getAnnotations() 读取,不持有可变引用。
4
+ */
5
+ export function createDraftStore({ getStorage, codec, getAnnotations, drafts, onSaved, maxSessions, maxItems }) {
6
+ const draftStorage = () => getStorage()
7
+
8
+ /** 只保留最近 maxSessions 个会话的草稿。 */
9
+ function prune(storage) {
10
+ const keys = []
11
+ for (let i = 0; i < storage.length; i += 1) {
12
+ const key = safeStorageKey(storage, i)
13
+ if (typeof key === 'string' && key.startsWith(codec.prefix)) keys.push(key)
14
+ }
15
+ if (keys.length <= maxSessions) return
16
+ const dated = keys.map((key) => ({
17
+ key,
18
+ savedAt: Number(JSON.parse(storage.getItem(key) ?? '{}')?.savedAt) || 0,
19
+ }))
20
+ dated.sort((a, b) => a.savedAt - b.savedAt)
21
+ for (const entry of dated.slice(0, dated.length - maxSessions)) {
22
+ try {
23
+ storage.removeItem(entry.key)
24
+ } catch {
25
+ /* 忽略单条删除失败 */
26
+ }
27
+ }
28
+ }
29
+
30
+ /** 存一份草稿;批注被清空时把这一键一起删掉。 */
31
+ function saveDraft(sessionId) {
32
+ if (typeof sessionId !== 'string' || sessionId === '') return
33
+ const full = codec.draftItems(getAnnotations())
34
+ const items = codec.fitDraftSize(full)
35
+ if (full.length === 0) drafts.delete(sessionId)
36
+ else drafts.set(sessionId, full)
37
+ onSaved(sessionId)
38
+ const storage = draftStorage()
39
+ if (storage === undefined) return
40
+ try {
41
+ if (items.length === 0) {
42
+ storage.removeItem(codec.draftKey(sessionId))
43
+ return
44
+ }
45
+ storage.setItem(codec.draftKey(sessionId), JSON.stringify({ version: 1, savedAt: Date.now(), items }))
46
+ prune(storage)
47
+ } catch {
48
+ /* 配额满或写入被禁:降级为仅内存保存 */
49
+ }
50
+ }
51
+
52
+ /** 读一份草稿:内存优先,其次本地存储;读坏了当没有。 */
53
+ function loadDraft(sessionId) {
54
+ const memory = drafts.get(sessionId)
55
+ if (memory !== undefined) return memory.map(codec.restoreDraftItem)
56
+ const storage = draftStorage()
57
+ if (storage === undefined) return []
58
+ const items = safeParse(storage, codec, sessionId, maxItems)
59
+ if (items === undefined || items.length === 0) return []
60
+ drafts.set(sessionId, codec.draftItems(items))
61
+ return items
62
+ }
63
+
64
+ return { draftStorage, saveDraft, loadDraft }
65
+ }
66
+
67
+ function safeStorageKey(storage, index) {
68
+ try {
69
+ return storage.key(index)
70
+ } catch {
71
+ return undefined
72
+ }
73
+ }
74
+
75
+ function safeParse(storage, codec, sessionId, maxItems) {
76
+ try {
77
+ const raw = storage.getItem(codec.draftKey(sessionId))
78
+ if (raw === null) return []
79
+ const parsed = JSON.parse(raw)
80
+ if (parsed === null || typeof parsed !== 'object' || !Array.isArray(parsed.items)) return []
81
+ return parsed.items.filter(codec.isDraftItem).slice(0, maxItems).map(codec.restoreDraftItem)
82
+ } catch {
83
+ return undefined
84
+ }
85
+ }
@@ -0,0 +1,73 @@
1
+ /** 批注数据块在用户气泡里的隐藏规则。 *
2
+ * 宿主半边在 agent/pre-step 把批注 JSON 作为额外的 text 块并进原用户消息,source 仍是
3
+ * `kind: 'user'` —— 自动审查因此把整段文本当作用户指令。代价是这条用户气泡的正文里会
4
+ * 多出一整段 JSON。这里注册一条 UserText 规则,把 JSON 段(从它开头的 `{` 到消息末尾)
5
+ * 连同它前面的空行折叠成一行占位文字;模型请求与会话记录都不受影响,规则只改渲染。
6
+ *
7
+ * 规则契约见 @deepseek-ai/dsh-client-ui-conversation 的 contract/user-text.ts:
8
+ * - 规则 id 不能是保留字 'text';返回的节点 id 必须是 'text';
9
+ * - 返回的区间必须非空,且 `data.text` 必须等于原文切片;
10
+ * - `data.display` 才是气泡里显示的文本。
11
+ */
12
+
13
+ /** JSON.stringify(payload, null, 2) 里 kind 那一行;用它定位并入块的位置。 */
14
+ const KIND_LINE = '"kind": "dsh-selection-annotations"'
15
+
16
+ /** 并入块之前的空白:宿主固定加 `\n\n`,正文本身也可能以空白结尾。 */
17
+ const BLANK = /\s/
18
+
19
+ /**
20
+ * 折叠后显示的一行占位。N 先取负载里的 `count`;它不是正整数时改用 `annotations`
21
+ * 数组的条数(只认非空数组)。两条都拿不到才退回不带数字的 `【额外批注】`,
22
+ * 不往气泡里写错数。
23
+ */
24
+ function displayOf(payload) {
25
+ const count = payload.count
26
+ if (Number.isInteger(count) && count > 0) return `【额外批注 x ${count}】`
27
+ const annotations = payload.annotations
28
+ if (Array.isArray(annotations) && annotations.length > 0) return `【额外批注 x ${annotations.length}】`
29
+ return '【额外批注】'
30
+ }
31
+
32
+ /**
33
+ * 构造规则。order 取 900:比空白折叠规则(1000/1010)小,同起点时优先隐藏,
34
+ * 不会被折叠规则先把这段文字拆出来。
35
+ */
36
+ export function createPayloadHidingRule() {
37
+ return {
38
+ id: 'selection-annotations:payload',
39
+ order: 900,
40
+ match(text, from) {
41
+ if (typeof text !== 'string' || text === '') return undefined
42
+ const kindAt = text.indexOf(KIND_LINE, from)
43
+ if (kindAt === -1) return undefined
44
+ // JSON 块的开头是它前一个 `{`;从那里到消息末尾就是并入的批注数据。
45
+ const jsonStart = text.lastIndexOf('{', kindAt)
46
+ if (jsonStart === -1 || jsonStart < from) return undefined
47
+ const candidate = text.slice(jsonStart)
48
+ let payload
49
+ try {
50
+ payload = JSON.parse(candidate)
51
+ } catch {
52
+ return undefined
53
+ }
54
+ if (payload === null || typeof payload !== 'object' || payload.kind !== 'dsh-selection-annotations') {
55
+ return undefined
56
+ }
57
+ // 宿主并块时在 JSON 前固定加了 `\n\n`。这里把区间往前吞掉空白,数据前的空白残留不留在正文里;
58
+ // 遇到非空白字符就停,用户正文的最后一行不会被吃进来。
59
+ let start = jsonStart
60
+ while (start > from && BLANK.test(text[start - 1])) start -= 1
61
+ // 气泡(UserMessageBubble)按 pre-wrap 内联渲染节点:display 不带换行就会紧贴正文最后一行。
62
+ // 有正文时前置两个换行,把被吞掉的那一整行空行还回去,占位落在空行下面;
63
+ // 只有 JSON、正文为空时不能前置,否则气泡顶部多出一条空行。
64
+ const ownLine = start > 0 && text[start - 1] !== '\n'
65
+ return {
66
+ id: 'text',
67
+ start,
68
+ end: text.length,
69
+ data: { text: text.slice(start), display: `${ownLine ? '\n\n' : ''}${displayOf(payload)}` },
70
+ }
71
+ },
72
+ }
73
+ }
@@ -0,0 +1,111 @@
1
+ import { safe } from './util.js'
2
+
3
+ export function jpegName(name) {
4
+ const base = typeof name === 'string' && name !== '' ? name : 'image'
5
+ return `${base.replace(/\.[^.]+$/, '')}.jpg`
6
+ }
7
+
8
+ /**
9
+ * 按设置把图片重编码成 JPEG。透明区域先填白 —— JPEG 没有 alpha,不填会变黑。
10
+ * 压缩没变小、或不需要压缩时保留原文件,避免把小图越压越大。
11
+ */
12
+ export async function compressImage(file, settings) {
13
+ if (!settings.compress) return file
14
+ if (typeof createImageBitmap !== 'function') return file
15
+ let bitmap
16
+ try {
17
+ bitmap = await createImageBitmap(file)
18
+ } catch {
19
+ return file
20
+ }
21
+ try {
22
+ if (Math.max(bitmap.width, bitmap.height) <= settings.minSize) return file
23
+ const canvas = document.createElement('canvas')
24
+ canvas.width = bitmap.width
25
+ canvas.height = bitmap.height
26
+ const painter = canvas.getContext('2d')
27
+ if (painter === null) return file
28
+ painter.fillStyle = '#ffffff'
29
+ painter.fillRect(0, 0, canvas.width, canvas.height)
30
+ painter.drawImage(bitmap, 0, 0)
31
+ const blob = await new Promise((resolve) => {
32
+ try {
33
+ canvas.toBlob(resolve, 'image/jpeg', settings.quality)
34
+ } catch {
35
+ resolve(null)
36
+ }
37
+ })
38
+ if (blob === null || blob.size >= file.size) return file
39
+ return new File([blob], jpegName(file.name), { type: 'image/jpeg' })
40
+ } finally {
41
+ safe(() => bitmap.close?.())
42
+ }
43
+ }
44
+
45
+ /**
46
+ * 生成一张小缩略图(data URL)。已提交台账里只放缩略图:原尺寸 data URL 会把存储撑爆,
47
+ * 而清单里需要的是「看得出是哪张图」,点击放大。
48
+ */
49
+ export async function downscaleDataUrl(file, maxSide, quality) {
50
+ if (typeof createImageBitmap !== 'function') return undefined
51
+ let bitmap
52
+ try {
53
+ bitmap = await createImageBitmap(file)
54
+ } catch {
55
+ return undefined
56
+ }
57
+ try {
58
+ const scale = Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height))
59
+ const width = Math.max(1, Math.round(bitmap.width * scale))
60
+ const height = Math.max(1, Math.round(bitmap.height * scale))
61
+ const canvas = document.createElement('canvas')
62
+ canvas.width = width
63
+ canvas.height = height
64
+ const painter = canvas.getContext('2d')
65
+ if (painter === null) return undefined
66
+ painter.fillStyle = '#ffffff'
67
+ painter.fillRect(0, 0, width, height)
68
+ painter.drawImage(bitmap, 0, 0, width, height)
69
+ const blob = await new Promise((resolve) => {
70
+ try {
71
+ canvas.toBlob(resolve, 'image/jpeg', quality)
72
+ } catch {
73
+ resolve(null)
74
+ }
75
+ })
76
+ if (blob === null) return undefined
77
+ return await fileToDataUrl(new File([blob], 'thumb.jpg', { type: 'image/jpeg' }))
78
+ } finally {
79
+ safe(() => bitmap.close?.())
80
+ }
81
+ }
82
+
83
+ export function fileToDataUrl(file) {
84
+ return new Promise((resolve) => {
85
+ try {
86
+ const reader = new FileReader()
87
+ reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : undefined)
88
+ reader.onerror = () => resolve(undefined)
89
+ reader.readAsDataURL(file)
90
+ } catch {
91
+ resolve(undefined)
92
+ }
93
+ })
94
+ }
95
+
96
+ /** 从本地存储恢复的图片只有 data URL:重新构造 File 才能在发送时带上字节。 */
97
+ export function dataUrlToFile(image) {
98
+ if (typeof image?.dataUrl !== 'string' || image.dataUrl === '') return undefined
99
+ return safe(() => {
100
+ const comma = image.dataUrl.indexOf(',')
101
+ if (comma < 0) return undefined
102
+ const header = image.dataUrl.slice(0, comma)
103
+ const match = header.match(/^data:([^;]+)/)
104
+ const mime = match?.[1] ?? 'image/jpeg'
105
+ const binary = atob(image.dataUrl.slice(comma + 1))
106
+ const bytes = new Uint8Array(binary.length)
107
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)
108
+ const name = typeof image.name === 'string' && image.name !== '' ? image.name : 'image.jpg'
109
+ return new File([bytes], name, { type: mime })
110
+ })
111
+ }
@@ -0,0 +1,25 @@
1
+ const SVG_NS = 'http://www.w3.org/2000/svg'
2
+
3
+ /**
4
+ * 「查看出处」图标:13×13,底部一条横线表示目标行,斜箭头从上方落到这条线上。
5
+ * 按钮内容只有这个图标,文字说明走 title / aria-label,不参与排布。
6
+ */
7
+ export function jumpIcon() {
8
+ const svg = document.createElementNS(SVG_NS, 'svg')
9
+ svg.setAttribute('viewBox', '0 0 16 16')
10
+ svg.setAttribute('width', '13')
11
+ svg.setAttribute('height', '13')
12
+ svg.setAttribute('fill', 'none')
13
+ svg.setAttribute('aria-hidden', 'true')
14
+ for (const d of [
15
+ 'M2.8 12.2h10.4',
16
+ 'M7.3 4.1 10.9 11.5M8.9 10.2 10.9 11.5 11.2 9.2',
17
+ ]) {
18
+ const path = document.createElementNS(SVG_NS, 'path')
19
+ path.setAttribute('d', d)
20
+ path.setAttribute('stroke', 'currentColor')
21
+ path.setAttribute('stroke-width', '1.2')
22
+ svg.appendChild(path)
23
+ }
24
+ return svg
25
+ }
@@ -0,0 +1,59 @@
1
+ import { DEFAULT_INSTRUCTION, DEFAULT_INSTRUCTION_EN, LOCALE_NS } from './config.js'
2
+ import { MESSAGES } from './messages.js'
3
+ import { safe } from './util.js'
4
+
5
+ /** 把 {name} 占位符换掉;缺省保留原样,便于发现漏翻的键。 */
6
+ export function formatMessage(template, params) {
7
+ if (typeof template !== 'string') return ''
8
+ if (params === undefined || params === null) return template
9
+ return template.replace(/\{(\w+)\}/g, (match, name) => (name in params ? String(params[name]) : match))
10
+ }
11
+
12
+ /**
13
+ * 文案跟着 DSH 的界面语言走:注册中英词典、绑定翻译函数。
14
+ * 没有 locale 服务(老版本宿主 / 测试台)时保持中文,功能不受影响。
15
+ */
16
+ export function createLocale(ctx) {
17
+ let active = 'zh'
18
+ const service = ctx.locale
19
+ const usable =
20
+ service !== undefined &&
21
+ service !== null &&
22
+ typeof service.register === 'function' &&
23
+ typeof service.bind === 'function'
24
+
25
+ const fallback = (key, params) => formatMessage(MESSAGES[active]?.[key] ?? MESSAGES.zh[key] ?? key, params)
26
+ let translate = fallback
27
+
28
+ if (usable) {
29
+ active = safe(() => service.getSnapshot?.().active) ?? 'zh'
30
+ ctx.effect(() => service.register(LOCALE_NS, MESSAGES), 'selection-annotations: dictionaries')
31
+ translate = service.bind(LOCALE_NS)
32
+ }
33
+
34
+ return {
35
+ get active() {
36
+ return active
37
+ },
38
+ t: (key, params) => translate(key, params),
39
+ defaultInstruction: () =>
40
+ active.toLowerCase().startsWith('en') ? DEFAULT_INSTRUCTION_EN : DEFAULT_INSTRUCTION,
41
+ isDefaultInstruction: (text) => text === DEFAULT_INSTRUCTION || text === DEFAULT_INSTRUCTION_EN,
42
+ syncActive() {
43
+ if (usable) active = safe(() => service.getSnapshot?.().active) ?? active
44
+ },
45
+ /** 语言切换后重绘;返回 effect 的清理函数。 */
46
+ subscribe(onChange) {
47
+ if (!usable || typeof service.subscribe !== 'function') return () => {}
48
+ return ctx.effect(() => {
49
+ const off = service.subscribe(() => {
50
+ active = safe(() => service.getSnapshot?.().active) ?? active
51
+ onChange()
52
+ })
53
+ return () => {
54
+ safe(off)
55
+ }
56
+ }, 'selection-annotations: locale changes')
57
+ },
58
+ }
59
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * 客户端半边只提供 `console.log` 与 `console.error` —— **没有 `console.warn`**。
3
+ * 而且日志本身不该有能力搞坏主流程(一次 console.warn 抛错就会把整条精修链路打断),
4
+ * 所以统一包一层,绝不外抛。
5
+ */
6
+ export const log = (message, ...rest) => {
7
+ try {
8
+ console.log(message, ...rest)
9
+ } catch {
10
+ /* 日志失败无所调*/
11
+ }
12
+ }
13
+ export const warn = (message, ...rest) => {
14
+ try {
15
+ console.error(message, ...rest)
16
+ } catch {
17
+ /* 日志失败无所调*/
18
+ }
19
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * 用 DSH 自己的 MarkdownText 渲染批注答复正文。
3
+ *
4
+ * 这是可选能力:宿主没有暴露 primitives 或 react-dom/client 时退回纯文本,
5
+ * 不影响插件加载。所有挂载出去的 React 根都会在容器离开文档后自动卸掉。
6
+ */
7
+ export function createMarkdown({ h, MarkdownText, createRoot, labels }) {
8
+ const usable =
9
+ MarkdownText !== undefined &&
10
+ MarkdownText !== null &&
11
+ (typeof MarkdownText === 'function' || typeof MarkdownText === 'object') &&
12
+ typeof createRoot === 'function'
13
+ const active = new Map()
14
+ let labelsKey = ''
15
+ let labelsValue = {}
16
+
17
+ function unmount(container) {
18
+ const root = active.get(container)
19
+ if (root === undefined) return
20
+ active.delete(container)
21
+ try {
22
+ root.unmount()
23
+ } catch {
24
+ /* 卸载失败不阻断重绘 */
25
+ }
26
+ }
27
+
28
+ /** 容器已经被移除的根,下一次挂载时顺手卸掉,避免越堆越多。 */
29
+ function prune() {
30
+ for (const [container] of active) {
31
+ if (container.isConnected === false) unmount(container)
32
+ }
33
+ }
34
+
35
+ let pruneTimer = 0
36
+
37
+ /**
38
+ * 卡片是先搭好 DOM 再插进页面的,挂载时容器还没连上文档。
39
+ * 如果每次 mount 都立刻清理「未连接」的根,会把同一批里刚挂好的前一个答复一起卸掉,
40
+ * 表现为一条答复有内容、其余空白。因此把清理推迟到当前这一批插进页面之后。
41
+ */
42
+ function schedulePrune() {
43
+ if (pruneTimer !== 0) return
44
+ pruneTimer = window.setTimeout(() => {
45
+ pruneTimer = 0
46
+ prune()
47
+ }, 0)
48
+ }
49
+
50
+ function mount(container, text) {
51
+ if (typeof text !== 'string') return
52
+ schedulePrune()
53
+ if (!usable) {
54
+ container.textContent = text
55
+ return
56
+ }
57
+ unmount(container)
58
+ const root = createRoot(container)
59
+ active.set(container, root)
60
+ container.setAttribute('data-sa-md', '1')
61
+ const fresh = typeof labels === 'function' ? labels() : {}
62
+ const key = JSON.stringify(fresh)
63
+ if (key !== labelsKey) {
64
+ labelsKey = key
65
+ labelsValue = fresh
66
+ }
67
+ root.render(h(MarkdownText, { text, variant: 'body', labels: labelsValue }))
68
+ }
69
+
70
+ function dispose() {
71
+ if (pruneTimer !== 0) {
72
+ window.clearTimeout(pruneTimer)
73
+ pruneTimer = 0
74
+ }
75
+ for (const [container] of active) unmount(container)
76
+ active.clear()
77
+ }
78
+
79
+ return { mount, prune, dispose, usable }
80
+ }